# Statsig Documentation — Full Corpus # Generated: 2026-11-08T01:32:17Z # Pages: 902 # Source: https://docs.statsig.com/llms.txt > For AI agents: a documentation index is available at [/llms.txt](/llms.txt). Append `.md` to any page URL for markdown, or send `Accept: text/markdown`. ================================================================================ # Statsig Overview URL: https://docs.statsig.com/welcome ================================================================================ # Statsig Overview Statsig is a unified platform for feature flags, A/B testing, and product analytics. ## Quick links ### [Intro to Statsig](https://docs.statsig.com/understanding-platform) Learn more about core concepts and features of Statsig. ### [SDK Quickstart](https://docs.statsig.com/sdks/quickstart) Install the Statsig SDK and get started in minutes. ### [Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction) Read about how to use Statsig with your data warehouse. ## Key features ### [Feature Flags](https://docs.statsig.com/feature-flags/overview) Control feature rollouts and manage deployments safely with feature flags. ### [Experimentation](https://docs.statsig.com/experiments/overview) Run A/B tests and experiments to optimize your product decisions. ### [Product Analytics](https://docs.statsig.com/product-analytics/overview) Analyze user behavior and product metrics with powerful analytics tools. To run an experiment end to end, go to [Experiment process overview](https://docs.statsig.com/experiments/process-overview), which lists each step from sizing the experiment through making a decision. You can use any of these features on top of your own data warehouse through [Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction) with no extract, transform, and load (ETL). Or, you can host your data in [Statsig's infrastructure](https://docs.statsig.com/sdks/quickstart). --- ## Explore SDKs Statsig offers SDKs clients, servers, and integrations. These SDKs accommodate most codebase or deployment preferences: ### Client-side SDKs ### [JavaScript](https://docs.statsig.com/client/javascript-sdk) Browser JavaScript ### [React](https://docs.statsig.com/client/React) Client-Side React ### [React Native](https://docs.statsig.com/client/ReactNative) Bare React Native SDK ### [Next.js](https://docs.statsig.com/client/Next) Next.js SSR, SSG & Client-Side ### [Angular](https://docs.statsig.com/client/Angular) Angular bindings for Javascript SDK ### [Swift](https://docs.statsig.com/client/iosClientSDK) iOS, MacOS, tvOS SDK ### [Android](https://docs.statsig.com/client/Android) Android Kotlin/Java SDK ### [.NET Client](https://docs.statsig.com/client/DotNet) Client SDK for .NET framework ### [Roku](https://docs.statsig.com/client/Roku) Roku Brightscript SDK ### [Unity](https://docs.statsig.com/client/Unity) Unity game engine SDK ### [Dart/Flutter](https://docs.statsig.com/client/Dart) Flutter/Dart Mobile App SDK ### [C++ Client](https://docs.statsig.com/client/CPP) C++ client-side SDK ### Server-side SDKs ### [Node.js](https://docs.statsig.com/server-core/node-core) Node.js server SDK ### [Java](https://docs.statsig.com/server-core/java-core) Java server SDK ### [Python](https://docs.statsig.com/server-core/python-core) Python server SDK ### [Go](https://docs.statsig.com/server/go) Go server SDK ### [Ruby](https://docs.statsig.com/server/ruby) Ruby server SDK ### [.NET Server](https://docs.statsig.com/server-core/dotnet-core) .NET server SDK ### [PHP](https://docs.statsig.com/server-core/php-core) PHP server SDK ### [Rust](https://docs.statsig.com/server-core/rust-core) Rust server SDK ### [C++ Server](https://docs.statsig.com/server-core/cpp-core) C++ server SDK ### Integrations ### [Webflow](https://docs.statsig.com/guides/webflow-sidecar-ab-test) Webflow integration ### [Shopify](https://docs.statsig.com/guides/shopify-ab-test) Shopify integration ### [Segment](https://docs.statsig.com/integrations/data-connectors/segment) Segment data connector ### [Rudderstack](https://docs.statsig.com/integrations/data-connectors/rudderstack) Rudderstack connector ### [Hightouch](https://docs.statsig.com/integrations/data-connectors/hightouch) Hightouch integration ### [mParticle](https://docs.statsig.com/integrations/data-connectors/mparticle) mParticle connector ### [Framer](https://docs.statsig.com/guides/framer-analytics) Framer integration ### [Slack](https://docs.statsig.com/integrations/slack) Slack notifications ### [Integrations](https://docs.statsig.com/integrations/introduction) View more integrations If you don't see the SDK or framework you need, ask directly in the [Slack Community](https://statsig.com/slack). --- ## Learning resources - **Statsig University**: A comprehensive collection of onboarding and training content, including a video [Resource Library](https://learn.statsig.com/pages/resource-library) and a schedule of user training [Webinars](https://learn.statsig.com/events). - **Community**: Join the [Slack Community](https://statsig.com/slack) to connect with other users and get help from the Statsig team. - **Blog**: Stay updated with the latest developments in product experimentation and feature management on the [Blog](https://statsig.com/blog). - **Use Cases**: Discover [Customer Stories](https://statsig.com/customers) to learn why customers love Statsig and how they use it to power their product development. ================================================================================ # Platform Overview URL: https://docs.statsig.com/understanding-platform ================================================================================ # Platform Overview ## What Statsig is used for Use Statsig to ship experiments, measure their impact, and learn from the products you build. The most popular features of Statsig are: - [Feature Flags](https://docs.statsig.com/feature-flags/overview): Expose new features to select user groups, roll them out (or roll them back), and measure their impact on your users. - [Experiments](https://docs.statsig.com/experiments/overview): Run randomized, controlled experiments on different variations of your product and measure the exact impact on your users. Use Experiments to iterate your products towards the right direction. - [Product Analytics](https://docs.statsig.com/product-analytics/overview): Understand the trends of your core business metrics, user behavior, and more. - [Infra Analytics](https://docs.statsig.com/infra-analytics/overview): Monitor and debug service health alongside product outcomes. Ingest metrics and traces with [OpenTelemetry](https://docs.statsig.com/infra-analytics/getting-started), search and group logs, and set alerts to catch regressions. Statsig also offers tools such as [Session Replay](https://docs.statsig.com/session-replay/overview) and [Web Analytics](https://docs.statsig.com/webanalytics/overview/) which gives even more insight into your products. ## Statsig implementations There are two ways you can implement Statsig: - Statsig Cloud - Statsig Warehouse Native (WHN) ### Statsig Cloud Statsig Cloud is a good option for teams that want to get started quickly without managing infrastructure or data warehousing. With Statsig Cloud, you install the Statsig SDK and configure event logging. Statsig handles everything else. - You get feature flags and 2 million metered events for free. - Includes analytics tools such as Dashboards, Metrics Explorer, and Insights. - For pricing details, refer to the [pricing page](https://www.statsig.com/pricing). ### Statsig Warehouse Native (WHN) If your events and metrics already reside in your own data warehouse and you have a dedicated data team, Statsig Warehouse Native (WHN) may be a better option. - WHN lets you host Statsig's Stats Engine within your warehouse, enabling you to calculate metric lifts on your pre-existing datasets. - You can choose between two methods: 1. **Using third-party or your own SDKs**: You handle feature assignment and provide exposure data (you randomize the users). 2. **Using Statsig SDKs**: Statsig handles randomization and writes data into your warehouse. Using third-party or your own SDKs helps you scale analysis, while using Statsig SDKs can significantly increase your experimentation velocity. > **Note:** > > WHN is only available with Enterprise. If you're interested in this option, go to [Statsig Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction) or [schedule a demo](https://www.statsig.com/contact/demo) with the Sales team. ### Choosing between Cloud and Warehouse Native The following criteria can help you decide between the two deployment modes: | Criteria | Cloud-hosted | Warehouse native (WHN) | | --- | --- | --- | | Data source | Primary source of metrics comes from Statsig SDKs or CDPs like Segment. Some metrics can still come from a warehouse. | Warehouse is the primary source of metrics, making WHN ideal when you want to reuse existing data pipelines and computation. | | Analysis needs | Automated experimentation for every experiment and product launch, especially with metrics derived from event logging. | Flexible analysis on top of your existing source of truth metric data. | | Data team involvement | Optional, but recommended for experiment design and readouts. | Necessary for setting up the warehouse connection and configuring core metrics. Not mandatory for every experiment. | | Costs | Total cost of ownership (TCO) is slightly lower. No warehouse costs involved. | TCO includes Statsig license as well as costs incurred for computation and storage in your warehouse. | | Modularity | An integrated end-to-end platform that spans SDKs for feature rollout, experiment execution, analysis, and experiment readouts. | Modular: You can opt for the integrated end-to-end platform or choose to use only a subset of capabilities, such as assignment or experiment analysis. | For a detailed comparison, go to [Statsig Cloud vs Warehouse Native](https://www.statsig.com/blog/deciding-cloud-hosted-versus-warehouse-native-experimentation-platforms). ## Get started with Statsig After you decide which deployment model fits your needs, choose the appropriate getting started guide: - [SDK Getting Started](https://docs.statsig.com/sdks/getting-started) - [Getting Started with Statsig Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/guides/quick-start) With the platform connected, [Experiment process overview](https://docs.statsig.com/experiments/process-overview) lists the steps to run an experiment, from sizing it through making a decision. It applies to both deployment models. > **Info:** > > Have a question or need help? The Statsig Engineering, Data, and Product teams are available in the [Slack community](https://www.statsig.com/slack). ================================================================================ # Support Options URL: https://docs.statsig.com/support-options ================================================================================ # Support Options Statsig uses automated tooling in the Slack Connect channel to triage and prioritize inbound support messages. Actual, full-time engineers handle all support at Statsig. Preferred methods of raising a support request: 1. Slack message through your dedicated Slack channel or [Slack Community](https://statsig.com/slack). 2. Email to support@statsig.com is discouraged but available for sensitive topics. > **Info:** > > Statsig does maintain a monitored support email system. However, Slack is strongly encouraged as the primary channel for support and communication to ensure the fastest possible responses to your questions. ## Community vs Standard vs Premium support Statsig offers different levels of support depending on your pricing tier. Standard or Premium support is only available for [Enterprise plans](https://www.statsig.com/pricing). Statsig standard business hours are 8am-5pm Pacific. | Feature | Community | Standard | Premium | | --- | --- | --- | --- | | Access to Statsig University [certifications](https://learn.statsig.com/certifications) and [webinar](https://learn.statsig.com/events) training sessions | Yes | Yes | Yes | | Access to Statsig's global [Slack community](https://statsig.com/slack) for best practices and peer insights | Yes | Yes | Yes | | Basic assistance during Statsig business hours | Yes | Yes | Yes | | Customer member access to Private Slack channel with Statsig | No | No | Up to 4 members | | Critical/High Priority support of 4-hour response times during Statsig business hours | No | No | Yes | | 24 hour response time for all other inquiries during Statsig business hours | No | No | Yes | | Dedicated Account Manager to support ongoing needs | No | Yes | Yes | | Check-ins with the Statsig team experts to align on goals and progress | No | As needed | Quarterly | | Data science consultations for advisory and experiment reviews | No | No | Up to 4 | | Early access invitation to events hosted by Statsig and partners | No | No | Yes | ## Learning resources - **Statsig University**: A comprehensive collection of onboarding and training content, including a video [Resource Library](https://learn.statsig.com/pages/resource-library) and a schedule of user training [Webinars](https://learn.statsig.com/events). - **Statsig Status Page**: Monitor Statsig's [operational status](https://status.statsig.com/) and configure [Slack alerts](https://docs.statsig.com/integrations/slack) to receive updates. - **Community**: Join the [Slack Community](https://statsig.com/slack) to connect with other users and get help from the Statsig team. - **Blog**: Stay updated with the latest developments in product experimentation and feature management on the [Blog](https://statsig.com/blog). - **Use Cases**: Discover [Customer Stories](https://statsig.com/customers) to learn why customers love Statsig and how they use it to power their product development. ================================================================================ # Experiments Overview URL: https://docs.statsig.com/experiments/overview ================================================================================ # Experiments Overview An experiment in Statsig is a randomized controlled trial (an A/B or A/B/n test). Statsig splits users into a control group and one or more test groups, serves each group a different variant, and reports metric lifts with confidence intervals. Use an experiment when you need to know whether a change caused a metric to move. To roll out a change without measuring variant lift, use a [feature gate](https://docs.statsig.com/feature-flags/overview) instead. This page covers the concepts behind an experiment. For the order of steps to run one, go to [Experiment process overview](https://docs.statsig.com/experiments/process-overview). ![Experiments banner image](https://docs.statsig.com/images/experiments-hero.png) ## Key concepts Every experiment you run on Statsig builds on the following concepts: ### Control variables A control variable is the variable in an experiment that you manipulate to observe its effect on key metrics. In a simple A/B test, the control variable has two values (A and B). The A variable doesn't change. It is the variable against which you evaluate your results. The B variable is a single change you want to evaluate. In A/B testing, you don't want to introduce more than one change in an experiment. More complex experiments have more values (for example, A, B, C, and D). Experiments with more than two values are also known as multivariate experiments. ### Variants A variant is a specific version of the product or feature you're testing. For example, in an A/B test: - **A (Control)**: The current state of the product or feature. - **B (Test)**: The modified state you want to evaluate. This is the change you're testing. Statsig randomly assigns users to each variant. This lets you compare variant performance across equally represented groups. ### Statistical significance [Statistical significance](https://docs.statsig.com/experiments/interpreting-results/read-results) determines whether the observed changes in metrics are likely due to the product change or to random variation. Statsig reports two measures: - **p-value**: The probability of observing the results by chance if the variant had no effect. A p-value below 0.05 typically indicates statistical significance. - **Confidence interval**: The range in which the true effect of a variant lies, with a given level of confidence. If the confidence interval (for example 95%) doesn't overlap zero, the effect is statistically significant. For more information on designing, monitoring, and analyzing experiments, go to [Product Experimentation Best Practices](https://statsig.com/blog/product-experimentation-best-practices). ## Randomization unit The [randomization unit](https://docs.statsig.com/experiments/interpreting-results/participating-units) is the entity, such as a user, a device, or a session, that Statsig randomly assigns to the control group or a test group. Every value of that unit always receives the same variant. The unit is also the basis of measurement for your metrics. You set which entity you want to use for the randomization unit. For example, if you set `userID` as the randomization unit, Statsig buckets each user by `userID` as well as your analysis reports metrics such as revenue per `userID`. You can select one of the following randomization units: ### User identifiers Your application generates a user ID when a user registers or signs in. Use `userID` as the randomization unit for experiments on logged-in experiences. For more details on user identifiers, go to [User Identifiers](https://docs.statsig.com/sdks/user). ### Device identifiers Statsig generates a `stableID`, a device identifier unique to Statsig, for each device that interacts with your product. For example, when a guest opens your product on an iOS device, Statsig creates a `stableID` for that device and tracks the device's actions through it. Use `stableID` as the randomization unit for experiments on unregistered or guest users, such as landing page changes aimed at improving registration rates. For more details, go to [Statsig Guide for Device-Level Experiments](https://docs.statsig.com/guides/first-device-level-experiment). ### Session identifiers Use a session ID as the randomization unit when you test behavior within a single session, such as a guest checkout flow that users typically complete in one visit. Session-based randomization assumes each session is independent of every other session. For best results, choose the randomization unit that matches where users are in your product at the moment when the assignment happens. A mismatch causes unintentional crossovers between groups and skews your results. The following table compares the common randomization units: | Unit | Advantages | Drawbacks | | --- | --- | --- | | `userID` | Persistent across sessions and devices. Statsig assigns the same variant wherever and whenever the user signs in. Doesn't rely on client-side cookies, which users can clear. | Unavailable before sign-in. This means it doesn't fit flows such as landing pages or account creation. Misses pre-login behavior because assignment starts at sign-in. | | `stableID` (device) | Reaches anonymous and first-time visitors who don't have a `userID`. Serves the same variant on a device whether or not the user signs in. Connects logged-out and logged-in activity on that device. | Different devices for the same user may receive different variants. Shared devices treat several users as one. Not suited to long-term studies: clearing cookies or switching devices creates a new `stableID` that isn't linked to the previous one. | | `Session ID` | Scopes the experiment to one visit, so you can measure a self-contained flow without cross-session carryover. Doesn't require a persistent identity. Exposures accumulate quickly, which can shorten the time to statistical power. | Users may remember their experience from one session to another, which breaks the session-independence assumption. Returning users may land in different variants. | ================================================================================ # Experiment Process Overview URL: https://docs.statsig.com/experiments/process-overview ================================================================================ # Experiment Process Overview Running an experiment on Statsig takes four kinds of work: sizing it, configuring it in the console, implementing it in your code, and checking it before and after you start. This page gives the order and links to the page that owns each step. If you'd rather follow one continuous tutorial that includes SDK setup, go to [Run your first experiment](https://docs.statsig.com/guides/abn-tests). You don't need every step. A simple A/B test on an existing metric needs the create, configure, and implement steps; the planning and pre-launch checks matter more as the cost of a wrong result goes up. ## Before you create the experiment | Step | What it covers | | --- | --- | | [Run a power analysis](https://docs.statsig.com/experiments/power-analysis) | Estimate how much traffic and how many days the experiment needs to detect the effect you care about. Run it first, because its output sets the target duration you enter later. | | [Choose a feature gate or an experiment](https://docs.statsig.com/guides/featureflags-or-experiments) | Decide whether you need to measure variant lift at all. A plain rollout doesn't need an experiment. | ## Create and configure | Step | What it covers | | --- | --- | | [Create the experiment](https://docs.statsig.com/experiments/create-new) | Name it, state the hypothesis, pick the randomization ID type, and choose whether it runs in its own layer. Covers user-level, device-level, custom ID, and isolated experiments. | | [Configure the scorecard](https://docs.statsig.com/experiments/setup/scorecard) | Record the hypothesis and choose the primary and secondary metrics that measure it. | | [Set allocation and targeting](https://docs.statsig.com/experiments/setup/allocation-and-targeting) | Choose how many eligible users enter the experiment and which users qualify. | | [Define groups and parameters](https://docs.statsig.com/experiments/setup/groups-and-parameters) | Name the variants and set the values your code reads. Do this before you start: group structure is frozen once the experiment runs. | | [Review the analysis settings](https://docs.statsig.com/experiments/setup/analysis-settings) | Set the target duration from your power analysis and choose the significance level Statsig applies to results. | ## Implement in your code | Step | What it covers | | --- | --- | | [Implement the experiment](https://docs.statsig.com/experiments/implementation/implement) | Read the experiment's parameters with `getExperiment`, log the events your scorecard metrics use, and test each variant in a lower environment. | | [Read parameters, not group names](https://docs.statsig.com/experiments/implementation/getting-group) | Why checking a group name in code is an anti-pattern, and what the diagnostics stream's rules mean. | ## Check before you start | Step | What it covers | | --- | --- | | [Set overrides](https://docs.statsig.com/experiments/setup/overrides) | Force yourself or specific users into each group to confirm every variant works during development. | | [Review the quality score](https://docs.statsig.com/experiments/setup/quality-score) | Catch setup gaps, such as a thin hypothesis, before the experiment starts collecting data. | ## After you start | Step | What it covers | | --- | --- | | [Monitor the experiment](https://docs.statsig.com/experiments/monitor) | Confirm assignment and logging are healthy: checks arriving, unit IDs matching, exposures balanced, no crossover. | | [Read the results](https://docs.statsig.com/experiments/interpreting-results/read-results) | Interpret exposures, the scorecard, and metric lifts once Statsig computes them. | | [End the experiment](https://docs.statsig.com/experiments/ending/ending-experiment) | Ship a group, stop assignments, conclude and defer, abandon, or reset. | ## Reference | Page | What it covers | | --- | --- | | [Manage an experiment](https://docs.statsig.com/experiments/manage) | Operations on the experiment itself: clone, rename, save as template, disable a group, share, export, archive, and delete. Also which tab holds each setting. | | [Layers](https://docs.statsig.com/experiments/layers-overview) | How layers let several experiments share a user population without overlapping. | | [Holdouts](https://docs.statsig.com/experiments/holdouts-introduction) | How to keep a population out of all experiments to measure cumulative impact. | ================================================================================ # Power Analysis URL: https://docs.statsig.com/experiments/power-analysis ================================================================================ # Power Analysis The Power Analysis Calculator is Statsig’s experiment-sizing tool. It uses historical traffic and metric statistics from a population you choose (such as everyone, a targeting gate, a qualifying event, a metric source, or a previous experiment) to estimate the relationship between your planning variables. The Experiment Setup panel recalculates those results against your planned group count, split, significance level, statistical power, CUPED, and multiple-comparison correction without re-running the analysis. You can run it before you create the experiment. Its output is the target duration you enter during setup. You can save the report or attach it to the experiment so the sizing decision stays with the test. After you launch an experiment, use the Power Analysis Calculator to read the confidence intervals on the experiment's _Results_ tab. For more information on experiment results, go to [How to read experiment results](https://docs.statsig.com/experiments/interpreting-results/read-results). ## Variables the calculator estimates The calculator uses historical metric statistics and traffic volume to estimate the relationship between three variables: - **Minimum detectable effect (MDE)**: The smallest change in the metric that the experiment can reliably detect. For example, at 80% statistical power, an effect equal to the MDE has an 80% chance of producing a statistically significant result. For a metric with a mean of 10 page loads per user, a 10% MDE corresponds to one page load per user. - **Duration and exposures**: How long the experiment runs and how many users enter its groups. Longer experiments typically have more observations, which can reduce the detectable MDE. Statsig uses historical traffic to estimate exposures by week. - **Allocation**: The percentage of eligible traffic assigned to the experiment. Increasing allocation generally increases group exposures and reduces the detectable MDE for a given week. Set the planned allocation in _Experiment Setup_ to compare durations and detectable effects. ## Run a power analysis 1. To run a power analysis, first go to _Experimentation > Power Analysis_. 2. On the **Calculator** tab, under _Population_, choose users who resemble those you plan to include in the experiment: - **Everyone**: When available, analysis uses the users for the selected **ID Type**, for example **User ID**. - **Targeting Gate**: Use users who pass a gate that matches your planned targeting. - **Qualifying Event**: Use users who logged a relevant event. Add filters if needed. - **Previous Experiment**: Use a prior experiment with a similar audience. 3. Under _Metrics_, search for and select one or more metrics to analyze. 4. Click **Run Power Analysis**. The analysis runs in the background and can take some time. Statsig notifies you through email when the analysis is ready. You can leave the page or click **Start a new analysis** while it runs. ## Find and attach past analyses Go to _Experimentation > Power Analysis > Past Analyses_ to view previous power analyses. You can attach a previous analyses to your experiment. Attaching an analysis links the sizing decision to the experiment it justifies. The MDE, allocation, power, and duration that you planned for remain visible on the experiment. Attaching analyses to experiments keeps information highlighted and visible. The link works in both directions and is recorded in the experiment’s change log, which gives reviewers and teammates an auditable answer to “why is this experiment running for six weeks?”. It also lets you compare the observed effect against the MDE you sized for rather than rebuilding the estimate from scratch. To attach an analysis to an experiment, do either of the following: - On the _Past Analyses_ tab, click the **⋯** menu on the analysis and select **Attach to Experiment**. - In an open analysis, click **Attach Experiment**. ## Population types The selected population determines the historical traffic and metric statistics used in the estimate. A population that doesn’t match the users your experiment reaches may give misleading results, whether it’s broader or narrower than the planned audience. The following examples describe how populations can affect results: ### Example: checkout flow with the Everyone population You want to test a change in the checkout flow and estimate the MDE for `total_purchases`. If only about 10% of your daily users reach the checkout page and you use the _Everyone_ population, the analysis is likely to: - Overestimate the number of users the experiment gets. - Underestimate the mean value of the `total_purchases` metric if users who do not reach checkout rarely purchase. Those users are included in the historical average but would not enter the planned experiment. - Incorrectly estimate the variance of the `total_purchases` metric because users outside the checkout flow may behave differently. For a checkout experiment, a previous experiment that reached checkout users can provide more representative traffic and metric data. ### Example: onboarding flow with a previous experiment population You want to test a new onboarding flow for everyone who signs up. he only prior experiment available ran on iOS users in a single country. If you use that experiment as the population, the analysis is likely to: Underestimate the number of users the experiment gets, because the prior experiment reached a fraction of your signups. The estimated duration is then longer than the experiment needs. Describe the metric for iOS users in one country. If those users convert differently than the rest of your signups, the MDE estimate doesn’t reflect the planned audience. An estimate that’s too pessimistic can lead you to shelve an experiment that your traffic supports. When no prior experiment matches the audience you plan to reach, use a targeting gate or qualifying event that reproduces the condition users meet to enter the experiment. ## Read the results To open your analysis (if it isn't attached to an experimnet), go to _Experimentation > Power Analysis > Past Analyses_ and select the analysis you want. A completed analysis is arranged to display both the inputs that it used as well as the results. In the results, choose the metric you want summarized in **Target Metric**. The results tabs update to answer different target metric questions. The following sections describe different types of information and analyses provided by the power analysis calculator: ### Week by Week breakdown If you know the available allocation, the _Week by Week breakdown_ tab displays the detectable MDE for each metric over time. Select a week to see its estimated control and test exposures. You can enter a target MDE to highlight weeks that meet your goal. The target is a planning threshold, not a predicted effect. As cumulative exposures grow, the detectable MDE often decreases. Each week's estimate also uses that week's metric statistics. This meanss that the MDE need not decrease every week. ### Scenario Matrix If you know the effect size you want to detect, the _Scenario Matrix_ tab estimates the weeks needed for different group sizes and target MDEs. Select a cell to see the estimated control and test exposures. You can add a custom group size or MDE. Estimates beyond observed history use projected traffic, so treat them as planning estimates. ## Experiment Setup options Use the _Experiment Setup_ section to match the analysis to your planned experiment. Changes recalculate the displayed results from the saved historical analysis. Click **Save Changes** to keep your settings and result selections. To recompute with different populations or metrics, make the edits you want and then click **Re-Run Analysis**. - **Number of Groups**: The total number of groups in the experiment, including control. - **Group Split**: Choose an equal split or set a different control group percentage. - **Allocation (% of eligible traffic)**: The percentage of eligible traffic available to the experiment. - **Significance Level (α)**: The significance level for the test, entered as a percentage. Typically 5%. - **Statistical Power (1-β)**: The statistical power for the test, entered as a percentage. Typically 80%. - **CUPED**: Apply [CUPED variance reduction](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) when available for the selected analysis. - **Stats Method**: **Two sided test** or **One sided test**. - **Apply Bonferroni Correction Per Variant**: Whether to include α correction for multiple tests in the power analysis. Expand _Advanced Statistics_ to inspect the historical metric statistics used in the estimate. ## Calculation details Statsig estimates MDE from the historical metric mean and variance and the expected exposures in each group. The estimate also reflects the power, significance level, test method, and multiple comparison correction selected in _Experiment Setup_. This formula shows a two-sided test with no Bonferroni correction and a positive metric mean. For other settings, Statsig adjusts the statistical threshold and uses the absolute value of the mean. ![MDE calculation for a two-sided test with a positive metric mean](https://docs.statsig.com/images/experiments/power-analysis/mde-formula.png) where: - $Z_{1-\beta}$ and $Z_{1-\alpha/2}$ are the normal quantiles for the statistical power and significance level set in _Experiment Setup_. - $\overline{X}$ is the historical mean of the metric for the selected population. - $var(X)$ is the historical variance of the metric for the selected population. - $N_{test}$ and $N_{control}$ are the expected exposures in the test and control groups. ================================================================================ # Create an Experiment URL: https://docs.statsig.com/experiments/create-new ================================================================================ # Create an Experiment An experiment is a randomized controlled trial: Statsig splits traffic into a control group and one or more test groups, serves each group a different variant, and reports how your metrics moved for each one. Assignment is random but deterministic, so a user sees the same variant every time they're evaluated. Use an experiment when you need evidence that a change caused a metric to move, not just a safe way to ship it. If you want to roll out a single change safely, without measuring variant lift, create a [feature gate](https://docs.statsig.com/feature-flags/overview) instead. For the full order of steps, from sizing the experiment through reading its results, go to [Experiment process overview](https://docs.statsig.com/experiments/process-overview). For a continuous tutorial that also covers integrating the Statsig SDK, go to [Run your first experiment](https://docs.statsig.com/guides/abn-tests). Size the experiment before you create it. A [power analysis](https://docs.statsig.com/experiments/power-analysis) tells you how much traffic and how many days it needs, which is the target duration you set during setup. > **Tip:** > > Experiments behave differently in Warehouse Native. Read about [Configuring Experiments in Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/features/experiment-options). ## User-level experiments To create a user-level experiment: 1. In the Statsig console, go to _Experimentation > Experiments_. 2. Click **Create**. The _Create New Experiment_ dialog opens. 3. Enter an **Experiment Name**. Statsig generates the **Experiment ID** from the name. 4. Click **Add Hypothesis** and describe the change and the result you expect. 5. In the _Targeting_ section, click **Target Applications** and select at least one application. The **Create** button stays disabled until you select one. 6. Optional: In the _Targeting_ section, click **Layer** to add the experiment to an existing layer, or choose **Create new Layer** at the bottom of the list. If you leave **Layer** empty, the experiment runs in its own layer. 7. Optional: In the _Details_ section, set any of the following, then click **Create**: - **Experiment Type**: The default is **Standard A/B/n**. The other options are **Switchback Test** and **Visual Editor**. Refer to [Switchback tests](https://docs.statsig.com/experiments/types/switchback-tests). - **Team**: Assign the experiment to an internal team. - **Tags**: Add tags to organize and filter your experiments. To pre-fill the dialog from a saved configuration, click **Template** at the top of the dialog and choose a template. Refer to [Templates](https://docs.statsig.com/experiments/templates/templates). ## Device-level and custom ID experiments The first control in the _Targeting_ section sets the unit that Statsig randomizes. It shows your project's default ID type. To use a different ID type, such as Stable ID for device-level experiments or a custom ID, use the [user-level experiment steps](#user-level-experiments) with the following change: 1. In the _Targeting_ section, click the ID type button, then choose the ID type you need. The list includes **User ID**, **Stable ID**, and any custom ID types defined in your project. 2. Click **Create**. You can change the ID type after the experiment is created by clicking the edit icon next to **ID Type** in the experiment's _Details_ panel. Then, finish configuring the experiment as you would a [user-level experiment](#user-level-experiments). ## ID mapping capabilities You may want to start an experiment with one ID type (such as `stableID` for device-level targeting) but analyze results using events from another ID type (such as `userID` for logged-in user metrics). **Cloud**: Doesn't support mapping between ID types. Experiments started with `stableID` analyze only events with `stableID`, and experiments started with `userID` analyze only events with `userID`. **Warehouse Native**: Supports ID mapping between different identifier types (for example, `stableID` to `userID`) through Entity Property Source configuration. For advanced ID mapping requirements, consider [Statsig Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction). ## Isolated experiments To create an experiment that excludes users exposed to other experiments, use the [user-level experiment steps](#user-level-experiments) with the following change: 1. In the _Targeting_ section, click **Layer**, then select an existing layer or choose **Create new Layer**. The list shows each layer's ID type and how much of it is already used, for example **(20% used)**. 2. Click **Create**. Then finish configuring the experiment. ## Configure the experiment A newly created experiment isn't running yet. Configure the following on the _Setup_ tab, then start the experiment: 1. [Configure the scorecard](https://docs.statsig.com/experiments/setup/scorecard): Record the hypothesis and choose the primary and secondary metrics that measure it. 2. [Set allocation and targeting](https://docs.statsig.com/experiments/setup/allocation-and-targeting): Choose how many eligible users enter the experiment and which users qualify. 3. [Define groups and parameters](https://docs.statsig.com/experiments/setup/groups-and-parameters): Name the variants and set the values your code reads. 4. [Review the analysis settings](https://docs.statsig.com/experiments/setup/analysis-settings): Set a target duration and choose the significance level Statsig applies to results. If you use Statsig exposure forwarding, review the [group setup guidance](https://docs.statsig.com/experiments/setup/groups-and-parameters) and [warehouse forwarding requirements](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). Each group's traffic share affects forwarding eligibility separately from the experiment's overall allocation. When the setup is complete, [implement the experiment](https://docs.statsig.com/experiments/implementation/implement) in your application, check it with [overrides](https://docs.statsig.com/experiments/setup/overrides) and the [quality score](https://docs.statsig.com/experiments/setup/quality-score), then start it. [Experiment process overview](https://docs.statsig.com/experiments/process-overview) lists every step in order. ## Reusing experiment salts Statsig SDKs use [deterministic hashing](https://docs.statsig.com/sdks/how-evaluation-works) to bucket users. Statsig buckets the same user identically for the same experiment, regardless of where evaluation occurs. Every experiment has its own bucketing salt so that each experiment's user assignment is random. You can copy and set the bucketing salts that Statsig uses for deterministic hashing. This capability is useful for advanced use cases, such as a series of related experiments that need to reuse the control and test buckets. Only Project Administrators can copy bucketing salts. To view or set an experiment's salt: 1. Open the experiment and click the **⋯** menu next to **Start**. 2. Choose **Modify Salt**. The _Experiment Salt_ dialog shows the current **Salt**. 3. Enter the new salt and save it. If your project requires reviews, the button reads **Submit for Review** and the change applies after approval. ================================================================================ # Configure the Experiment Scorecard URL: https://docs.statsig.com/experiments/setup/scorecard ================================================================================ # Configure the Experiment Scorecard An experiment's scorecard documents the hypothesis you're testing and the metrics that measure it. Configure it on the experiment's _Setup_ tab after you [create the initial experiment](https://docs.statsig.com/experiments/create-new). Set the hypothesis before you start the experiment. Statsig computes scorecard metrics daily. Experiments are eligible for advanced treatments such as [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) and [sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing). The _Setup_ page extends the information you entered when you created the experiment. The console splits the scorecard across two sections: _Hypothesis_ and _Metrics_. The results themselves appear under a _Scorecard_ heading on the _Results_ tab. ## Scorecard fields - **Hypothesis**: A rich-text field in the _Hypothesis_ section. Use its toolbar to apply Heading 1, Heading 2, Normal, and Small text styles, bold, italic, underline, strikethrough, links, text color, highlighting, bulleted and numbered lists, text alignment, images, and code blocks. Statsig requires a hypothesis before you can start the experiment. - **Primary Metrics**: The metrics you expect the experiment to directly affect. Statsig requires at least one and allows up to 10. - **Secondary Metrics**: Metrics you monitor for unintended side effects. They aren't the primary focus of the experiment. You can add up to 40. Both metric fields list every metric in the project, but Statsig disables any metric whose ID type doesn't match the experiment's. Keep the primary metric set small. For how a focused scorecard changes the way you read results, go to [Best practices and avoiding false positives](https://docs.statsig.com/experiments/interpreting-results/best-practices). ## Write the hypothesis The _Hypothesis_ field includes a template that you can modify: > We believe that \[change or feature\] for \[user segment\] will \[desired outcome\] because \[reason or insight\]. We will measure success using \[primary metric\], and monitor \[guardrail metrics\] to ensure no negative impact. ## Hypothesis Advisor Hypothesis Advisor gives instant feedback on the hypothesis you enter and flags what's missing. When it's on, the _Hypothesis_ field shows a strength rating such as _Weak_ or _Acceptable_, and a button opens the suggestions. Turn it on from _Settings > Product Configuration > AI Features_, on the _Project_ tab, under _Experiments_. Use the _Prompt for Hypothesis_ field on the same page to set custom requirements you want Hypothesis Advisor to apply (for example, "Strongly recommend that a validation plan be mentioned"). ================================================================================ # Experiment Allocation and Targeting URL: https://docs.statsig.com/experiments/setup/allocation-and-targeting ================================================================================ # Experiment Allocation and Targeting Allocation sets how many users enter the experiment. Targeting sets which users qualify for the experiment. You can change allocation after the experiment starts, but changing targeting mid-run has consequences for the users already exposed. Set both allocation and targeting from the experiment's _Setup_ page. ## Allocation Allocation is the percentage of eligible users that Statsig assigns to your experiment, from 0% to 100% of your total users. Start with a smaller percentage, verify that the experiment is stable, then increase the allocation. You can change the allocation at any time after the experiment starts. > **Tip:** > > Decreasing allocation biases group allocation and pollutes your metric results. Don't decrease allocation without [resetting the experiment](https://docs.statsig.com/experiments/ending/reset). Allocation applies within the experiment's [layer](https://docs.statsig.com/experiments/layers-overview). An experiment can only take allocation the layer still has free. Allocation controls how much eligible traffic enters the experiment. It's separate from the split between groups. For warehouse exposure forwarding requirements, go to [Experiment Groups and Parameters](https://docs.statsig.com/experiments/setup/groups-and-parameters). ## Targeting Targeting limits the experiment to the users who meet the conditions you define. You can set new targeting criteria or reference an existing feature gate. - For basic targeting, leave the default [inline targeting](https://docs.statsig.com/dynamic-config/add-rule). Make sure the **Criteria** field shows **Everyone**. - For more advanced targeting (for example, progressive rollouts), or to keep targeting criteria when you launch the experiment, review how to target [feature gates](https://docs.statsig.com/feature-flags/create). By default, Statsig applies no targeting criteria, and the experiment includes all allocated users within the defined layer or exposed user base. Your targeting choice changes what happens when you ship. For how a targeting gate affects the parameter values users receive after a decision, go to [Make a Decision](https://docs.statsig.com/experiments/ending/make-decision#experiments-with-a-targeting-gate-or-targeting-rules). ================================================================================ # Experiment Groups and Parameters URL: https://docs.statsig.com/experiments/setup/groups-and-parameters ================================================================================ # Experiment Groups and Parameters Groups are the variant labels in the console, such as `Control` or `Test`. Parameters are the values your code reads to change the product or feature's behavior. Configure your parameters before your groups on the experiment's _Setup_ tab. For why your code should read parameters rather than check group names, go to [Read parameters, not group names](https://docs.statsig.com/experiments/implementation/getting-group). ## Add groups and set parameter values Define the parameters first. In the _Groups and Parameters_ section of the _Setup_ tab, select **Add Parameter**, give the parameter a name such as `button_label` or `image_size`, choose its type, then select **Add**. Each group gets a field for that parameter's value. To add a group, select the **+** (_Add Variant_) control to the right of the existing groups. Statsig adjusts the user allocation automatically as you add groups. In the _Groups and Parameters_ section, you can also name, describe, and add variant images for each group. Group names and descriptions are labels that help you identify and compare variants in the Statsig console. Your code reads parameter values through the SDK and never reads group names, so renaming a group doesn't require a code change or change what users see. Settle on group names before you start the experiment: the _Group Name_ field locks once the experiment starts, and group names act as join keys if you forward exposures to a warehouse. Descriptions and variant images stay editable while the experiment runs. ## Warehouse exposure forwarding If you use Statsig exposure forwarding, the daily export excludes groups at 0% or 100% traffic share by default. This is the split between groups, not the experiment's overall allocation. An experiment at 100% overall allocation with a 50/50 group split passes this percentage check. Other forwarding requirements still apply. If you need exposures from experiment groups at 0% or 100%, contact Statsig Support. For details, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). ## What you can change after the experiment starts Set the group structure before you start the experiment. After an experiment starts, you can't add or delete groups, rename them, or change their percentage splits. | Change | After the experiment starts | | --- | --- | | Add or delete a group | Not available | | Change a group's percentage split | Not available | | Rename a group | Not available | | Change a group's description | Available | | Change which group is the control | Available until you ship with holdback | | Replace a group's variant images | Available | | Stop one group from serving its values | Available through [Disable a Group](https://docs.statsig.com/experiments/implementation/disable-group) | | Edit a group's parameter values | Available | | Add a parameter | Available | | Rename, retype, or delete a parameter | Available | To change the group structure of a running experiment, [reset it](https://docs.statsig.com/experiments/ending/reset) or create a new experiment. Both options re-randomize assignments and end the current analysis window. > **Warning:** > > Adding a parameter or editing parameter values during a run can mix materially different treatments into a single scorecard. Parameters define the values the SDK returns. They aren't a result dimension or a version label. If the treatment's meaning changed, start a new iteration instead. ================================================================================ # Experiment Analysis Settings URL: https://docs.statsig.com/experiments/setup/analysis-settings ================================================================================ # Experiment Analysis Settings Two settings control how long an experiment should run and how strictly Statsig reports its results: the target duration and the significance level. Set them both from the experiment's _Setup_ tab. If wanted you can change the significance level from _Experiment Results_. ## Target duration A target duration is optional. It helps you wait long enough for the experiment to reach full power. Your organization sets the default and the minimum, and the console shows the default beneath the field. Use the [Power Analysis Calculator](https://docs.statsig.com/experiments/power-analysis) to determine which target works best for your metrics. Set the target duration from the _Target Duration_ section of the _Setup_ tab, as a number of **Days** or a number of **Unique Exposures**. Days and Unique Exposures are alternatives, not a pair: an experiment carries one target. Setting a new target removes the other. An exposure is a single experimental unit enrolled in the experiment, typically a user or a device for device-level experiments. **Target durations longer than 90 days**: By default, Statsig computes Experiment Results for the first 90 days, though the experiment itself can run longer. Before you set a duration beyond 90 days, consider whether results past that period are still relevant, and whether earlier data might already provide the insights you need. This applies to targets set in Days. The console doesn't raise the 90-day warning when you target unique exposures. After you set the target, you can track progress against the target duration or exposure count in the experiment header. Statsig also notifies you through email and Slack (if integrated) when you reach the target. A target duration doesn't stop the experiment. Reaching the target notifies you, but the run continues until you [end the experiment](https://docs.statsig.com/experiments/ending/ending-experiment) or until a [scheduled stop](https://docs.statsig.com/experiments/ending/schedule-stop) you set runs. ## Advanced Settings The rest of an experiment's analysis options live in the collapsed **Advanced Settings** section at the bottom of the _Setup_ tab, split into _Analysis Configuration_ and _Experiment Population_. ### Analysis Configuration - **Analytics Type**: Choose [Frequentist](https://docs.statsig.com/experiments/advanced-setup/sequential-testing), [SPRT](https://docs.statsig.com/experiments/advanced-setup/sprt), or [Bayesian](https://docs.statsig.com/experiments/advanced-setup/bayesian). Each choice reveals its own settings block. Set it before you start the experiment, because the analytics type locks once the experiment starts. - **Default Confidence Interval**: Choose 80%, 90%, 95%, 98%, or 99%. A lower confidence interval gives faster, more directional results with a higher tolerance for false positives. Alpha is one minus this value. - **Apply Sequential Testing**: Adjusts confidence intervals to reduce false positives when you read results before the experiment reaches its target duration. This option appears only after you set a target, in either days or unique exposures. - **Multiple Hypothesis Corrections**: Expands to five options, described in [Significance level adjustments](#significance-level-adjustments). - **Specify Default Date Filter**: Sets the date range results open with. Without it, results use a cumulative filter over all available days. ### Experiment Population - **ID Type**: The unit Statsig randomizes. Go to [Create an Experiment](https://docs.statsig.com/experiments/create-new#device-level-and-custom-id-experiments). - **Stratified Sampling**: Balances groups on a metric or classification before the experiment starts. Go to [Stratified sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling). - **Configure Allocation Duration**: Stops enrolling new users after a set number of days. This works only when your SDK uses [Persistent Assignment](https://docs.statsig.com/server/concepts/persistent_assignment) for the experiment, or when the experiment runs on a one-time surface such as signup. Without one of those, users enrolled earlier stop receiving their group's experience. ## Significance level adjustments Your organization sets the defaults for confidence interval and multiple-hypothesis correction, so a new experiment may not start at 95% and uncorrected. Change them per experiment under _Advanced Settings_, and change the confidence interval later from the _Comparison & Stats_ panel on the [Results tab](https://docs.statsig.com/experiments/interpreting-results/read-results#significance-level-settings). Selecting **Multiple Hypothesis Corrections** reveals the following, and you can't combine a Bonferroni option with a Benjamini-Hochberg one: - **Apply Bonferroni Correction Per Variant**: Divides the significance level (_α_) by the number of test groups. Applies only with more than two variants. - **Apply Bonferroni Correction Per Metric**: Divides _α_ across the metrics in the scorecard. Set **Primary Metric Weight** to the share of _α_ that goes to primary metrics. For the calculation, go to [Bonferroni correction](https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction). - **Apply Benjamini-Hochberg Procedure Per Variant** and **Per Metric**: Control the false discovery rate instead of the family-wise error rate. For the calculation, go to [Benjamini-Hochberg procedure](https://docs.statsig.com/experiments/statistical-methods/methodologies/benjamini-hochberg-procedure). - **Apply Benjamini-Hochberg Procedure for Primary Metrics Only**: Appears when you select **Per Metric**, and narrows the correction to primary metrics. Clearing **Per Metric** also clears this option. Organization admins set the project-wide defaults for these options, along with limits such as the minimum target duration. For the full list, go to [Experiment policies](https://docs.statsig.com/access-management/org-admin/experiment_policy). ================================================================================ # Implement an Experiment URL: https://docs.statsig.com/experiments/implementation/implement ================================================================================ # Implement an Experiment Implementing an experiment means reading its parameters in your code with `getExperiment`, logging the events your scorecard metrics use, testing each variant in a non-production environment, and starting the experiment. Statsig generates the assignment code and runs the analysis on exposures and events; your code supplies the exposures and events. Use this page after you [create the experiment](https://docs.statsig.com/experiments/create-new). To check a feature gate rather than read experiment parameters, follow the [feature gate SDK guide](https://docs.statsig.com/guides/check-gate) instead. To implement an experiment: 1. Pull the experiment configuration from your application. 2. Log the events you want in your experiment results. 3. Test the experiment in development or another lower environment. 4. Start the experiment. ## Pull experiment configurations from Statsig The following snippet illustraates the shape of an experiment on a product demo flow, where you want to improve conversion to demo completion. Go to the SDK documentation for your language for a complete setup. For full implementation details, go to the [SDK documentation](https://docs.statsig.com/sdks/getting-started) for your language, or work through the guide for [your first A/B test](https://docs.statsig.com/guides/abn-tests). ```javascript const user = { userID: loggedInUserID }; const demoConfiguration = statsig.getExperiment(user, "demo_experience"); // use parameters to control the experience if (demoConfiguration.get("show_banner", false)) { showBanner(); } const title = demoConfiguration.get("title", "Start Demo"); banner.setTitle(title); ``` To get a starter snippet for your experiment, click **View Code Snippets** (the code icon next to **Start**) or **Code Snippet** in the _Groups and Parameters_ section of the _Setup_ tab. In the _Code_ dialog, choose your SDK from **SDK Type**. ![Experiment page header for a Not Started experiment, with the code icon to the right of Start showing a Code Snippets tooltip](https://docs.statsig.com/images/experiments/code-snippet-button.png) ## Log events for your scorecard To get results for the events and metrics you care about, instrument the experience with event logging. You can also set up an [event integration](https://docs.statsig.com/integrations/introduction) or [data warehouse ingestion](https://docs.statsig.com/data-warehouse-ingestion/introduction) to send events to Statsig's stats engine. With the Statsig SDKs, your code might look like this: ```javascript statsig.logEvent(user, "demo_started"); ... statsig.logEvent(user, "demo_completed"); ``` A few events let you measure how users move through a funnel in your product and experiment on those flows to increase conversion. ## Test in a lower environment After you start an experiment, you can't edit the groups without restarting it, because Statsig is already allocating users to each group. Test each experiment in a lower environment before you start it. Testing in a lower environment together with [overrides](https://docs.statsig.com/experiments/setup/overrides) lets you set your own experiment group and test each variant. To enable the experiment in lower environments: 1. On the experiment's _Setup_ tab, click **Test**, then **Enable for Environments**. 2. In the _Enable Experiment in Lower Environments_ dialog, select each environment to test in, for example **Development** or **Staging**. These environments should match your [SDK environment setup](https://docs.statsig.com/guides/using-environments#configuring-environments). 3. Click **Save**. The experiment status changes from _Not Started_ to _Testing_. Refresh the page if the status doesn't update. To stop testing, clear every environment in the same dialog and click **Save**; the status returns to _Not Started_. While the experiment is in _Testing_, the enabled environments evaluate the configuration that is currently saved on the **Setup** tab. Changes you make to groups, parameters, or targeting before you start the experiment take effect in those environments as soon as the SDK fetches new config, so you can iterate on the setup without starting the experiment. Production keeps returning the default values from your code until you click **Start**. The **Test** menu also includes **Override IDs**, which opens the [overrides](https://docs.statsig.com/experiments/setup/overrides) dialog, and **View Exposures**, which opens the exposure stream on the _Diagnostics_ tab. In the results section, you can track cumulative exposures and metric results collected from lower environments. Statsig displays results in aggregate across all lower environments and doesn't distinguish between individual environments. Statsig retains metric data and exposure data even when you repeatedly disable and re-enable the experiment for the lower environment. When you need to re-test the experiment end to end, resalt it to reshuffle users into new groups. While the experiment is in _Testing_, click the **⋯** menu next to **Start**, choose **Resalt**, then click **Confirm**. ![Open overflow menu beside Start with Resalt highlighted, alongside Clone, Rename, Modify Salt, Archive, and Delete](https://docs.statsig.com/images/experiments/lower_environment_resalt.png) ## Start the experiment **Start** stays disabled until the setup is complete, for example until the experiment has at least one primary metric and at least one parameter in _Groups and Parameters_. Hover over **Start** to see which setup items are missing. After the setup is complete and you've tested the experiment in a lower environment, click **Start**. Your experiment is immediately live in production. ================================================================================ # Read Parameters, Not Group Names URL: https://docs.statsig.com/experiments/implementation/getting-group ================================================================================ # Read Parameters, Not Group Names Statsig experiments differentiate their groups through parameters, not group names. Every group defines a value for the same parameters, your code reads those values with `experiment.get("param", default)`, and the console blocks **Start** until the experiment defines at least one parameter. Checking a group name in code instead is an anti-pattern: it's fragile, it forces a code change for every new variant, and it borrows a field that exists for diagnostics. Group names belong in the console, where comparing "Sorted Long List" with "Default Search Results" is easier to discuss than the `sorted = true, length = 10` parameters they represent. ## Example: group names compared with parameters A function that checks experiment groups might look like this: ```ts async function getSearchItems(user: StatsigUser, searchTerm: String): String[] { const results = index.get(searchTerm); const experiment = statsig.getExperimentSync(user, 'search_results'); // NOTE - these APIs don't actually exist - this is for the sake of an example if (experiment.groupName === 'Sorted Long List') { return results.sort().slice(10); } else if (experiment.groupName === 'Sorted Short List') { return results.sort().slice(3); } else { return results; } } ``` This code has two problems: 1. It's fragile. If the group name in code doesn't match the name in the Statsig console, Statsig doesn't return the correct experience. 2. It's static. Adding another experiment group, such as an "Unsorted long list", requires a code change. The same function using experiment parameters directly: ```ts async function getSearchItems(user: StatsigUser, searchTerm: String): String[] { let results = index.get(searchTerm); const experiment = statsig.getExperimentSync(user, 'search_results'); results = experiment.get("sorted", false) ? results.sort() : results; const numItems = experiment.get("length", 0); return numItems > 0 ? results.slice(numItems) : results; } ``` This code doesn't reference any group names. To test an unsorted list of 5 items against a sorted list of 20 items, configure the groups in the Statsig console and name them however you want; the same code handles every combination of `sorted` and `length`. ## Diagnostics rule meanings The _Diagnostics_ tab helps you debug your integration and understand which group Statsig assigns a user to. The _Rule_ column of the _Exposure Stream_ and the result of **Check Group for a User** use the following values. | Rule | Meaning | | --- | --- | | Not started | You haven't started the experiment, so Statsig hasn't determined the allocation groups yet. | | Holdout | The user is in a holdout that this experiment references, so they aren't in the experiment. | | Layer Assignment | Statsig doesn't allocate the user to this experiment because it buckets them into a different part of the layer. | | Failed targeting | The user doesn't meet the requirements for the targeting gate or inline targeting. | | Not Allocated | Statsig doesn't allocate the user to this experiment because they don't meet the rollout percentage. | | `{group name} ({override type})` | An experiment override forced the user into the given group, for example `Test (ID Override)`. | | `{group name}` | Statsig bucketed the user into this experiment group. | | Abandoned | You selected the control group in **Make Decision** and abandoned this experiment. | | `{group name}` (Launched) | You selected this group as the launch group in **Make Decision**, so the user sees the launched experience. | ================================================================================ # Experiment Overrides URL: https://docs.statsig.com/experiments/setup/overrides ================================================================================ # Experiment Overrides Experiment overrides force individuall chosen users into specific experiment groups instead of a randomly assigned group. When your app fetches an experiment's parameters, Statsig first checks for overrides. It then, if a user is assigned into an ovrride group, returns that override group immediately. You can use an override during development to put yourself into each group and confirm that every variant works. To test each variant across a whole environment without pinning individual users, [enable the experiment for a lower environment](https://docs.statsig.com/experiments/implementation/implement#test-in-a-lower-environment). Statsig supports two kinds of overrides: - **ID Overrides**: Force specific unit IDs, such as a user ID or stable ID, into a group. - **Conditional Overrides**: Force every user who passes a feature gate or segment into a group. ## How Statsig evaluates overrides - Statsig evaluates ID overrides first, then conditional overrides from top to bottom. - The ID type of an ID override doesn't have to match the experiment's ID type. - Each override applies to either one, single, environment or to all environments. - For experiments in a layer, set overrides at the layer level. Layers make their experiments mutually exclusive which lets Statsig override a user into a single experiment within a layer. - By default, Statsig excludes overridden users from experiment results, because those users aren't randomized. To count them, select **Include Overrides in Results** at the bottom of the dialog. Statsig includes only overrides whose ID type matches the experiment's ID type. - Add overrides before the experiment starts, or at least before a user's first exposure. Adding a large number of users to an override can reduce the reliability of your results. > **Warning:** > > If you add an override after Statsig has already exposed a user to the experiment, Statsig honors the override but doesn't exclude that user from experiment results. Statsig keeps attributing the user's events and metrics to the group it first assigned them to, even though the user now sees a different group. This can pollute your results. The impact depends on how many users fall into this category. ## Open the Manage Overrides dialog 1. In the [Statsig console](https://console.statsig.com), go to _Experimentation > Experiments_ and select the experiment. 2. On the _Setup_ tab, scroll to _Groups and Parameters_ and click **Manage Overrides**. You can also click **Test**, then **Override IDs**. The button shows the number of saved overrides, for example **Manage Overrides (1)**. ## Add an ID override 1. [Open the Manage Overrides dialog](#open-the-manage-overrides-dialog) and select the **ID Overrides** tab. 2. Click the **IDs** field, enter or paste one or more IDs, and press Enter after each one. 3. Choose the **Experiment Group** to force these IDs into. 4. Choose the **ID Type** of the IDs you entered, for example **User ID** or **Stable ID**. 5. Choose the **Environment** where the override applies, or keep **All Environments**. 6. Click **Add**. The override appears in the table with its IDs, group, unit ID type, and environment. 7. Click **Save**. To change the group for an existing ID override, use the **Group** dropdown in its table row, then click **Save**. To find an override in a long list, use the **Search** field above the table. ## Add a conditional override 1. [Open the Manage Overrides dialog](#open-the-manage-overrides-dialog) and select the **Conditional Overrides** tab. 2. Click **Add Override**. 3. In the new row, choose **Gate** or **Segment**, then select the gate or segment. 4. Choose the environment where the override applies, or keep **All Environments**. 5. Choose the experiment group to force matching users into. 6. To add more conditions, click **Add Another Override**. Drag rows by their handle to change the order; Statsig evaluates them from top to bottom. 7. Click **Save**. ## Delete an override Remove an override you no longer need so that Statsig evaluates the experiment's rules as normal. 1. [Open the Manage Overrides dialog](#open-the-manage-overrides-dialog) on the experiment or layer that contains the override. 2. On the **ID Overrides** or **Conditional Overrides** tab, click the trash can icon next to the override. 3. Click **Save**. ## Test an override Confirm that Statsig returns the overridden group for a user: 1. On the experiment, open the _Diagnostics_ tab and click **Check Group for a User**. 2. In the _Evaluate_ dialog, edit the user object. For an ID override, set the ID field to an overridden ID, for example `"userID": "my-test-user"`. For a conditional override, add the properties a user needs to pass the gate or segment. 3. Read the result below the editor. An overridden user shows the group name followed by the override type, for example **Test (ID Override)**. ================================================================================ # Experiment Quality Score URL: https://docs.statsig.com/experiments/setup/quality-score ================================================================================ # Experiment Quality Score The Experiment Quality Score is a percentage that Statsig computes for each experiment from a weighted set of setup checks. These checks can include hypothesis length and balanced exposures. The score appears in the experiment's _Details_ panel as a value out of 100. The scores are color-coded: green, yellow, or red according to threshold values. Use the Experiment Quality Score to catch setup gaps before you start an experiment and to find systematic issues when you compare scores across your experimentation program. To diagnose problems in a running experiment, such as a sample ratio mismatch, use [experiment health checks](https://docs.statsig.com/experiments/monitor). ## Enable and configure the quality score Only Project Admins can change the quality score configuration. 1. Go to _Settings > Product Configuration > Experimentation_ and open the **Project** tab. 2. In the _Experiment Quality Score_ row, click **Edit**. Statsig evaluates experiments against a list of pre-defined assessment criteria. Each criterion has a default weight. You can change each weight to match your organization's needs. ![Experiment quality score configuration interface showing multiple criterion such as Hypothesis Lenght and each critera's associated weight](https://docs.statsig.com/images/snippets/quality-score/91fea3df-0dae-4d0a-ada8-1c1c9313e60e.png) When Statsig computes a score, it skips checks that aren't ready yet and renormalizes the remaining weights to 100%. For example, if the experiment hasn't started, the Balanced Exposures check isn't ready and Statsig ignores it. Statsig omits checks with a weight of 0 from the score card entirely. ## Customize checks through the Console API If you need checks that the defaults don't cover, different requirements per product team, or different thresholds, you can manage or modify the checks through the Statsig Console API. For example, you might require hypotheses to be at least 200 characters and contain a link to an external planning doc. Run a POST or PATCH on the [`console/v1/experiments` endpoint](https://docs.statsig.com/api-reference/experiments/partially-update-experiment) to update individual scores on any experiment. Include an existing check with a weight of 0 to remove it, so the list contains only the checks you need. For example, run a PATCH on an experiment with this payload: ```json { "manualQualityScores": [ { "criteriaName": "HYPOTHESIS_LENGTH", "criteriaDescription": "Check passed", "status": "PASSED", "score": 0, "weight": 0 }, { "criteriaName": "MyCompany's Hypothesis Check", "criteriaDescription": "Has Internal URL and > 200 Chars", "status": "PASSED", "score": 100, "weight": 100 }, { "criteriaName": "Naming", "criteriaDescription": "Experiment prefixed with team name", "status": "FAILED", "score": 0, "weight": 100 } ] } ``` This payload: - Drops the original `HYPOTHESIS_LENGTH` check. - Keeps the other original checks with their weights. - Adds a new check, `MyCompany's Hypothesis Check`, for custom logic on the hypothesis. - Adds a new check, `Naming`, for custom logic on the name. Statsig normalizes the remaining weights. If the original `HYPOTHESIS_LENGTH` check had a weight of 10, the total weight becomes 290 and Statsig normalizes scores accordingly. If all non-custom checks pass, the score is 190/290, or about 66%. To apply custom checks across all experiments: 1. Use the Console API's `experiments/get` endpoint to pull all experiments. 2. For each experiment, run your custom logic and patch the results. ## View quality scores Quality scores appear in the _Details_ panel. Statsig evaluates each applicable check and includes it in the displayed score. Hover over the score to see the breakdown. The table lists each criterion, its passing value, and its weight. For example, _Hypothesis Length_ passes at 50 or more characters, and _# of primary metrics_ passes with 1 to 5 primary metrics. Statsig color-codes the score by the threshold it reaches. | Score | Color | | --- | --- | | 85% or higher | Green (passing) | | 50% to 84% | Yellow (warning) | | Below 50% | Red (error) | You can also retrieve quality scores through the Console API for bulk analysis. ================================================================================ # Monitor an Experiment URL: https://docs.statsig.com/experiments/monitor ================================================================================ # Monitor an Experiment Statsig runs health checks on every live experiment: SDK checks arriving, unit IDs matching, exposures balanced with no sample ratio mismatch (SRM), and no crossover units. Review the checks after you launch the experiment and again before you read its results. Use this page to find out whether assignment and logging are correct. To interpret metric lifts, go to [How to read experiment results](https://docs.statsig.com/experiments/interpreting-results/read-results). To clone, rename, archive, or otherwise operate on the experiment itself, go to [Manage an Experiment](https://docs.statsig.com/experiments/manage). ## Experiment health checks 1. Go to _Experimentation > Experiments_ and select the experiment you want to inspect. 2. In the _Details_ panel, find the health status badge next to the quality score, for example **Healthy** or **Unhealthy**. 3. Hover over the badge to see the _Experiment Health Check_ summary, then click **View Details**. Alternately, open the _Diagnostics_ tab, which leads with the _Experiment Health Check_ section. A warning icon on the _Diagnostics_ tab label also signals a failing check. Select a check to read its status, such as _FAILED_, and an explanation of what triggered it. The checks shown depend on the experiment's setup and how long it's been running. The console organizes each check by its current state. For example: _Checks not yet detected_ or _Pulse metrics available_. Common health checks include: - **Checks detected**: Verifies that the SDK is reporting config checks shortly after launch. _Checks not detected recently_ means the experiment previously recorded exposures but none in the last 24 hours. - **Valid unit type**: Confirms that checks include the experiment's configured ID type. - **Event metrics have data**: Ensures that events carry the same unit ID as exposures. This lets Statsig compute metrics. This check often surfaces problems when downstream tooling, such as Segment, omits `stableID` or custom IDs. - **Pulse metrics available**: Indicates that results are ready (typically the day after launch). - **Exposures are balanced**: Runs a [chi-squared test](https://www.jmp.com/en/statistics-knowledge-portal/linear-models/chi-square-test) for sample ratio mismatch (SRM). Occasionally, warnings occur because of randomness, but persistent red alerts point to assignment or logging issues. Refer to [SRM thresholds](#srm-thresholds) for more information. - **Crossover units detected**: Highlights units exposed to more than one group, when they exceed 0.1% of exposed units. Statsig Cloud keeps these units in both groups because the SDK rarely produces crossovers, and flags them so you can address the root cause. Refer to [Crossover troubleshooting](#crossover-troubleshooting). - **Default value type mismatch**: Warns if an experiment's fallback default value type disagrees with the parameter definition. - **Group Assignment Health**: Surfaces unexpected assignment reasons (for example, `Uninitialized` or `InvalidBootstrap`). Click **View Assignment Reasons** to see the hourly breakdown. - **Differential Impact Detection**: Reports when Statsig has finished checking whether a group of users responds to the treatment differently from the rest. Refer to [Differential impact detection](https://docs.statsig.com/experiments/exploring-results/differential-impact-detection). ### SRM thresholds The Exposures are balanced check sets its status from the chi-squared p-value and the absolute deviation from the expected split. | p-value | Absolute deviation | Status | | --- | --- | --- | | Between 0.001 and 0.01 | Any | Warning (yellow) | | Less than 0.01 | Less than 0.1% | Warning (yellow) with low expected impact | | Less than 0.001 | 0.1% or more | Alert (red) that requires investigation | To diagnose and resolve SRM, go to [Managing SRM](https://docs.statsig.com/experiments/monitoring/srm). ## Guardrail metric alerts The _Diagnostics_ tab lists the metric alerts attached to this experiment under _Guardrail Metric Alerts_. It displays each metric's current status and when it last triggered. When an alert generates, a banner appears at the top of the experiment and a matching card appears on the _Results_ tab. Select **Resolve** to clear an alert and record why. For more information, go to [Rollout alerts](https://docs.statsig.com/metrics/rollout-alerts), which covers how to create an alert as well as how Statsig evaluates your alerts. ## Crossover troubleshooting A crossover unit is a unit that logged exposures to more than one group of the same experiment run. Statsig can't attribute that unit's behavior to a single variant. The _Crossover units detected_ check appears when crossover units exceed 0.1% of exposed units. ### How Statsig Cloud handles crossover units Statsig Cloud keeps a crossover unit in both groups instead of discarding it. Statsig SDKs produce crossovers rarely, and the units that do cross over tend to cross in every group rather than in one. Including them dilutes the measured effect slightly instead of biasing it toward one group. Below 1%, treat the check as a prompt to find the root cause, not as a reason to discard the readout. Above 1%, contact Statsig in Slack: a rate that high usually points to an implementation problem. Warehouse Native drops crossover units from the analysis instead of keeping them, because it often reads exposures from another assignment service where crossover rates run higher. For that behavior and its thresholds, go to [Monitor an experiment](https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment) in the Warehouse Native documentation. ### Common causes of crossover units | Cause | What to look for | What to do | | --- | --- | --- | | The client bootstrapped with values generated for a different unit | Exposures with the `BootstrapStableIDMismatch` reason in the exposure stream | Pass `getClientInitializeResponse` the same `stableID` the client uses at runtime. Go to [BootstrapStableIDMismatch](https://docs.statsig.com/sdks/debugging#bootstrapstableidmismatch). | | A client SDK and a server SDK both evaluate the same experiment for the same user | One unit ID under two groups, with exposures logged from two SDK types | Evaluate an experiment for a given user in one place. If both SDKs must evaluate it, confirm that a configuration update reached both before you read results. | | A client holds cached values from before a configuration change | Crossover that starts right after you change allocation, targeting, or the experiment's salt | Avoid changing a running experiment's configuration. To change group structure, [reset the experiment](https://docs.statsig.com/experiments/ending/reset) instead. | ### What doesn't count as crossover Two patterns look like crossover in the exposure stream, but neither triggers the check: | Pattern | Why it isn't crossover | | --- | --- | | Exposures with the `Unrecognized` reason | The definition was missing from the SDK's payload, so the exposure carries no group. A unit that returns the default value on one check and a real variant on the next has one analyzed exposure, not two conflicting ones. Go to [Evaluation reasons](https://docs.statsig.com/sdks/debugging#evaluation-reasons). | | Exposures from an earlier run | The check compares exposures within the current analysis window. [Resetting an experiment](https://docs.statsig.com/experiments/ending/reset) generates a new salt and starts a new window, so a unit that was in control before the reset and in test after isn't flagged. Statsig doesn't exclude those units from the new run's analysis. | ### Prevent crossover with persistent assignment Configure [persistent assignment](https://docs.statsig.com/server/concepts/persistent_assignment) on a supported server SDK before you start the experiment. Persistent assignment saves each unit's evaluation the first time the SDK evaluates it, then loads that saved evaluation on later calls. The unit keeps its group even when the experiment's configuration changes, which is the only way to keep an assignment stable through a configuration change. If you can't pinpoint the cause, contact Statsig in Slack for help. ## Exposure streams The _Exposure Stream_ section on the _Diagnostics_ tab lists the most recent exposures for the experiment. Use it to confirm that checks arrive, that targeting resolves the way you expect, and that your SDKs evaluate against current configuration. Select **Show non-production logs** to include checks from non-production environments. ### Read an exposure row | Column | What it shows | | --- | --- | | _Eval Time_ | When the SDK last applied the configuration it used for this check. It isn't the moment the SDK evaluated the unit. | | _Received_ | The exposure's own time, corrected for clock skew. Read this column as when the evaluation happened. | | ID column | The unit Statsig evaluated. The heading is the experiment's ID type, such as `userID`, `stableID`, or a custom ID. | | _Rule_ | The rule that matched, such as _Failed targeting_. For each value, go to [Diagnostics rule meanings](https://docs.statsig.com/experiments/implementation/getting-group#diagnostics-rule-meanings). | | _Reason_ | The evaluation reason, such as `Network:Recognized`. For each value, go to [Evaluation reasons](https://docs.statsig.com/sdks/debugging#evaluation-reasons). | | _LCUT_ | Last Config Updated Time: the most recent configuration change reflected in the SDK. Go to [Evaluation times](https://docs.statsig.com/sdks/debugging#evaluation-times). | | _Stale_ | `Yes` when the evaluating process used an older version of the experiment than the console holds. The _Rule_ value also carries a `(Stale version)` suffix. | | _User Properties_ | The user object your code sent with the check. | _Eval Time_ moves only when an SDK picks up a configuration change, so the gap between it and _Received_ widens the longer a project goes without one. Don't read that gap as delivery latency: neither column reports how long Statsig took to ingest the exposure. To measure SDK upload latency, turn on [SDK debug logging](https://docs.statsig.com/sdks/debugging) instead. ### Query the stream The _Query Exposures_ panel beside the table controls what the stream returns. Choose a time range, select **+** next to _Filters_ to filter on a column or user property, then select **Apply**. The time range reaches back 7 days at most. Calendar days older than that aren't selectable, and presets wider than 7 days don't appear. This limit applies to row-level exposure queries in the console for every project, and no setting extends it. It bounds the query, not your data. ### What the exposure stream can't tell you Each query returns at most 100 rows, newest first, however wide the time range. Treat the stream as a recent sample for debugging rather than an export. It also lists every evaluation that reached Statsig, including rows that [bot filtering](https://docs.statsig.com/experiments/monitoring/bots) later removes, so it isn't the analyzed population. A row missing here is weaker evidence than a unit missing from your results. For exposure counts over a longer window, select **View in Metrics Explorer** in the _Exposure Stream_ header. That view aggregates exposures and the 7-day limit doesn't apply to it. ## Cumulative exposures To track growth per variant: 1. Open the _Results_ tab. 2. Find the _Cumulative Exposures_ card below the hypothesis. It shows the total exposures and each group's share. 3. Click **See More** to expand the chart. **Figure: Cumulative exposures by group** Assignment pauses between July 12 and July 20, so the stack holds flat near 20,000 units before climbing again to 35,774 across three evenly split groups. Stacked area chart. X axis: Date. Y axis: Cumulative exposures. | Date | Control | Test A | Test B | | --- | --- | --- | --- | | 2026-07-08 | 0 | 0 | 0 | | 2026-07-09 | 3317 | 3291 | 2995 | | 2026-07-10 | 5276 | 5272 | 5140 | | 2026-07-11 | 6321 | 6424 | 6132 | | 2026-07-12 | 6696 | 6762 | 6508 | | 2026-07-13 | 6711 | 6777 | 6526 | | 2026-07-14 | 6727 | 6791 | 6542 | | 2026-07-15 | 6741 | 6807 | 6559 | | 2026-07-16 | 6755 | 6823 | 6577 | | 2026-07-17 | 6771 | 6839 | 6593 | | 2026-07-18 | 6784 | 6851 | 6606 | | 2026-07-19 | 6795 | 6864 | 6618 | | 2026-07-20 | 6813 | 6883 | 6636 | | 2026-07-21 | 8731 | 8749 | 8671 | | 2026-07-22 | 8880 | 8932 | 8853 | | 2026-07-23 | 9052 | 9090 | 9019 | | 2026-07-24 | 9214 | 9257 | 9212 | | 2026-07-25 | 9343 | 9405 | 9344 | | 2026-07-26 | 9490 | 9544 | 9477 | | 2026-07-27 | 9651 | 9715 | 9688 | | 2026-07-28 | 9798 | 9890 | 9868 | | 2026-07-29 | 9951 | 10060 | 10042 | | 2026-07-30 | 10104 | 10244 | 10220 | | 2026-07-31 | 10278 | 10416 | 10376 | | 2026-08-01 | 10425 | 10548 | 10503 | | 2026-08-02 | 10564 | 10688 | 10632 | | 2026-08-03 | 10734 | 10861 | 10841 | | 2026-08-04 | 10908 | 11018 | 11019 | | 2026-08-05 | 11060 | 11189 | 11184 | | 2026-08-06 | 11216 | 11348 | 11344 | | 2026-08-07 | 11383 | 11498 | 11496 | | 2026-08-08 | 11527 | 11637 | 11635 | | 2026-08-09 | 11645 | 11786 | 11779 | | 2026-08-10 | 11839 | 11951 | 11984 | The chart shows how many units entered each group over time, so you can identify ramp issues early. A band that flattens means the experiment stopped assigning units, and a band that outpaces the others points at an uneven split. ================================================================================ # Manage an Experiment URL: https://docs.statsig.com/experiments/manage ================================================================================ # Manage an Experiment Every experiment in the Statsig console has a three-dot actions menu for operations on the experiment itself as well as a detail page that organizes its configuration and analysis into tabs. Use this page to perform an operation on an experiment or to find which tab holds a setting. To find out how a running experiment is doing instead, such as whether its health checks pass, go to [Monitor an Experiment](https://docs.statsig.com/experiments/monitor). To create an experiment, go to [Create an Experiment](https://docs.statsig.com/experiments/create-new). ## Experiment actions The three-dot (**...**) menu in the experiment header holds the following operations. Which entries appear depends on the experiment's state. | Action | What it does | When it's available | | --- | --- | --- | | **Add Decision Framework** | Attaches a [decision framework](https://docs.statsig.com/experiments/templates/decision-framework) that defines success criteria and ship-versus-iterate logic. | Before the experiment starts | | **Clone** | Copies the experiment. A clone inherits the source experiment's notes text, so review and replace those notes before you use the new experiment. | Any time | | **Rename** | Changes the experiment's name. | Any time | | **Save as Template** | Saves the experiment's configuration as a reusable [template](https://docs.statsig.com/experiments/templates/templates), which then appears as a **Template** option when you create an experiment. | Before the experiment starts | | **Disable a Group** | Turns off one group while the others keep running. Go to [Disable a Group](https://docs.statsig.com/experiments/implementation/disable-group). | After the experiment starts | | **Share Link** | Copies a shareable link to the experiment. | Any time | | **Modify Salt** | Copies and sets the salt used for deterministic hashing. Refer to [Reusing experiment salts](https://docs.statsig.com/experiments/create-new#reusing-experiment-salts). | Project Administrators only | | **Export Report** | [Exports a report](https://docs.statsig.com/experiments/interpreting-results/export) of the experiment's results. | After the experiment has data | | **Archive** | [Archives the experiment](https://docs.statsig.com/experiments/ending/ending-experiment#archive-an-experiment) to preserve its history and results and make it read-only. | Any time | | **Delete** | Deletes the experiment. | Any time | The header also contains the Open History section, which lists every committed change to the experiment, and View Code Snippets. To stop, ship, reset, or abandon an experiment rather than operate on its record, go to [Ending an Experiment](https://docs.statsig.com/experiments/ending/ending-experiment). ## Where each setting lives The experiment detail page organizes configuration and analysis into the following tabs: | Tab | What it holds | | --- | --- | | _Setup_ | The experiment's [metrics](https://docs.statsig.com/experiments/setup/scorecard), [allocation and targeting](https://docs.statsig.com/experiments/setup/allocation-and-targeting), [groups and parameters](https://docs.statsig.com/experiments/setup/groups-and-parameters), and [analysis settings](https://docs.statsig.com/experiments/setup/analysis-settings). | | _Diagnostics_ | Health checks, guardrail metric alerts, and the _Exposure Stream_. Go to [Monitor an Experiment](https://docs.statsig.com/experiments/monitor). | | _Results_ | Exposures and scorecard metric lifts. Go to [How to Read Experiment Results](https://docs.statsig.com/experiments/interpreting-results/read-results). | | _Explore_ | [Custom queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries) that break results down by user or event dimensions. | | _Summary_ | A high-level summary of the experiment, including any generated summary sections and notes. | A panel on the right side of every tab holds the experiment's _Details_ (description, owner, status, [quality score](https://docs.statsig.com/experiments/setup/quality-score), ID type, tags, team, and target applications) and a _Discussion_ thread. ================================================================================ # Reviewing Experiment Changes URL: https://docs.statsig.com/experiments/reviews ================================================================================ # Reviewing Experiment Changes When a project requires config reviews, Statsig holds every experiment change until a member of the team approves and commits it. Buttons that normally apply a change read **Submit for Review** instead. The experiment's _Setup_ tab becomes read-only while a change is pending and the header hides the **Start** or **Make Decision** buttons until the change is committed or rejected. To turn reviews on for a project or an environment, go to [Set up reviews](https://docs.statsig.com/guides/setting-up-reviews). ## When an experiment change needs review A change to an experiment needs review when both of the following are true: - **The experiment requires review.** Statsig requires it when the owning [team](https://docs.statsig.com/access-management/teams) requires it, the project requires it, or the experiment itself requires it. Any one of these is enough. A level that doesn't require review can't override one that does. - **The change affects an environment that requires review.** Environments scope where a requirement applies, but they never create one. Production environments always requires review. By default, other environments don't require reviews. > **Note:** > > Warehouse Native analysis-only experiments are exempt unless the project also requires reviews on analysis-only experiments. ## Submit a change for review 1. Make a change. For example, to change a lifecycle action, open **Start** or the **Make Decision** dropdown and choose the action you want. 2. Optionally, add reviewers in the _Changes require review_ block. You can add several reviewers, but only one of them needs to approve. Statsig adds reviewers automatically when the change touches an environment that requires a specific review group. 3. Describe the change. 4. Select **Submit for Review**. A banner appears at the top of the experiment naming the request, such as "my\_experiment was requested to be started", along with who requested it and which reviewers it went to. Statsig emails the reviewers, notifies them in the console, and if you've configured it, sends a message through the [Slack integration](https://docs.statsig.com/integrations/slack). ## Which experiment changes are reviewable Reviews cover the experiment's whole lifecycles: creating, starting, and scheduling a start; making a decision, including ship, rollout, and scheduled rollout; stopping assignments, concluding, abandoning, resetting, and restarting; scheduling or editing a stop; archiving, unarchiving, and deleting; and editing settings, overrides, owners, team, target applications, or allowed reviewers. ## Approve and commit a change Approving a review doesn't change the experiment. The change must be committed before it affects the experiment. 1. A reviewer opens the experiment, selects **View Changes** to compare the current and proposed configuration, then selects **Approve** or **Reject**. 2. The review moves to _Approved & Awaiting Commit_. 3. Someone with edit access selects **Commit Changes** to apply it. > **Note:** > > Statsig doesn't notify anyone when a review is ready to commit. Approved changes stay pending until someone commits them, so check the project's _Reviews_ page or the experiment banner for work in the _Approved & Awaiting Commit_ state. ## Commit without review You can only approve your own changes without reivew if you have this permission as part of your role. If your role has the **Self-Approve Review** permission, your own pending change shows **Commit without Review** instead of **Approve**. Selecting **Commit without Review** asks you to confirm, then applies the change immediately and records it in the experiment's history as self-approved. This permission is on by default for the Admin role and off for Member, so turning reviews on doesn't by itself produce two-person approval. To require a second person, turn off **Self-Approve Review**. ## Withdraw or clear a pending review - Before approval, the requester selects **Edit > Cancel Submission**. - After approval but before commit, select **Discard**. Anyone with edit access can discard a pending change, not only the requester. - After commit, make a reversing change. You can't cancel a committed review. An experiment holds one review at a time. Submit a second change only after the first one commits or clears. ## When the experiment changes under a pending review A review stores a snapshot of the experiment as it was at submission. If the experiment is edited after that snapshot is created, committing the change fails with a message stating that the experiment has been modified since your change. Refreshing doesn't clear this, because Statsig replays the stored change. Check the experiment's history for what changed, discard the pending review, make the change again, and commit it after approval. ## Allowed Reviewers The _Details_ panel shows an experiment's **Allowed Reviewers**. If this list isn't populated, it limits who you can pick as a reviewer when you submit a change. Editing the list is itself a reviewed change, routed to the existing reviewers, so an editor can't remove the people who review their work. ================================================================================ # How to Read Experiment Results URL: https://docs.statsig.com/experiments/interpreting-results/read-results Updated: 2025-09-18 ================================================================================ # How to Read Experiment Results The Results tab shows how each experiment group performed on your primary and secondary metrics: the relative lift, its confidence interval, and whether the result is statistically significant. Use it to check exposures and the Scorecard for a running or completed experiment. To filter or group results by a dimension the Scorecard doesn't show, use a [custom Explore query](https://docs.statsig.com/experiments/interpreting-results/custom-queries). ## Cumulative exposures **Figure: Cumulative exposures by model group** A launch burst brings the experiment to nearly 70,000 exposures in four days, then enrollment settles into a steady climb to 118,356 units, split within half a point of a third for each of the three model groups. Stacked area chart. X axis: Date. Y axis: Cumulative exposures. | Date | GPT-3 (Control) | GPT-4 | GPT-4o | | --- | --- | --- | --- | | 2026-02-17 | 0 | 0 | 0 | | 2026-02-18 | 6526 | 7338 | 7029 | | 2026-02-19 | 12757 | 13667 | 13364 | | 2026-02-20 | 19214 | 19710 | 19406 | | 2026-02-21 | 23169 | 23425 | 23402 | | 2026-02-22 | 23412 | 23691 | 23683 | | 2026-02-23 | 23884 | 24233 | 24185 | | 2026-02-24 | 24385 | 24732 | 24702 | | 2026-02-25 | 24781 | 25159 | 25154 | | 2026-02-26 | 25198 | 25579 | 25575 | | 2026-02-27 | 25559 | 25976 | 26013 | | 2026-02-28 | 25851 | 26227 | 26296 | | 2026-03-01 | 26099 | 26501 | 26562 | | 2026-03-02 | 26659 | 26974 | 27093 | | 2026-03-03 | 27069 | 27438 | 27546 | | 2026-03-04 | 27474 | 27863 | 27965 | | 2026-03-05 | 27949 | 28288 | 28375 | | 2026-03-06 | 28376 | 28649 | 28789 | | 2026-03-07 | 28630 | 28919 | 29091 | | 2026-03-08 | 28892 | 29155 | 29326 | | 2026-03-09 | 29364 | 29713 | 29906 | | 2026-03-10 | 29844 | 30178 | 30418 | | 2026-03-11 | 30331 | 30583 | 30870 | | 2026-03-12 | 30715 | 31015 | 31273 | | 2026-03-13 | 31131 | 31470 | 31712 | | 2026-03-14 | 31432 | 31763 | 32000 | | 2026-03-15 | 31668 | 32028 | 32261 | | 2026-03-16 | 32130 | 32586 | 32728 | | 2026-03-17 | 32624 | 33091 | 33238 | | 2026-03-18 | 33085 | 33575 | 33634 | | 2026-03-19 | 33462 | 33991 | 34018 | | 2026-03-20 | 33905 | 34439 | 34405 | | 2026-03-21 | 34163 | 34685 | 34682 | | 2026-03-22 | 34433 | 34937 | 34943 | | 2026-03-23 | 34986 | 35493 | 35460 | | 2026-03-24 | 35476 | 35982 | 35960 | | 2026-03-25 | 35952 | 36395 | 36404 | | 2026-03-26 | 36421 | 36790 | 36814 | | 2026-03-27 | 36855 | 37240 | 37195 | | 2026-03-28 | 37118 | 37528 | 37452 | | 2026-03-29 | 37380 | 37814 | 37723 | | 2026-03-30 | 37845 | 38318 | 38286 | | 2026-03-31 | 38316 | 38812 | 38727 | | 2026-04-01 | 38776 | 39205 | 39166 | | 2026-04-02 | 39176 | 39610 | 39570 | The Cumulative Exposures chart shows exposures: the unique experimental units enrolled in the experiment, typically unique users, or devices for device-level experiments. The timeline shows when the experiment started and how many exposures Statsig enrolled each day. Use this chart to verify the rate at which users entered each group, the total number exposed, and whether the target ratio matches what you configured in experiment setup. Click the **See More** option to expand the chart. ## Scorecard The experiment Scorecard shows the metric lifts for all of the primary and secondary metrics that you set up when creating the experiment. ### Real-time results in the first 24 hours Statsig calculates the Scorecard results hourly up to the first 24 hours after you start your experiment. Statsig calculates Scorecard results before the first daily metric results run. This hourly calculation applies only to Statsig Cloud. For Warehouse Native projects, reload results on demand or set up a daily schedule. Use the real-time Scorecard to confirm that Statsig calculates exposures and metrics as expected, and to debug your experiment or gate setup. > **Note:** > > Don't make any experiment decisions based on real-time results data in this first 24-hour time period. Let the experiment reaches its target duration, which is when your primary metrics reach experimental power, before you make any decisions. For more information about target duration, go to [Target Duration](https://docs.statsig.com/experiments/setup/analysis-settings#target-duration). Until the first daily run, the real-time view differs from daily results in the following ways: - Metric lifts don't have confidence intervals. - There's no time-series view of metric trends. - There's no projected topline impact analysis. - You can't apply advanced statistical treatments such as CUPED or sequential testing. ### Daily Scorecard results ![Experiment scorecard table displaying metric lifts and confidence intervals](https://docs.statsig.com/images/snippets/pulse/read-results/8b855f5c-d26f-4185-ac31-5108fbebe18e.png) The daily results run calculates the difference between randomization groups (for example, test and control) across your metric suite and applies a statistical test to the results. Refer to [Statsig's stats engine](https://docs.statsig.com/experiments/statistical-methods/introduction) for details. For every metric, Statsig shows you: - The calculated relative difference (Delta %). - The confidence interval. - Whether the result is statistically significant. Positive lifts are green, negative lifts are red, and non-significant results are grey. The formula for calculating lift is: $$ \Delta \overline{X} \% = \frac{\overline{X}_t - \overline{X}_c}{\overline{X}_c} \times 100 \% $$ Statsig reports confidence intervals at the selected significance level (95% by default). In a typical two-sided Z-test, Statsig shows the confidence interval as $\pm 1.96 \times$ standard error. Statsig automatically applies 99.9% winsorization to `event_count`, `event_count_custom`, and `sum` metrics. Winsorization caps extreme outlier values to reduce their impact on experiment results. For metrics in the Scorecard or Monitoring Metrics sections of your experiment or gate, you can also apply optional statistical treatments such as: CUPED (pre-experiment bias reduction) and sequential-testing-adjusted confidence intervals. ### 90-day compute window By default, Statsig computes experiment results for only the first 90 days of your experiment. Statsig notifies you by email as you approach the 90-day cap. At that point, you can extend the compute window by 30 days at a time. If the experiment runs beyond the compute window, Statsig stops adding new users to the experiment's results. Analysis for users already exposed continues until you make a decision on the experiment. This calculation window only affects whether Statsig includes a user in the experiment's analysis. It doesn't affect the experience each user receives: new users still receive the experience for the group Statsig randomizes them into. ## Experiment results views On the Results tab, select **Display Options** and then set **Chart Type** to choose how the Scorecard renders metric lifts. | Chart Type | What it shows | | --- | --- | | Cumulative (default) | The aggregate difference between experiment groups, with the corresponding confidence intervals. Hover over a metric for the raw statistics behind the lift calculation and the topline impact. | | Daily | The difference between experiment groups, aggregated by days since the experiment started. | | Days Since Exposure | The difference between experiment groups, aggregated by days since each user's exposure to the experiment. | | Table | The same data as the cumulative view, in a table with additional fields. | The **Display Options** panel also includes: - **Data**: Choose the value to display: Relative Delta, Absolute Delta (per unit), Relative or Absolute Topline Impact, or Relative or Absolute Projected Launch Impact. For what the impact values mean, go to [Topline impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact). - **Zoom**: Adjust the zoom level of the chart. - **Sort By** / **Organize By**: Control the order and grouping of the metrics. - **Filters**: Filter the displayed metrics by tag or filter group. ![Cumulative results view with hover details](https://docs.statsig.com/images/snippets/pulse/read-results/856c7750-df56-45d9-b253-6b63f336cac7.png) ## Dimensions You can break down a Scorecard metric by a user dimension or by an event dimension. ### User dimensions User dimensions are user-level attributes that are either part of the user object you log or additional metadata that Statsig extracts. Examples include operating system, country, and region. To filter or group by user dimensions, create a [custom Explore query](https://docs.statsig.com/experiments/interpreting-results/custom-queries) on the **Explore** tab. For example, view results for users in the US, or for users on iOS grouped by country. ### Event dimensions Event dimensions are the `value` or `metadata` logged as part of the custom event that defines the metric. To break a metric down by categories specific to that metric, [specify the dimension](https://docs.statsig.com/metrics/metric-dimensions) in the `value` or `metadata` attribute when you log the source event. For example, when you log a "click" event, you can also log the target category in the `value` attribute. Statsig automatically generates results for each category in addition to the top-level metric. To view breakdowns for all categories within a metric, select the (+) sign next to the metric. ![dimension results view](https://docs.statsig.com/images/snippets/pulse/read-results/f557dac6-e29f-4cb5-bd6a-19fc2b226193.png) ## Significance level settings Open the _Comparison & Stats_ panel to view Scorecard results at different significance levels and adjust the statistical settings. To open it, select the pencil icon next to the Test and Control summary row on the Scorecard. The panel also includes **Compare** and relative-to group pickers that control which groups Statsig compares. - **Confidence Interval**: Changes the confidence interval displayed with the metric deltas. Choose from 80%, 90%, 95%, 98%, or 99%. A lower confidence interval accepts a higher false-positive rate in exchange for faster, directional results. - **CUPED**: Toggle CUPED on or off. This setting applies only to Scorecard metrics; Statsig doesn't apply CUPED to non-Scorecard metrics. - **Sequential Testing**: Applies a correction to p-values and confidence intervals to reduce the increased false positive rate caused by evaluating results before the target completion date. This setting appears only for experiments with a set target duration. - **SPRT**: Toggle the Sequential Probability Ratio Test (SPRT) on or off. SPRT is a sequential testing methodology that supports unlimited peeking without alpha-spending or confidence-interval penalties. Refer to [Sequential Probability Ratio Tests](https://docs.statsig.com/experiments/advanced-setup/sprt) for details, including its configuration options. - **Power Parameter**: Appears when SPRT is on. Sets the target statistical power (1 − β) that Statsig uses to compute the SPRT decision boundaries. The default is 80%; choose from 80%, 90%, 95%, 98%, or 99%. This isn't the per-metric effect size: set the Minimum Detectable Effect (MDE) and Cohen's d separately during experiment setup, as described in [Power analysis and setting Cohen's d](https://docs.statsig.com/experiments/advanced-setup/sprt#power-analysis-and-setting-cohens-d). Multiple-hypothesis corrections aren't in this panel. Set [Bonferroni correction](https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction) and the [Benjamini-Hochberg procedure](https://docs.statsig.com/experiments/statistical-methods/methodologies/benjamini-hochberg-procedure) in _Advanced Settings_ on the [experiment's _Setup_ tab](https://docs.statsig.com/experiments/setup/analysis-settings#significance-level-adjustments). ## Restarting results If your experiment has stopped computing results, select **Restart** to resume updates. Understand how Restart behaves before you proceed: - A Restart isn't a [Reset](https://docs.statsig.com/experiments/ending/reset) of your experiment. A Restart doesn't re-salt (re-randomize) units, and all users continue to receive the same group assignments. - Statsig begins computing experiment results from the restart point, so your metric results start over. Old results may still appear in time series and Explore query views, but Statsig doesn't carry them forward or update them. - Your Cumulative Exposures chart updates based on new exposures. The duration of the pause in computations determines whether the chart starts over from zero or includes past exposures. To avoid needing a Restart, extend experiments while they're running. Watch for email alerts from Statsig and check your experiments regularly. ================================================================================ # Best Practices and Avoiding False Positives URL: https://docs.statsig.com/experiments/interpreting-results/best-practices Updated: 2025-09-18 ================================================================================ # Best Practices and Avoiding False Positives Sound experiment readouts start from a written hypothesis, a small set of Scorecard metrics, and skepticism toward borderline p-values. Follow these practices when you read a Scorecard. For why a result can flip from significant to neutral as data accumulates, refer to the [Results FAQ](https://docs.statsig.com/experiments/interpreting-results/faq). ## Start with a hypothesis Decide before you open the Results tab which metrics you expect the change to move, what else could have happened, and what would signal that something went wrong. ## Pick a small set of key metrics Choose a few metrics directly tied to your hypothesis that establish whether the experiment worked. More than a handful of key metrics usually indicates an ill-defined hypothesis or unfocused experimentation. ## Avoid cherry-picking results Don't select three metrics that look good while ignoring two that don't. Don't pick "good" or "bad" numbers with no connection to your hypothesis. A statistically significant result should have a plausible explanation, and a false positive is one plausible explanation. ## Look for consistent supporting effects Multiple independent effects that fit one plausible story lend credibility to the observed effects, even when individual p-values are borderline. ## Expect false positives Examining many metrics increases the false positive rate. At a 95% confidence interval (5% significance level), expect about one statistically significant metric in twenty from random chance alone, and more if you include borderline metrics (for example, p = 0.06). Be suspicious of statistically significant results with borderline p-values. ## Look beyond your hypothesis Check for other effects, tradeoffs, and unexpected behaviors. These findings show how users interact with your product and often lead to follow-up experiments and new ideas. ================================================================================ # Slicing by User Properties URL: https://docs.statsig.com/experiments/interpreting-results/user-properties Updated: 2025-09-18 ================================================================================ # Slicing by User Properties Slicing by user properties breaks experiment results down by a user attribute, such as home country, subscription status, or engagement level, so you can see whether the treatment effect differs across user groups. In Statsig Cloud, Statsig captures and freezes each user's properties at first exposure, so a slice reflects who the user was when they entered the experiment. Statsig Warehouse Native can also read user properties from a warehouse table (entity properties). To slice by a user property at any time, run a [custom Explore query](https://docs.statsig.com/experiments/interpreting-results/custom-queries) that filters or groups by that property. In Warehouse Native, you can also pre-compute the properties you slice by most often so they load with the Scorecard. ![Pulse results sliced by user properties](https://docs.statsig.com/images/experiments/interpreting-results/userproperties/60ad9a4f-8e85-42a6-8c36-147fc6c85873.png) ## Pre-computed user properties Statsig Warehouse Native can pre-compute the user properties you frequently use to slice results. On the experiment setup page, under _Advanced Settings_, configure which properties Statsig pre-computes. You can also configure team-level defaults or set these properties on an experiment template. ![Experiment setup page with pre-computed user properties configuration](https://docs.statsig.com/images/experiments/interpreting-results/userproperties/196bd217-dd29-4b63-9f1b-d08639e0d36d.png) After you configure pre-computed properties, you can filter all metrics on the Results tab by those properties. ![Metrics results with user property filters applied](https://docs.statsig.com/images/experiments/interpreting-results/userproperties/8b5c6dcc-feac-46c9-a6fa-331daafc4864.png) ================================================================================ # Metric drill-down URL: https://docs.statsig.com/experiments/interpreting-results/drill-down Updated: 2025-09-18 ================================================================================ # Metric drill-down Metric drill-down shows the statistics behind a single Scorecard result: group sizes, means, totals, the p-value, the time series of the lift, and the projected topline impact. Use it when a metric moved and you need to see whether the effect is stable over time or driven by a small number of units. To break a metric down by a dimension, use a [custom Explore query](https://docs.statsig.com/experiments/interpreting-results/custom-queries) instead. ## Metric tooltip When you hover over a metric on the Results tab, Statsig shows a card with key statistics. Its _Metric Detail_ tab leads with the metric's delta, p-value, and reverse power, and a badge saying whether the result is statistically significant. An _Explanation_ tab describes the result in prose. ![UI for metric hover card in experiments](https://docs.statsig.com/images/metric_hover_card.png) Below that, a table breaks the metric down by group: - **Group**: The name of the group of users. For feature gates, Statsig treats the Pass group as the test group and the Fail group as the control. For experiments, these are the variant names. - **Units**: The number of distinct units included in the metric, for example distinct users for `user_id` experiments or devices for `stable_id` experiments. The column header names the experiment's ID type, such as `userIDs` or `companyIDs`. - **Mean**: The average per-unit value of the metric for each group. - **Total**: The total metric value across all units in the group, over the time period of the analysis. The card also states whether CUPED applied, and offers **View Details** for the full drill-down, **Autoscale CI** to rescale the confidence interval, and **Explore Result** to open the metric in a [custom query](https://docs.statsig.com/experiments/interpreting-results/custom-queries). ### Calculation details | Metric type | Total calculation | Mean | Units | | --- | --- | --- | --- | | `event_count` | Sum of events (99.9% winsorization) | Average events per user (99.9% winsorization) | All users | | `event_user` | Sum of event DAU (distinct user-day pairs) | Average `event_dau` value per user per day. Statsig calls this "Event Participation Rate" because it represents the probability that a user is DAU for that event. | All users | | `ratio` | Overall ratio: sum(numerator values)/sum(denominator values) | Overall ratio | [Participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) | | `sum` | Total sum of values (99.9% winsorization) | Average value per user (99.9% winsorization) | All users | | `mean` | Overall mean value | Overall mean value | Participating users | | user: `dau` | Sum of daily active users | Average metric value per user per day. The probability that a user is DAU. | All users | | user: `wau`, `mau_28day` | Not shown | Average metric value per user per day. The probability that a user is xAU. | All users | | user: `new_dau`, `new_wau`, `new_mau_28day` | Count of distinct users that are new xAU at some point in the experiment | Fraction of users that are new xAU | All users | | user: retention metrics | Overall average retention rate | Overall average retention rate | Participating users | | user: L7, L14, L28 | Not shown | Average L-ness value per user per day | All users | ### p-value In null hypothesis significance tests, the p-value is the probability that a difference as extreme as the observed one arises by random chance when the experiment has no actual effect. A p-value threshold determines which results count as a real effect and which are plausibly due to random chance. For the formula, refer to [p-value calculation](https://docs.statsig.com/experiments/statistical-methods/p-value). ### Reverse power Reverse power is the smallest effect size that an experiment can reliably detect in its current state (some studies call this value ex-post MDE). Statsig calculates it from the sample size and the standard error of the control group. Reverse power doesn't depend on the observed effect size. In practice, it answers the question: given how the test turned out, what's the smallest effect you have sufficient power (typically 80%) to detect? For a two-sided test, Statsig computes the reverse power for a metric X as: $$ Reverse Power = \frac{(Z_{1-\beta} + Z_{1-\alpha/2})}{\overline{X}_{\text{control}}}\times \sqrt{\frac{\mathrm{var}(\Delta \overline{X})}{N_{\text{control}}}} \times 100\% $$ For a one-sided test, Statsig computes the reverse power for a metric X as: $$ Reverse Power = \frac{(Z_{1-\beta} + Z_{1-\alpha})}{\overline{X}_{\text{control}}}\times \sqrt{\frac{\mathrm{var}(\Delta \overline{X})}{N_{\text{control}}}} \times 100\% $$ - $\overline{X}_{\text{control}}$ is the mean metric value across control users. - $var(Δ\overline{X})$ is the population variance of delta. - $N_{\text{control}}$ is the observed number of units in the control group. - $Z_{1-\beta}$ is the standard Z-score for the selected power. Typically ${1-\beta}$ = 0.8 and $Z_{1-\beta}$ = 0.84. - $Z_{1-\alpha/2}$ and $Z_{1-\alpha}$ are the standard Z-scores for the selected significance level in a two-sided test and in a one-sided test. Reverse power is an optional feature. To turn it on or off, go to _Settings > Product Configuration > Experimentation > Organization_. ## Detailed view Select **View Details** to open the detailed view for a metric. It contains three sections: - **Time Series**: How the metric evolves over time. - **Raw Data**: Group-level statistics. - **Impact**: How the experiment affects the metric. ### Time series In the time series view, select and drag to zoom in on a time range. The drop-down offers three types of time series. #### Daily The metric impact on each calendar day, without aggregating days together. Use the daily view to assess day-over-day variability and the impact of specific events. It's the recommended view for holdouts because it highlights the impact over time as you launch new features. ![Daily metric impact visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/f42453a6-e413-47d5-b176-bb3e9b49a915.png) #### Cumulative The cumulative metric impact from the start of the experiment. Use the cumulative view to observe trends and to watch how the confidence interval changes over time. ![Cumulative metric lift visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/b2e9aea9-98fb-4e29-bccf-abae356d0173.png) #### Days since exposure The metric impact based on how long a user has been in the experiment. Statsig aligns daily data for each user by the day the user entered the experiment (Day 0, Day 1, and so on), not by calendar date. This alignment lets you distinguish early (novelty) effects from long-term effects. This view also shows pre-experiment data, which reveals biases between groups before the experiment started. Such biases can arise from random chance or from an issue in the random assignment process. ![Days since exposure metric visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/17eeb054-43d8-424c-b43a-85c682bfcfb8.png) ### Raw data The raw data view shows the group-level statistics that Statsig uses to compute the metric deltas and confidence interval: Units, Mean, Total, and the standard error of the mean (Std Err). Refer to the [statistical calculations reference](https://docs.statsig.com/experiments/statistical-methods/introduction) for details. ### Impact ![Experiment impact metrics interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/171754168-624f740e-bdd6-46ea-a2e3-8d70e637ff75.png) - **Experiment Delta (absolute)**: The absolute difference of the mean between groups, that is, Test Mean - Control Mean. Statsig shows the p-value to indicate whether the observed absolute difference is statistically significant. - **Experiment Delta (relative)**: The relative difference of the mean, that is, 100% x (Test Mean - Control Mean) / Control Mean. - **Topline Impact**: The measured effect the experiment has on the overall topline metric each day, on average. Statsig computes it daily and averages it across the days in the analysis window. The absolute value is the net daily increase or decrease in the metric; the relative value is the daily percentage change. - **Projected Launch Impact**: An estimate of the daily topline impact Statsig expects if you launch the test group to all users. This estimate takes into account the layer allocation and the size of the test group, and assumes that the targeting gate (if there is one) stays the same after launch. The projected launch impact is often smaller than the relative experiment delta because the experiment reaches only a subset of the users who contribute to the topline metric, and the topline impact can be higher or lower than the experiment delta because Statsig computes the two values differently (unit-level averages for deltas, daily pooled totals for topline). For the calculations, refer to [topline and projected impact calculations](https://docs.statsig.com/experiments/statistical-methods/topline-impact). ================================================================================ # Participating Units URL: https://docs.statsig.com/experiments/interpreting-results/participating-units Updated: 2025-09-18 ================================================================================ # Participating Units Participating units, also called participating users, are the exposed units that have a non-zero denominator for a metric that divides a numerator by a denominator, such as a ratio metric. Statsig uses only these units in the statistical calculations for those metrics, so their unit count is smaller than the experiment's total exposures. Check this number when a ratio or mean metric's unit count looks lower than the Cumulative Exposures chart. The [calculation details table](https://docs.statsig.com/experiments/interpreting-results/drill-down#calculation-details) on the metric drill-down page lists which metric types (`ratio`, `mean`, and retention metrics) use participating units. ![Participating units diagram showing subset of total exposed users](https://docs.statsig.com/images/experiments/participating_units.png) Statsig includes a unit in a daily ratio only if it triggered the denominator event that day. Statsig excludes units that never trigger the denominator event during the experiment from the test vs. control comparison for that metric. ## Example An e-commerce company measures average basket size with the ratio metric "Total Items Purchased per Order": the numerator is the count of items bought, and the denominator is the number of orders submitted. In an experiment on the checkout flow, Statsig includes only users with at least one Order event in that metric. ================================================================================ # Custom "Explore" Queries URL: https://docs.statsig.com/experiments/interpreting-results/custom-queries Updated: 2025-09-18 ================================================================================ # Custom "Explore" Queries A custom Explore query re-runs the experiment analysis on a filtered or grouped slice of your data: one set of metrics, one dimension filter or Group By, and one date range. Results use the same stats engine as the Scorecard, including p-values, confidence intervals, [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped), and [Sequential Testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing), and Statsig saves each result as a point-in-time snapshot in Query History. Use a custom query when the Scorecard's dimension breakdowns don't cover the segment you care about, or to check how an experiment or launch affected a specific set of users. For the default views of Scorecard metrics, use **Display Options** on the [Results tab](https://docs.statsig.com/experiments/interpreting-results/read-results#experiment-results-views) instead. > **Warning:** > > Be careful when you draw inferences from custom queries, especially when you group by a dimension with many values. Grouping this way increases your chance of seeing a false-positive statistically significant result. ## Running a custom query On the **Explore** tab of your experiment, select **Create**. Leave _Query Type_ set to **Custom Metric Query**, then define the query with the following fields. The same selector also starts an [interaction effect detection](https://docs.statsig.com/experiments/exploring-results/interaction-detection) or [differential impact detection](https://docs.statsig.com/experiments/exploring-results/differential-impact-detection) analysis. ![Custom query explore tab interface](https://docs.statsig.com/images/snippets/pulse/custom-queries/b2737ba1-dbf4-4235-a806-afea5dfe9a78.png) | Field | Description | | --- | --- | | Metrics | The metrics to analyze: a single metric, several metrics, or a metric tag, which includes every metric in that tag. The field offers three shortcuts: Scorecard Metrics (all metrics in your experiment's Primary and Secondary Metrics sections), Primary Metrics, and Secondary Metrics. | | Metric Filter | Filter the selected metrics by an event or user dimension with the Add Filter dropdown. For example, to view results for Canadian users only, filter to Country = CA. Filters apply per metric. | | Group By | Group results by an event or user dimension. Group By applies at the query level, so the dimension you select applies to all included metrics. | | Time Range for Metric Data | The date range for the analysis. Defaults to the full date range of your experiment data. | | ID List Segment filters (advanced) | Include only users in an ID-list [segment](https://docs.statsig.com/segments/overview), or exclude users in one (for example, users retroactively identified as bad actors). Useful when you didn't log a user dimension you want to filter on, or when you define the sub-population you care about in your own data warehouse. This option can bias results: define the segment based on the user's status before exposure to the experiment or feature gate. | | Filter by Exposure Date (advanced) | Include or exclude a date range of exposures. In Warehouse Native, you can also include or exclude users based on when they were first exposed. Useful when metrics have a novelty effect or delayed impact, or when you want to restrict results to certain users. This filter can bias results, so use it cautiously. | ![Metric filter dropdown selecting Country equals CA](https://docs.statsig.com/images/snippets/pulse/custom-queries/f56b4259-4d18-44d1-9646-9d7aa2f8f847.png) > **Note:** > > Statsig bases user groups in experiment results on first-touch attribution: filters and grouping use the user attributes collected at the time of first exposure in the gate, experiment, or layer check. ![Custom query definition form showing selected metrics and filters](https://docs.statsig.com/images/snippets/pulse/custom-queries/85264260-2f65-4bfd-b4e1-477bd043b87d.png) ## Viewing a custom query in Explore Queries take a few minutes to run, and Statsig emails you when the results are ready. Results appear in the **Query History** section of the **Explore** tab, where Statsig stores all historical queries across your team. You can give a query a display name inline to find it later. ![Explore tab query history list](https://docs.statsig.com/images/snippets/pulse/custom-queries/46574581-604e-4d29-b231-fa51876c813d.png) > **Note:** > > Precomputed user dimensions, which run on a schedule, load through separate asynchronous Explore queries after the main experiment results appear, and become available within a few minutes. The gap is most noticeable right after the first reload of the day. If you see "No dimensions available for this time range" for a precomputed dimension, wait a few minutes and refresh. User-triggered custom queries don't have this delay. ## Scheduling a custom query To refresh a custom query daily, schedule it from the **Explore** tab: author the query, select the **...** menu, then select **Schedule**. The query then runs daily and appears in the **Scheduled** tab of your Metric Lifts. ![Scheduled custom queries tab displaying daily runs](https://docs.statsig.com/images/snippets/pulse/custom-queries/56d11b46-f2de-4569-89f7-b0a439910964.png) ![Scheduled query configuration interface](https://docs.statsig.com/images/snippets/pulse/custom-queries/fad0c8ce-3f9c-46be-a09c-52263e124259.png) ## Reviewing custom query results Custom query results look like the main Results tab because Statsig applies the same statistical methods and analysis practices to both. The key difference is that a custom query result is a snapshot in time. After the query runs, Statsig saves the results, and they don't update when more metric data arrives. To update your results, run a new custom query or schedule one to run at a regular cadence. ### Sequential testing and custom queries If you enable [Sequential Testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) for your experiment, you can apply it to custom query results too. Whether and how much Statsig adjusts confidence intervals and p-values follows the standard rules of sequential testing: if your custom query doesn't satisfy the experiment's target Days or Unique Exposures from your setup, Statsig applies sequential testing adjustments to account for the under-powered state of the experiment. Because a custom query is a snapshot in time, Statsig computes sequential testing adjustments for that specific analysis only. If you run additional custom queries with more or less data (for example, more days in the analysis or more unique users in the experiment), the adjustments change accordingly. Custom queries that meet the configured minimum Days or Unique Exposures receive no sequential adjustments. ![Custom query results table displaying sequential testing adjustments](https://docs.statsig.com/images/snippets/pulse/custom-queries/df7c4087-82c3-41fb-8f5d-124094ec4526.png) ================================================================================ # Exporting Experiment Result Reports URL: https://docs.statsig.com/experiments/interpreting-results/export Updated: 2025-09-18 ================================================================================ # Exporting Experiment Result Reports Exporting a results report saves your experiment or feature gate results as a CSV file so you can analyze them outside Statsig. You start the export from the Results tab, and Statsig emails you a download link that you can share or load into BI tools, notebooks, or a data warehouse. Use Export Report for a one-time snapshot in Statsig Cloud. If you use Warehouse Native, Statsig writes results to your warehouse instead; refer to [Export experiment results to your warehouse](https://docs.statsig.com/experiments/interpreting-results/access-whn). ## Export a report ![Finding Export Report](https://docs.statsig.com/images/snippets/pulse/export/a2d68701-6828-47d2-8fde-b44a5cea4abb.png) You can export results only after the experiment or gate has results. For an experiment, open the three-dot (**...**) menu in the header and select **Export Report**; Statsig disables the option until there's data to export. For a holdout, select **Export Report** on the _Pulse Results_ tab. The export can take up to 10 minutes. When the report is ready, Statsig sends you a notification and an email, and a link appears under _Settings > Product Configuration > Reports_. ![Export Pulse Report Menu](https://docs.statsig.com/images/snippets/pulse/export/5af19e59-f2b7-492b-9dc2-9439e447dbcc.png) ================================================================================ # Metric Insights and Aggregated Impact URL: https://docs.statsig.com/experiments/exploring-results/aggregated-impact Updated: 2025-09-18 ================================================================================ # Metric Insights and Aggregated Impact Aggregated Impact is the sum of projected launch impact across every experiment and feature gate that moved one metric, discounted by each result's false positive risk. The Insights page in the Statsig console shows this total alongside the individual tests that moved the metric, so you can quantify how much impact your team has driven on that metric and diagnose unexpected metric changes. The Insights page is the reverse perspective of the [Results tab](https://docs.statsig.com/experiments/interpreting-results/read-results). Use the Results tab when you start from one experiment and want to know which metrics it moved. Use the Insights page when you start from one metric and want to know which experiments and gates moved it most, for example to assess your team's impact or to set realistic goals. ## How to read the Insights page 1. In the [Statsig console](https://console.statsig.com/), go to the Insights page. Insights also appears in the _Insights_ tab for each metric. 2. Select a metric from the drop-down at the top of the page. 3. Select the ID type, time window, and other filters. The Insights page then shows the relative impact, topline impact, and projected launch impact for every experiment or gate that includes the metric. Statsig sums the projected launch impacts, adjusts for false positive risk (the "winner's curse"), and displays the result as the Aggregated Impact Estimate. ![Insights dashboard showing aggregated impact estimates for a metric](https://docs.statsig.com/images/snippets/pulse/aggregated-impact/430563dc-4794-4d69-a314-36c76a6fcf74.png) ## How the math works For the topline and projected launch impact calculations, go to [Computing projected launch impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact#computing-projected-launch-impact). To estimate false positive risk and calculate Aggregated Impact, Statsig uses the methodology in [A/B Testing Intuition Busters: Common Misunderstandings in Online Controlled Experiments (Kohavi, Deng, and Vermeer, KDD 2022)](https://dl.acm.org/doi/10.1145/3534678.3539160): $$ Aggregated Impact=\sum_{i}{(1 - FPR_i) \times Projected Launch Impact_i} $$ The [projected launch impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact) estimates the topline impact if you make a decision and launch the test group to all users. Statsig calculates the false positive risk with the following formula: $$ FPR_i = \frac{\alpha_i \times \pi}{\alpha_i \times \pi + (1 - \beta_i) \times (1 - \pi)} $$ In this formula, $\alpha_i$ is the significance level for experiment i, $\beta_i$ is the type II error, and 1 - $\pi$ is the prior success rate based on historical experiment results. ================================================================================ # Topline and Projected Impact URL: https://docs.statsig.com/experiments/statistical-methods/topline-impact Updated: 2025-09-18 ================================================================================ # Topline and Projected Impact Topline impact is the daily change in a company metric that an experiment caused while it ran, measured across the users in the experiment. Projected launch impact scales that number to your whole user base to estimate the daily change if you launch the test group to everyone, relative to the expected baseline value of the metric without the experiment. Use topline impact to report what the experiment did; use projected launch impact to inform a launch decision. Statsig shows topline impact and projected launch impact in both absolute and relative units. Neither uses CUPED, because CUPED already adjusts for pre-exposure data, which is the same data the topline metric changes from. Applying CUPED would double-count that adjustment. > **Tip:** > > Take an experiment with a Control group of 1000 users and a Test group of another 1000 users that ran for 30 days. For an `event_count` metric, the experiment delta is +1.0 events per user (absolute). The topline impact for this metric is +33.33 events per day (absolute). ## Computing topline impact Statsig computes the topline impact over the total duration of the experiment. The calculation depends on whether the metric is an absolute quantity or a ratio. ### Topline impact for count and sum metrics This calculation applies to `event_count` and `sum` metrics. Statsig derives the absolute topline impact from the experiment results: the difference in means between test and control, multiplied by the average number of users in the test group per day. $$ Impact_{abs}=(X_t-X_c) \cdot N_t / n_{days} $$ Statsig then computes the relative impact from the absolute impact and the overall metric value shown in the [metrics dashboard](https://docs.statsig.com/metrics/console). The relative impact is the percentage change in the overall metric value over the rollup window that Statsig attributes to the active experiment. $$ Impact_{rel}=\frac{Impact_{abs}}{\text{Topline\_Value}-Impact_{abs}} \times 100\% $$ ### Topline impact for ratio and mean metrics To derive the topline impact on a ratio metric, Statsig first determines the impact on the numerator $X$ and the denominator $Y$ separately. The topline impact is the current value of the ratio metric minus the baseline value obtained by subtracting the numerator and denominator impacts: $$ Impact_{abs}=\frac{Topline_X}{Topline_Y}-\text{Baseline\_Value} $$ where the baseline value is the expected value of the topline metric if the experiment weren't running: $$ \text{Baseline\_Value}=\frac{Topline_X-(\bar{X_t}-\bar{X_c}) \cdot N_t}{Topline_Y-(\bar{Y_t}-\bar{Y_c}) \cdot N_t} $$ Statsig computes the relative impact for ratio metrics by dividing the absolute impact by the baseline value: $$ Impact_{rel}=\frac{Impact_{abs}}{\text{Baseline\_Value}} \times 100\% $$ ## Computing projected launch impact Statsig uses the layer allocation of the experiment and the size of the test group to estimate a scaling factor $m$, which represents the increase in absolute impact expected when you launch the test group. To accommodate changes in allocation during the experiment, Statsig calculates the launch factor over a rollup window as: $$ m_{rollup}=\frac{1}{\sum_{1}^{rollup}{\text{layer\_alloc} \times \text{group\_pct}}} \times rollup $$ > **Note:** > > The calculation doesn't factor in the targeting gate. The projected impact calculation assumes that the targeting gate remains the same after you launch the experiment. ### Projected launch impact for count and sum metrics This calculation applies to `event_count`, `event_dau`, and `sum` metrics. The projected absolute impact is the current topline impact scaled by $m$. For example, consider an experiment with 50% layer allocation and a 50/50 test/control split, so that 25% of all users are in the test group. If the topline impact is +10 events per day, launching the experiment results in +40 events per day. If the allocation changed during the experiment, Statsig uses a weighted average of the historical allocations. $$ Projected_{abs}=Impact_{abs} \times m $$ The relative projected impact is the expected percentage change in the topline metric, relative to the baseline value of the metric without the experiment running. $$ Projected_{rel}=\frac{Projected_{abs}}{\text{Topline\_Value}-Impact_{abs}} \times 100\% = Impact_{rel} \times m $$ ### Projected launch impact for ratio and mean metrics The projected impact of a ratio metric depends on the numerator and denominator impacts, using the same scaling factor $m$ for each term: $$ Projected_{abs}=\frac{Topline_X+(m-1) \cdot (\bar{X_t}-\bar{X_c}) \cdot N_t}{Topline_Y+(m-1) \cdot (\bar{Y_t}-\bar{Y_c}) \cdot N_t} - \text{Baseline\_Value} $$ where the first term is the projected metric value after launch. The projected relative impact of a ratio metric is the projected absolute impact divided by the baseline value of the ratio: $$ Projected_{rel}=(\frac{Projected_{abs}}{\text{Baseline\_Value}}) \times 100\% $$ ## Confidence intervals for topline and projected impact Statsig computes the confidence intervals for topline and projected impact with the same method as [confidence intervals for experiment deltas](https://docs.statsig.com/experiments/statistical-methods/confidence-intervals). $$ CI(Impact) = Impact \pm Z \cdot \sqrt{var(Impact)} $$ For the absolute impact of count and sum metrics, the variance is a linear combination of the test and control variances: $$ var(Impact_{abs})=[var(\bar{X_t})+var({\bar{X_c}})] \cdot N_t^2 $$ For projected launch impact: $$ var(Projected_{abs})=var(Impact_{abs}) \cdot m^2 $$ For ratio metrics and relative impacts, Statsig calculates the variance with the [Delta method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method), which accounts for the correlation between the numerator and denominator terms by linearizing non-linear combinations of experiment variables. For example, the variance in the relative impact of a count metric is: $$ var(Impact_{rel})=var(Impact_{abs}) \cdot \frac{(\text{Topline\_Value})^2}{(\text{Topline\_Value} - Impact_{abs})^4} $$ ================================================================================ # Meta-Analysis URL: https://docs.statsig.com/experiments/exploring-results/meta-analysis Updated: 2025-09-18 ================================================================================ # Meta-Analysis Meta-analysis in Statsig is a set of console views that summarize results across all the experiments in a project. They're the tabs of the _Insights_ page under _Experimentation_: **Experiment Timelines**, **Knowledge Bank**, **Metric Insights**, **Metric Correlations**, and **Metric Impacts** (the batting average). Use these views to learn how hard a metric is to move, to find more sensitive proxy metrics, or to compare how teams' experiments perform in aggregate. Use the [Results tab](https://docs.statsig.com/experiments/interpreting-results/read-results) to read the results of one experiment, and [Aggregated Impact](https://docs.statsig.com/experiments/exploring-results/aggregated-impact) to total the lift that experiments and gates have driven on one metric. ## Experiment timeline view The experiment timeline view filters to the experiments a team has run and answers questions like: - What experiments are running now? - When does Statsig expect them to end? - What percentage of experiments ship control versus test? - What is the typical duration? - Do experiments run for their planned duration, or much longer or shorter? - Do experiments impact key business metrics, or only shallow or team-level metrics? - How much do they impact key business metrics? ![Experiment timeline view dashboard](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/d1e1db49-18b4-46af-93f7-4c0e58c5bdb0.png) ## Metric impact (batting average) The "batting average" view shows how easy or hard a metric is to move. Filter to a set of shipped experiments to see how many of them moved the metric by 1% versus 10%. You can filter by team, tag, or statistical significance. Use this view to: - Check whether a claim that the next experiment moves this metric by 15% is realistic. - Set goals based on past ability to move this metric. ![Metric impacts view showing how many experiments moved a metric by each percentage bucket](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/72f987a4-02ba-4937-9f3d-06892c55e4e9.png) ## Metric correlation view The metric correlation view plots two metrics against each other so you can inspect them for correlation. Each data point represents one experiment's impact on both metrics. Often the metric you want to move isn't sensitive and is slow to measure. Use this view to find more sensitive, faster-to-measure proxy metrics, then run experiments against those proxies. You can remove outliers, filter to a team's experiments, or download the underlying dataset. In this hypothetical example, `Checkouts` is the metric you want to move, but it isn't sensitive. `AddToCart` correlates well with `Checkouts`, while `ViewItemDetail` doesn't. ![Metric correlation scatter plot](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/016285b0-cdc4-46a4-8fdf-204b20b5b0e4.png) ![Metric correlation analysis interface](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/c29e5d7d-d8b6-4841-acaf-8d521a5db398.png) ## Metric insights The metric insights view shows all experiments and feature rollouts that impact a metric you select. For details, go to [Aggregated Impact](https://docs.statsig.com/experiments/exploring-results/aggregated-impact). ![Metric insights view listing experiments and gates that impact a selected metric](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/8d61ada1-bf1f-41cf-b52b-f01d24052568.png) ## Knowledge Bank The Knowledge Bank is a searchable repository of experiment learnings across teams. Use it to find shipped, healthy experiments, review past work, and get ideas for new experiments. New team members can explore the experiments a team ran or search by topic. The meta-analysis views offer structured ways to review your experiment corpus; use the Knowledge Bank when you need free-text search. ![Knowledge bank search interface](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/860430c4-a754-4ff8-aa85-8bf49a755801.png) ================================================================================ # Differential Impact Detection URL: https://docs.statsig.com/experiments/exploring-results/differential-impact-detection ================================================================================ # Differential Impact Detection Differential Impact Detection flags an experiment when its effect on one configured user segment, such as a browser, operating system, or country, differs sharply from its effect on all other users. Experiments can affect sub-populations in ways the topline result hides: a bug might affect only one browser, or a segment's lift might cancel out against other changes. Statsig analyzes experiments for differential impact when Pulse loads after Day 1, after Day 3, and when the experiment reaches its Target Duration, and it flags extreme differential impacts for any segment you configure. This feature is also called Heterogeneous Treatment Effect or Segments of Interest. ![Differential impact detection alert in Pulse results](https://docs.statsig.com/images/snippets/whn/differentialImpact/9783ba7a-812b-4fea-97af-4e3344f8345f.png) ## Configure segments of interest Configure the Segments of Interest that Statsig evaluates for Differential Impact Detection. On Statsig Cloud, segments are user properties in the [User Object](https://docs.statsig.com/concepts/user) that you set when you use the Statsig SDK. On Statsig Warehouse Native, you can also configure segments as an [Entity Property](https://docs.statsig.com/statsig-warehouse-native/features/entity-properties). ![Segments of Interest configuration interface](https://docs.statsig.com/images/snippets/whn/differentialImpact/c9bb5e56-dbc8-4fc2-a33b-92974f867120.png) ## How Statsig flags differential impacts If Statsig finds extreme outliers for a segment you configured, it flags the experiment when you view Pulse results. The Explore section of your Pulse results shows the data broken out by segment. ![Pulse results showing differential impact by segments](https://docs.statsig.com/images/snippets/whn/differentialImpact/5e5a3907-ff67-404c-a94f-2f986262008e.png) ## Methodology Statsig uses a Welch's t-test to compare the treatment effect for one segment of users with the treatment effect for all other users. Welch's t-test suits this comparison because user segments can have unequal population variances. Statsig calculates the average treatment effect as follows: $$ \overline{TE} = \overline{X_t} - \overline{X_c} $$ Statsig calculates the variance in treatment effect as follows: $$ var(TE) = var(X_t) + var(X_c) $$ Statsig calculates the n of the treatment effect as follows: $$ n_{TE} = min(n_t, n_c) $$ With these values, Statsig determines the t-statistic and degrees of freedom as it does for any experiment that uses [Welch's t-test](https://docs.statsig.com/stats-engine/p-value#welchs-t-test). Statsig then applies a Bonferroni Correction to adjust alpha and avoid false positives. The correction sets two thresholds: a high likelihood of heterogeneous treatment effect and some likelihood of heterogeneous treatment effect. For the Bonferroni Correction, one "comparison" is the calculation of one dimension against the rest, for one metric, for one test variant against control. $$ \text{high chance of HTE, } \alpha = \frac{0.01}{\text{number of comparisons}} $$ $$ \text{some chance of HTE, } \alpha = \frac{0.05}{\text{number of comparisons}} $$ ## View historical differential impact analyses To view all historical analyses, go to the _Explore_ tab of your experiment and filter to the Differential Impact Detection query type. ================================================================================ # Interaction Detection URL: https://docs.statsig.com/experiments/exploring-results/interaction-detection ================================================================================ # Interaction Detection Interaction Detection measures whether two overlapping experiments change each other's effect on a metric. It compares experiment B's lift among users in experiment A's test group with B's lift among users in A's control group. A statistically significant difference between those two lifts is the interaction effect. Run Interaction Detection when two experiments share traffic and you want to know whether rolling out both produces the sum of their individual effects. To prevent overlap instead of measuring it, put the experiments in the same [Layer](https://docs.statsig.com/experiments/layers-overview). ## When overlapping experiments need interaction detection Statsig recommends running overlapping experiments. Users viewing your landing page may experience multiple experiments at the same time. Running overlapping experiments is [supported by industry experience](https://www.statsig.com/blog/embracing-overlapping-a-b-tests-and-the-danger-of-isolating-experiments) and [published research](https://www.microsoft.com/en-us/research/articles/a-b-interactions-a-call-to-relax/). If you expect two experiments to conflict, make them mutually exclusive with [Layers](https://docs.statsig.com/experiments/layers-overview) (also called Universes) instead of running them together. ## How to use interaction detection To start an Interaction Detection analysis, open the experiment's _Explore_ tab, select **Create**, then set _Query Type_ to **Interaction Effect Detection**. ![Interaction Detection interface in Statsig console](https://docs.statsig.com/images/experiments/exploring-results/interaction-detection/b49e62b2-ba95-4db3-8d5a-3ce3f08b620d.png) Select a second experiment and the metrics to analyze. Statsig shows a summary with three sections: - **By Groups**: unit counts for each combination of group assignments across the two experiments. - **Metric Summary Results**: estimated intervals of the difference in metric lift. - **Overlapping Unique Users**: an overview of the traffic intersection between the two experiments. ![Interaction Detection analysis results dashboard](https://docs.statsig.com/images/experiments/exploring-results/interaction-detection/ebbb4383-8abe-4b9b-9132-fb543e6b33ac.png) For more examples, refer to the Statsig blog post [Interaction effect detection](https://www.statsig.com/blog/interaction-effect-detection). ## Methodology Assume two experiments, A and B, each with a control group and a test group. The interaction effect measures the overlapping impact on users exposed to both experiment A and experiment B. $$ \Delta_{\text{treatment effect}} = (\overline{X_{testA \cdot testB}} - \overline{X_{testA \cdot controlB}}) - (\overline{X_{controlA \cdot testB}} - \overline{X_{controlA \cdot controlB}}) $$ $$ \Delta_{\text{treatment effect}}{\%} = \frac{\Delta_{\text{treatment effect}}}{(\overline{X_{controlA \cdot testB}} - \overline{X_{controlA \cdot controlB}})} $$ $$ variance = \frac{Var(X_{testA \cdot testB})}{n_{testA \cdot testB}} + \frac{Var(X_{testA \cdot controlB})}{n_{testA \cdot controlB}} + \frac{Var(X_{controlA \cdot testB})}{n_{controlA \cdot testB}} + \frac{Var(X_{controlA \cdot controlB})}{n_{controlA \cdot controlB}} $$ ### Intuition - The term $\overline{X_{testA \cdot testB}} - \overline{X_{testA \cdot controlB}}$ answers: "If a user is in A's test group, how much does changing B from control to test change the metric?" - The term $\overline{X_{controlA \cdot testB}} - \overline{X_{controlA \cdot controlB}}$ answers: "If a user is in A's control group, how much does changing B from control to test change the metric?" - The difference between those two values shows whether the effect of B depends on whether the user is in A's test or control group. That difference is the interaction effect. If the result isn't statistically significant, the effect of B is the same regardless of which group the user is in for A (no significant interaction). If it's statistically significant, the effect of B depends on A's assignment (significant interaction). ### Directionality The sign of the interaction effect (positive or negative) indicates whether the two treatments amplify or dampen each other's effects. - **Statistically positive interaction**: B's effect is stronger when A is also active. - **Statistically negative interaction**: B's effect is weaker, or reversed, when A is active. ### Magnitude The magnitude (absolute size) of the interaction effect indicates how much the combined impact deviates from simple additivity. For example: - Experiment A produces a +5% lift on your metric of interest. - Experiment B produces a +5% lift on the same metric. - The interaction effect between A and B is –3%. The –3% interaction effect means that rolling out both experiments together produces an overall impact about 3% lower than the sum of their individual effects. The features interfere with each other. To get the most accurate estimate of the true combined impact, run a new experiment that includes both features together. Experiments A and B may not have run over the same time period or under identical conditions, and these differences in timing and seasonality can influence the measured interaction magnitude. > **Info:** > > When an experiment includes more than two groups, Statsig evaluates interaction effects pairwise between groups. To view the interaction effect for specific group combinations, select the groups in the **Select Comparison** dropdown in the Interaction Effect Detection results. ================================================================================ # Reconciling Results Between Experimentation Platforms URL: https://docs.statsig.com/experiments/interpreting-results/reconciling-experiment-results ================================================================================ # Reconciling Results Between Experimentation Platforms Experiment results can differ between analysis platforms because the same data supports many analysis methodologies. Most differences trace back to one of three causes, and you can resolve them by working through the causes in order: 1. The two platforms read or join the metric source data to exposure data differently, which invalidates every downstream step. 2. Statistical features that one platform applies and the other doesn't, most often outlier trimming or pre-experiment bias reduction, are working as intended. 3. A metric definition, or an advanced configuration on a metric or experiment, behaves differently than you expected. Use this page when a Statsig result doesn't match a number from your in-house platform or another platform for the same experiment. If results within Statsig look wrong on their own, start with the [results FAQ](https://docs.statsig.com/experiments/interpreting-results/faq) instead. ## Joining data Differences in experiment results most often stem from how a platform joins exposure data with metric data. ### ID formats In some cases, systems log IDs in different formats to different places. For example, the binary ID `4TLCtqzctSqusYcQljJLJE` maps to the UUID `a0fb4ef0-9d9e-11eb-9462-7bfc2b9a6ff2`, so a company might have the binary ID in its production environment while its data users work with the equivalent UUIDs. Exposures logged with the binary ID can't join with metric data that uses the UUID, and results are empty. Check samples from both the metric source and the assignment source or diagnostic logstream to confirm that the identifiers are in the same format. You can use ID Resolution to bridge ID type gaps, but Statsig didn't design it for this scenario. ID Resolution connects identifiers across logged-out and logged-in sessions, or other scenarios where users switch identifiers during the experiment. ### Timestamps Analyze metric data only after Statsig exposes a user to the experiment. Pre-experiment data should have no average treatment effect, so including it dilutes results. Statsig Cloud uses a date-based join between exposures and metric data: experiments include metric data from the whole of the first exposure date for each experimental unit. While this can include some pre-experiment metric data, the average treatment effect of this dilution should be null. Statsig Warehouse Native uses a timestamp-based join, with an option for a date-based join for daily data. The following query shows the Cloud date-based join. The Warehouse Native join is identical except that the join condition compares `metrics.timestamp >= exposures.first_timestamp` instead of `metrics.date_id >= exposures.first_date_id`. ```sql WITH metrics as (...), exposures as (...), joined_data as ( SELECT exposures.unit_id, exposures.experiment_id, exposures.group_id, metrics.timestamp, metrics.value FROM exposures JOIN metrics ON ( exposures.unit_id = metrics.unit_id AND metrics.date_id >= exposures.first_date_id ) ) SELECT group_id, SUM(value) as value FROM joined_data GROUP BY group_id; ``` Statsig's exposure timestamps are always in UTC. If your metric data is in another timezone, adjust it so the join doesn't filter on mismatched dates. Statsig supports timestamp-based joins for some Enterprise Cloud customers. Contact Statsig to learn more. ### Exposure duplication De-duplicate exposure data before joining so that each user has a single record. Many platforms also manage crossover users (users present in more than one experiment group) by removing them from the analysis or alerting when crossovers occur at high frequency. ```sql SELECT unit_id, experiment_id, MIN(timestamp) as first_timestamp, COUNT(distinct group_id) as groups FROM GROUP BY unit_id, experiment_id, group_id HAVING COUNT(distinct group_id) = 1; ``` ### Data availability When you compare a platform analysis to an experiment analysis that ran in the past, the underlying data may have aged out of retention or no longer exist. Compare the table's retention policy to the analysis dates in your original experiment analysis to confirm that the data still exists. Also confirm that you configured your experiment in Statsig to analyze the same time range as your original analysis. ### Validation To validate the initial metric data and join, run the date-based join query from the [Timestamps](https://docs.statsig.com/experiments/interpreting-results/reconciling-experiment-results#timestamps) section on both platforms, adjusted for each platform's SQL dialect. Confirm that a target metric has the same totals per group across both platforms. Statsig provides the intermediate and result datasets it uses, and the queries behind its analysis, so you can trace where a gap arises. Warehouse Native projects have an advantage here because the SQL dialect and source data are generally the same in Statsig's queries and in your in-house code, which makes comparisons simpler. Pick one metric of interest, validate that data, and resolve any differences before you check statistical and metric methodologies. ## Statistical features Choices in statistical methodology can change experiment results. The following features are common root causes of gaps. Read the queries Statsig runs closely to understand the particulars of its methodology. ### Winsorization Outlier trimming, or [Winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization), changes experiment outcomes by capping extreme values. Disable it in Statsig metrics when you compare across systems, unless you also apply it manually on the other platform. ### CUPED [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) changes variances and observed deltas, especially when pre- and post-exposure data are highly correlated or when groups differ systematically in their pre-experiment data. You can configure CUPED at the metric level, and you can disable it for a result set after running the analysis. ### Ratio metrics For ratio metrics that use the delta method, Statsig includes only units with a non-zero denominator. Statsig calculates ratios and means as $\bar{u} = \frac{\sum_{i=0}^{n}(numerator_i)}{\sum_{i=0}^{n}(denominator_i)}$ and uses the [delta method](https://docs.statsig.com/experiments/statistical-methods/variance#ratio-and-mean-metrics) to correct for the cluster-based nature of these metrics. ## Metric definitions Users often misunderstand how Statsig calculates a given metric. Refer to the [metrics guide](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics) for details. ================================================================================ # Frequently Asked Questions on Reading Experiment Results URL: https://docs.statsig.com/experiments/interpreting-results/faq Updated: 2025-09-18 ================================================================================ # Frequently Asked Questions on Reading Experiment Results This page answers common questions about reading experiment results: significance that flips, missing metrics, exposure-count mismatches, and dimension breakouts. For a walkthrough of the Results tab and the Scorecard, go to [How to read experiment results](https://docs.statsig.com/experiments/interpreting-results/read-results). ## Why did my statistically significant result turn negative Trust the current result: it incorporates more information about the users in your experiment. A result can flip for several reasons: - Random noise, which decreases as the sample size grows. - Within-week seasonality (for example, an effect that differs on Mondays), which normalizes with more data. - The population that saw the experiment early differs from slower adopters. This is common: a daily user likely sees your experiment before someone who uses your product once a month. Use the [time series view](https://docs.statsig.com/experiments/interpreting-results/drill-down#time-series) to check. - A novelty effect made the experiment look meaningful early, but the effect faded. For example, users might click a changed button out of curiosity, then revert to prior behavior. Use the [days since exposure view](https://docs.statsig.com/experiments/interpreting-results/drill-down#days-since-exposure) to check. Pick a readout date when you launch your experiment, based on a [power analysis](https://docs.statsig.com/experiments/power-analysis), and disregard the statistical interpretation of results until then. Reading results multiple times before the readout date increases the false positive rate. ## How should I start interpreting results Start with your Scorecard metrics and a hypothesis about what the experiment should drive; your primary metrics should answer that hypothesis. The delta is the observed difference between the test and control groups, and the error bars show the confidence interval: the range of values the true difference plausibly falls in. Treat results as statistical evidence, not facts: - A result that isn't statistically significant means you don't have sufficient evidence to reject the null hypothesis: given your experiment design, the observed result is reasonably likely to have happened by chance. Treat it as a lack of evidence for your hypothesis, and keep in mind that underpowered tests can produce neutral results even when a true effect exists. - A statistically significant result means the probability of observing this result, or one more extreme, if the two groups were identical is below the threshold you set. Treat it as evidence for your hypothesis, but be wary when you've made multiple comparisons (many metrics, rerunning an experiment, or grouping by dimensions), because each comparison raises the chance of a false positive. A significant result from a test that was extremely unlikely to succeed has a high chance of being a false positive; consider reproducing the result, running a back-test, or lowering your significance level. After the Scorecard, use the all-metrics tab and [custom Explore queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries) to gather more information. Significant movements in those views aren't necessarily statistically sound, because examining more metrics increases the chance of a false positive. Use them to look for unexpected large regressions and to generate follow-up hypotheses. For more guidance, refer to [Best practices and avoiding false positives](https://docs.statsig.com/experiments/interpreting-results/best-practices). ## Why are results missing for some metrics Missing metric results usually happen when your company uses the SDK or event imports and also imports precomputed metrics from your data warehouse. Because these import processes can run at different times, data availability can differ. Adjust your analysis date range to get a full view of your data. ## Why does my external source show more exposure events than Statsig Statsig doesn't count exposures on the last day (the day you made a decision). Filter out that day when you analyze your external data. The hours that define a "day" for your project depend on your project's timezone. ## Why doesn't the Results tab show breakouts for the categorical metadata I log The Results tab shows results for sub-groups of a metric (for example, iOS vs. Android) only when you configure that metadata as a dimension. [Event dimensions](https://docs.statsig.com/experiments/interpreting-results/read-results#event-dimensions), which you log in the `value` or `metadata` fields of a custom event, are the most common dimension type. Define them in your [custom event setup](https://docs.statsig.com/metrics/metric-dimensions). ## Why are dimensions greyed out or showing "No dimensions available for this time range" Precomputed user dimensions load asynchronously after the main Scorecard results and may be greyed out while processing. Wait a few minutes and refresh. You may see "No dimensions available for this time range" when a breakdown has no results for the selected metric and date range. If a precomputed dimension stays unavailable, check its source tables and columns. A source issue can affect one dimension while others load successfully. For details, refer to [Custom Explore queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries). ================================================================================ # Ending an Experiment URL: https://docs.statsig.com/experiments/ending/ending-experiment ================================================================================ # Ending an Experiment Ending a Statsig experiment means choosing what happens to new users, to users already exposed, and to the experiment's results. You can ship a group to all users (Make a Decision), stop enrolling new users while exposed users keep their assignment (Stop Assignments), stop enrollment and data collection without shipping a group (Conclude Experiment and Defer Decision), abandon the experiment, reset it, or disable a single group. The following table shows which action fits each situation and where to find the details. ## Choose how to end an experiment | Action | New users | Existing users | Results | Page | | --- | --- | --- | --- | --- | | Make a Decision | Receive the shipped group's parameter values as the new defaults | Receive the shipped group's parameter values | Remain accessible but stop updating on the day you make the decision | [Make a Decision](https://docs.statsig.com/experiments/ending/make-decision) | | Stop Assignments | No new users enter; allocation drops to 0% and new users receive the project's default experience | Keep receiving their control or treatment experience (requires Persistent Assignment) | Analysis continues for already-exposed users | [Stop Assignments](https://docs.statsig.com/experiments/ending/stop-assignments) | | Conclude Experiment and Defer Decision | No new users enter | Receive the default experience | Data collection stops and results conclude; you can still ship, reset, or abandon later | [Conclude Experiment & Defer Decision](https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision) | | Abandon | Receive the default experience | Receive the default experience | Experiment moves to a finished state; you can reset it later | [Abandon an Experiment](https://docs.statsig.com/experiments/ending/abandon) | | Reset | Receive the default experience until you restart; the new salt reassigns groups on restart | Receive the default experience until you restart | Experiment returns to an unstarted state and the previous run's results stay in history | [Reset an Experiment](https://docs.statsig.com/experiments/ending/reset) | | Disable a group | Statsig can still assign new users to the disabled group; they receive the default experience | Users in the disabled group receive the default experience; other groups keep running | Statsig continues calculating results for the disabled group | [Disable a Group](https://docs.statsig.com/experiments/implementation/disable-group) | ## Stopping an experiment When an experiment has a problem rather than a result, pick the action by how much of the test you still want. - You no longer want to run this test: [abandon the experiment](https://docs.statsig.com/experiments/ending/abandon). - You plan to fix the problem and run the same test again: [reset the experiment](https://docs.statsig.com/experiments/ending/reset). - Only one variant is bad and the other groups are still worth running: [disable that group](https://docs.statsig.com/experiments/implementation/disable-group). ## Reset an experiment Resetting returns the experiment to an unstarted state, generates a new salt, and starts a new analysis window. Go to [Reset an Experiment](https://docs.statsig.com/experiments/ending/reset) for what the reset changes and why the new run is a separate experiment. ## Archive an experiment After you make a decision on an experiment, or when you abandon or reset it, you can archive the experiment. Archiving preserves the experiment's history and results and makes the experiment read-only. If you later decide to make the experiment active again, unarchiving the experiment makes it editable but doesn't automatically restart it. If the unarchived experiment was previously part of a layer and you intend to include it again, you must manually reset allocation from that layer. ================================================================================ # Make a Decision URL: https://docs.statsig.com/experiments/ending/make-decision ================================================================================ # Make a Decision Making a decision for an experiment ships one group, including control, to all your users. After you make the decision, the experience users receive depends on whether the experiment uses a targeting gate. Experiment results remain accessible after you make a decision, but they stop updating. The last day of metrics is the day you make the decision. Use Make a Decision when you're ready to ship a group. To stop enrolling new users while users already exposed keep their variant, use [Stop Assignments](https://docs.statsig.com/experiments/ending/stop-assignments) instead. To stop enrollment and data collection without shipping a group yet, use [Conclude Experiment and Defer Decision](https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision) instead. ## Experiments with no targeting gate When you ship a group in an experiment with no targeting gate, the shipped group's parameter values become the default values for all your users. If the experiment uses parameters from a layer, the layer's parameters take the shipped group's values as their defaults. All your users see these values. For example, suppose you have a layer named Demo Layer with a parameter, `a_param`, whose default value is `layer_default`. ![Layer configuration showing default parameter value before experiment](https://docs.statsig.com/images/experiments/ending/make-decision/162633143-3ddd9652-4e99-4760-aac0-c89dec8ce70c.png) To run an experiment in Demo Layer, create an experiment named Demo Experiment. ![Experiment creation dialog in Demo Layer with control and test groups](https://docs.statsig.com/images/experiments/ending/make-decision/162633041-633de059-f676-4f76-a0ef-4d17b03648a0.png) Demo Experiment has two groups, Control and Test, each with a different value for the layer-level parameter `a_param`. ![Experiment parameter table comparing control and test values for a_param](https://docs.statsig.com/images/experiments/ending/make-decision/162633712-a5e889dd-32ba-4248-8524-b6d5555b4dfd.png) If you ship the Control group, `a_param` takes the Control group's value, `experiment_one_control`, as its default. ![Layer defaults updated to use control group value experiment_one_control](https://docs.statsig.com/images/experiments/ending/make-decision/162630956-1ffaa81f-c95f-4df7-9ced-b138cfe26d96.png) If you ship the Test group, `a_param` takes the Test group's value, `experiment_two_test`, as its default. ![Layer defaults updated to use test group value experiment_two_test](https://docs.statsig.com/images/experiments/ending/make-decision/162631111-daf31f6f-156b-481e-aa01-f29743f7e20a.png) ## Experiments with a targeting gate or targeting rules When you ship a group in an experiment that has a targeting gate or targeting rules, you choose whether to continue targeting after shipping. - If you discontinue targeting, the shipped group's parameter values become the default values for all your users. If the experiment uses parameters from a layer, the layer's parameters take the shipped group's values as their defaults. - If you continue targeting with a targeting gate, Statsig adds an override to the experiment's layer. Users who pass the targeting gate see the shipped group's parameter values. Users who fail the targeting gate see the default value: the layer-level parameter default or the default you set for the parameter in your code. - If you continue targeting with targeting rules, Statsig ships the experiment only to users who pass the inline targeting rules set in the experiment setup. > **Info:** > > If you continue targeting, shipping a group doesn't update the default value of any layer parameters. When you continue targeting, users who pass the targeting gate aren't eligible for future experiments in the layer. Statsig doesn't recommend shipping experiments with targeting on, especially when the experiment is in a layer. ## Roll out an experiment group Rolling out an experiment group lets you ship the winning variant without a sudden, large shift of traffic into that group. A scheduled rollout increases the shipped group's size to the target percentage in phases, reallocating users proportionally from all other groups. ### Set up rollouts 1. Open the **Make Decision** dropdown and select the group you want to ship. 2. In the _Configure Rollout_ section, turn on **Ship with Rollout**. 3. Under _Choose a Rollout Method_, select one of the following: - **Simple Rollout**: Enter a _Rollout %_. Statsig resizes the shipped group to that percentage immediately. - **Scheduled Rollout**: Ship the group gradually over a series of phases. ![Make decision rollout options interface](https://docs.statsig.com/images/experiments/ending/make-decision/549864e9-0509-4b44-a588-fd10ace1e365.png) Choosing a simple rollout clears any phases you previously scheduled. ![Ship with rollout configuration screen](https://docs.statsig.com/images/experiments/ending/make-decision/f200b795-0442-49ed-8c13-e220b3a77a81.png) ### Schedule rollout phases Select **Add a Scheduled Rollout** to open the _Gradual Rollout_ dialog, then select **Add Another Phase** for each phase you want. Each phase has a date, a time, and a pass percentage. ![Automated rollout phases configuration dialog](https://docs.statsig.com/images/experiments/ending/make-decision/6fab7c0e-2566-4d14-bdb6-b94102fb08ac.png) The _Preview_ section of the same dialog shows the resulting schedule and the current pass percentage before you commit. Select **Save** to keep the phases, then submit the decision. > **Note:** > > Rollout times come in 15-minute increments. Each configured phase is a discrete increase to the next rollout percentage, not a gradual rollout spread over the phase. ![Rollout schedule preview and commit interface](https://docs.statsig.com/images/experiments/ending/make-decision/f1fd04b3-e6a0-4e32-91a8-fb24279ab923.png) ### Resizing logic During each phase, Statsig resizes the rollout group to the percentage you set and scales all other groups proportionally. You have _n_ groups with sizes: G₁, G₂, ..., Gₙ Their total sum is: 100 = G₁ + G₂ + ... + Gₙ. Suppose you set one group, the k-th group, to a new size Gₖ′. Let Delta = Gₖ′ − Gₖ. Because the grand total must remain 100, Statsig adjusts the remaining groups proportionally. Let T = 100 - Gₖ Then, for each group i ≠ k, Gᵢ′ = Gᵢ − (Delta × Gᵢ / T). Each group other than k decreases (or increases, if Delta < 0) by its fraction of T. ### Rollout limitations - Experiment results freeze to a snapshot from when you make the rollout decision. - Rolling out a group to 100% doesn't fully ship the experiment. Configurations such as experiment or layer allocation, targeting, and overrides don't change. To fully ship the experiment, make a decision without specifying any rollouts. - You can roll groups out and back, but the rollout percentage can't be lower than the group's original size. - If you use warehouse exposure forwarding, the daily export excludes groups at 0% or 100% traffic share by default. Group rollout is separate from overall experiment allocation. Experiment lifecycle conditions also affect forwarding eligibility. If you need these exposures, contact Statsig Support. For details, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). ## Ship with a holdback > **Info:** > > Ship with holdback is an Early Access feature. Shipping with holdback releases an experiment variant (the shipped group) to most of your users while keeping a percentage of users in the control group for ongoing comparison. To ship with a holdback: 1. From the **Make Decision** dropdown, choose the variant to ship. 2. In the _Configure Rollout_ section, turn on **Ship with Holdback**. 3. Set **Holdback %** to the percentage of users to keep in the control (holdback) group. This value must be less than half of the control group's split percentage, and you can't change it after you make the decision. ![Ship with holdback dialog specifying control percentage in Make Decision modal](https://docs.statsig.com/images/experiments/ending/make-decision/046fcb33-d4c0-4ca4-b58a-1c8e931b6161.png) After you ship with holdback, Statsig allocates users as follows: - Statsig sets the control (holdback) group to the percentage you specified and assigns the remaining users to the shipped experience. - Statsig divides the shipped group into two segments: Test and Launched. The Test segment has the same percentage allocation as the holdback group, for an [equal-sized comparison](https://docs.statsig.com/experiments/holdouts-introduction#how-to-read-holdouts) of 50:50. The Launched segment no longer appears in experiment results, but users in this segment continue to receive the shipped experience. - Some users in control move to the shipped group to reach the allocation you set. Statsig doesn't reassign any user who has previously been in a test or shipped group to control. Statsig assigns new users, who have never seen the experiment, based on each group's allocation percentage. ![Pulse results display separating test and launched segments when shipping with holdback](https://docs.statsig.com/images/experiments/ending/make-decision/48f999c5-f7d0-47fd-9af8-96512802d6cf.png) Continue monitoring the experiment results, which compare the Test segment with the control (holdback) group. When you decide to end the holdback, make a decision to ship the variant to everyone, including users in the holdback. New results (Test segment compared with holdback) start when you ship with holdback. Statsig retains your original experiment results from the point of the holdback decision, and they remain accessible. The experiment history shows the new decision log entry and a **View Results Snapshot** button that opens a read-only snapshot of the original results. ![Snapshot of original experiment when using ship with holdback](https://docs.statsig.com/images/experiments/ending/make-decision/ship_with_holdback.png) ================================================================================ # Schedule an Experiment Stop URL: https://docs.statsig.com/experiments/ending/schedule-stop ================================================================================ # Schedule an Experiment Stop A scheduled stop runs Stop New Assignments or Conclude Experiment & Defer Decision on an experiment at a future date and time that you pick. Scheduling changes only when the action runs, not what the action does. Use it when you already know when an experiment should stop, for example at the end of a planned test window, so you don't have to end it by hand. To stop an experiment right away, run [Stop Assignments](https://docs.statsig.com/experiments/ending/stop-assignments) or [Conclude Experiment and Defer Decision](https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision) from the **Make Decision** dropdown instead. ## How a scheduled stop works An experiment has at most one pending stop: one date and time, and one action. The two actions behave the same way they do when you run them from the **Make Decision** dropdown: - **Stop New Assignments**: Statsig stops enrolling new users, and analysis continues. Users already assigned keep their group only when you use [Persistent Assignment](https://docs.statsig.com/server/concepts/persistent_assignment). Otherwise, they receive the default experience. For details, go to [Stop Assignments](https://docs.statsig.com/experiments/ending/stop-assignments). - **Conclude Experiment & Defer Decision**: Statsig stops delivery and analysis, and ships no group. For details, go to [Conclude Experiment and Defer Decision](https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision). Statsig checks for due stops about every five minutes. Statsig doesn't run a stop before the experiment starts. After the experiment starts, a stop whose time has passed runs on the next check. The date and time picker uses 15-minute steps in your browser's local time zone. You can pick any time from now through one year ahead. When you schedule a start and a stop together, the stop must be later than the start. Each action appears only after you turn it on in project settings. Go to _Settings > Product Configuration > Experimentation_, open the _Project_ tab, and select **Enable decision type - Stop New Assignments**, **Enable decision type - Conclude Experiment and Defer Decision**, or both. A scheduled stop is one of several ways to [end an experiment](https://docs.statsig.com/experiments/ending/ending-experiment). > **Note:** Experiments and decisions you can't schedule > > Autotune, switchback experiments, and Warehouse Native analysis-only experiments don't support a scheduled stop. You also can't schedule shipping a group or abandoning an experiment. ## Schedule a stop when you start an experiment Use the Start dialog when the experiment hasn't started and has no scheduled start. The dialog opens from the same **Start** button you use to [implement and launch the experiment](https://docs.statsig.com/experiments/implementation/implement). 1. Open the experiment and click **Start**. 2. Under _Start_, select **Immediately**, or select **At a scheduled time** and pick the start date and time. 3. Under _Stop_, select **At a scheduled time**. The default, **Manually**, runs the experiment until you stop it. 4. Pick the stop date and time, then select **Stop New Assignments** or **Conclude Experiment & Defer Decision**. 5. Click **Start & Schedule Stop** or **Schedule Start & Stop**. If your company requires reviews, click **Submit for Review**. ## Change a scheduled start and stop When the experiment hasn't started and already has a scheduled start, the experiment header shows **Change Scheduled Start**. - To edit the schedule, click **Change Scheduled Start**, then **Edit Scheduled Start**. The dialog shows the scheduled start and the scheduled stop together. - To cancel, click **Change Scheduled Start**, then **Cancel Scheduled Start**. If the experiment also has a scheduled stop, choose what to cancel: - **Scheduled start and stop**: The experiment doesn't start, so Statsig cancels the stop too. - **Scheduled stop only**: The experiment still starts at the scheduled time and runs until you stop it. ## Schedule a stop on a running experiment 1. Open the experiment and click **Make Decision**. 2. Under _Stop_, select **Schedule Stop**. 3. Pick the stop date and time, then select **Stop New Assignments** or **Conclude Experiment & Defer Decision**. 4. Click **Schedule Stop**. If your company requires reviews, click **Submit for Review**. ## Change or cancel a pending stop While a running experiment has a pending stop, the experiment header shows **Change Scheduled Stop** and hides **Make Decision**. - To edit the stop time or action, click **Change Scheduled Stop**, then **Edit Scheduled Stop**. - To cancel the stop, click **Change Scheduled Stop**, then **Cancel Scheduled Stop**. **Make Decision** returns after you cancel the scheduled stop. ## Reviews for scheduled stops If your project [requires reviews](https://docs.statsig.com/experiments/reviews), a reviewer approves the schedule, each edit, and each cancellation. When the stop time arrives, Statsig runs the approved action without asking for a second approval. > **Note:** When Statsig clears a pending stop > > Restarting the experiment clears its pending stop. If you turn off the project setting for the scheduled action, Statsig clears the pending stop instead of running it. ================================================================================ # Stop Assignments URL: https://docs.statsig.com/experiments/ending/stop-assignments ================================================================================ # Stop Assignments Stop Assignments stops enrolling new users into a running experiment while Statsig keeps analyzing the users already exposed. Users already assigned keep receiving their control or treatment experience. Use Stop Assignments after an experiment has run long enough that you want to analyze only the users exposed so far. Use [Conclude Experiment and Defer Decision](https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision) instead when you also want to stop data collection and return exposed users to the default experience. To ship one variant to all users, [make a decision](https://docs.statsig.com/experiments/ending/make-decision) on the experiment. To run the same action at a future date instead of now, [schedule the stop](https://docs.statsig.com/experiments/ending/schedule-stop). ## Prerequisites - Configure [Persistent Assignment](https://docs.statsig.com/server/concepts/persistent_assignment). Without it, users already exposed to a treatment group stop receiving the treatment experience after you stop assignments. You need Persistent Assignment even if you use stable identifiers. - Enable the decision type so that it appears in the Make Decision dropdown. Go to _Settings > Product Configuration > Experimentation_, open the _Project_ tab, and select **Enable decision type - Stop New Assignments**. ## Stop assignments for an experiment 1. Open the experiment and select the **Make Decision** dropdown. 2. Under _Stop_, select **Stop New Assignments**. 3. Optionally, enter a _Reason for Pausing Assignment_. 4. Select **Submit for Review**, or **Save** if your project doesn't [require reviews](https://docs.statsig.com/experiments/reviews). > **Warning:** > > You can't undo a stop. Statsig disables the **Stop New Assignments** option for the rest of the run, and the experiment can't go back to enrolling new users. You can still ship a group, [reset the experiment](https://docs.statsig.com/experiments/ending/reset), or [abandon it](https://docs.statsig.com/experiments/ending/abandon). ![Make Decision dropdown highlighting the Stop New Assignments option](https://docs.statsig.com/images/experiments/stop_assignment.png) ## What happens after you stop assignments - Statsig stops enrolling new users. Statsig doesn't check new users against the experiment; they receive the project's default experience. To ship one variant to new users, make a decision on the experiment or set the variant in code. - The experiment's allocation percentage on the _Setup_ tab doesn't change. Statsig stops enrollment independently of that value, so a stopped experiment still shows the allocation you configured. - Users already exposed continue to receive their control or treatment experience, if you configured Persistent Assignment. - Analysis continues as the experiment records new data points for already-exposed users. - The experiment history records the change as _Experiment Assignment Paused_. ================================================================================ # Conclude Experiment & Defer Decision URL: https://docs.statsig.com/experiments/ending/conclude-experiment-defer-decision ================================================================================ # Conclude Experiment & Defer Decision Conclude Experiment and Defer Decision stops user allocation and data collection on a running experiment and concludes its results without shipping a group. All previously exposed users return to the default experience. Use it when you want to separate running the experiment from making the ship decision, for example to review a fixed set of results with stakeholders before you choose what to ship. Use [Stop Assignments](https://docs.statsig.com/experiments/ending/stop-assignments) instead when exposed users should keep their variant while analysis continues on the users already exposed. ![Make Decision dropdown showing the Conclude Experiment & Defer Decision option](https://docs.statsig.com/images/experiments/ending/conclude-experiment-defer-decision/conclude_experiment.png) ## Enable the Conclude Experiment and Defer Decision option The option appears in the Make Decision dropdown only after you enable it in project settings. 1. Go to _Settings > Product Configuration > Experimentation_. 2. On the _Project_ tab, select **Enable decision type - Conclude Experiment and Defer Decision**. ![Project setting toggle for the Conclude Experiment and Defer Decision decision type](https://docs.statsig.com/images/experiments/ending/conclude-experiment-defer-decision/enable_conclude_setting.png) ## Conclude an experiment 1. Open the experiment and select the **Make Decision** dropdown. 2. Under _Stop_, select **Conclude Experiment & Defer Decision**. 3. Optionally, enter a _Reason for Stopping Experiment_. 4. Select **Submit for Review**, or **Save** if your project doesn't [require reviews](https://docs.statsig.com/experiments/reviews). Restarting a concluded experiment requires a [reset](https://docs.statsig.com/experiments/ending/reset). To run this action at a future date instead of now, [schedule the stop](https://docs.statsig.com/experiments/ending/schedule-stop). ## What happens after you conclude an experiment - Statsig stops enrolling new users. - All previously exposed users start receiving the default experience. - Statsig stops collecting data for the experiment and concludes the results. - You can still ship the control or a test variant, reset the experiment, or abandon it. ## Reloads after you conclude an experiment Exposure and metric data may change slightly if you trigger another reload after you conclude an experiment. These changes don't mean Statsig is still exposing new users. The timestamp of when you concluded the experiment may differ from when the latest exposure data landed in your warehouse during the previous reload. Because of this difference, additional exposures from that time window may appear in the refreshed data. ================================================================================ # Abandon an Experiment URL: https://docs.statsig.com/experiments/ending/abandon ================================================================================ # Abandon an Experiment Abandon an experiment when a technical error or an unforeseen issue stopped it from reaching a conclusive result. Abandoning an experiment moves it to the abandoned state, a finished state in which the experiment no longer enrolls users and every user receives the default experience. The experiment's results stay available. Abandoning isn't a verdict on the variants. It records that the run produced no reliable data. If control turned out to be the better experience, [ship control](https://docs.statsig.com/experiments/ending/make-decision) instead. Use [Reset](https://docs.statsig.com/experiments/ending/reset) when one group has a bug you plan to fix and you want to run the same test again. ![Make Decision dropdown showing the Abandon Experiment and Reset options](https://docs.statsig.com/images/experiments/ending/abandon/abandon.png) ## Abandon an experiment 1. Open the experiment and select the **Make Decision** dropdown. 2. Under _Abandon_, select **Abandon Experiment**. 3. Optionally, enter _Experiment Notes_ describing why you abandoned the run. 4. Select **Submit for Review**, or **Save** if your project doesn't [require reviews](https://docs.statsig.com/experiments/reviews). ## What happens after you abandon an experiment - The experiment's status becomes Abandoned and it stops enrolling users. - All users, including users already exposed, receive the default experience defined in code or in the layer. - The experiment's results remain available for review. - To run the test again, [reset](https://docs.statsig.com/experiments/ending/reset) the abandoned experiment and start it. The reset generates a new salt, so users are reassigned and don't necessarily land in the group they were in before. - You can [archive](https://docs.statsig.com/experiments/ending/ending-experiment#archive-an-experiment) the experiment to make it read-only. ================================================================================ # Reset an Experiment URL: https://docs.statsig.com/experiments/ending/reset ================================================================================ # Reset an Experiment Resetting an experiment returns it to the unstarted state so you can fix a problem and run the test again. Statsig generates a new salt, creates new group IDs, clears the start and decision state, and starts a new analysis window. Reset an experiment when a bug or a bad variant invalidated the run and you want the same test to start over. Use a different action when you don't need a fresh run: - To end the experiment without running it again, [abandon it](https://docs.statsig.com/experiments/ending/abandon). - To turn off one bad variant while the rest of the experiment keeps running, [disable that group](https://docs.statsig.com/experiments/implementation/disable-group). - To begin a new analysis window without re-randomizing anyone, [restart results](https://docs.statsig.com/experiments/interpreting-results/read-results#restarting-results). A restart keeps the existing salt, so users keep their group assignments. ## Reset an experiment 1. Open the experiment and select the **Make Decision** dropdown. 2. Select **Reset**. 3. Start the experiment again after you fix the issue that prompted the reset. ## What happens after you reset an experiment - The experiment returns to the unstarted state. Every user receives the default experience, either the value defined in code or the layer default, until you start the experiment again. - Statsig generates a new salt. Because the salt determines which group a user hashes into, users are randomly reassigned when you start the experiment again and don't necessarily land in the group they were in before. This reassignment keeps a bug or bad experience in the previous run from affecting the same group after you address the issue. - Statsig creates new group IDs and preserves each group's name and size. - Statsig clears the analysis window and saves a snapshot of the results collected so far. - You can [archive](https://docs.statsig.com/experiments/ending/ending-experiment#archive-an-experiment) the experiment after a reset to preserve its history and make it read-only. ## Treat the new run as a separate experiment A reset creates a new iteration rather than undoing the previous one, and Statsig can't restore an experiment to its pre-reset running state. - Results from the earlier run stay visible in the experiment's history, but don't combine them with the new run as a single scorecard. Mixing a pre-reset period with a post-reset period introduces assignment artifacts that bias the comparison. - Setting the salt back to its previous value doesn't resume the earlier run. It brings future assignment closer to the old hash mapping, but the analysis window has already restarted. - A reset doesn't restore allocation on an experiment whose allocation was set to zero. Raise allocation as a separate edit after you reset. ================================================================================ # Disable a Group URL: https://docs.statsig.com/experiments/implementation/disable-group ================================================================================ # Disable a Group Disabling a group turns off one test group in a multi-group experiment while the other groups keep running. Users assigned to the disabled group receive the default experience instead. Disable a group when one variant performs poorly or creates a bad user experience but the rest of the experiment is still valid. If the whole experiment is failing, [make a decision](https://docs.statsig.com/experiments/ending/make-decision) and ship control instead. ## What to expect when you disable a group - Users already assigned to the disabled group receive the default experience. - Statsig continues to assign new users to the disabled group, and those users also receive the default experience. Because assignment continues, the disabled group doesn't trigger a Sample Ratio Mismatch (SRM). - Statsig continues to show the group, log its exposures, and calculate its experiment results, so you can verify that user experiences recover after you disable the group. ## Disable a group 1. Log into the [Statsig console](https://console.statsig.com) and select **Experiments** in the left-hand navigation panel. 2. Select the experiment where you want to disable a group. 3. Click the **...** menu in the top right corner. 4. Select **Disable A Group**. 5. Select the experiment groups you want to disable, then select **Confirm**. ![Experiment overflow menu showing Disable a Group option](https://docs.statsig.com/images/experiments/implementation/disable-group/disable_group.png) ![Disable group dialog listing experiment groups with toggles](https://docs.statsig.com/images/experiments/implementation/disable-group/disable_experiment_groups.png) ## Reenable a group To reenable a previously disabled group, click the **...** menu and select **Disable or Enable A Group**. ![Menu option to disable or enable a group in experiment controls](https://docs.statsig.com/images/experiments/implementation/disable-group/2fa3cb71-9a46-46f1-bb11-b8e7f07df9c6.png) ![Modal showing reenable group selections](https://docs.statsig.com/images/experiments/implementation/disable-group/a56e7f14-53e9-4d41-8266-d70de1ec3ebf.png) > **Info:** > > Users in a reenabled group may have received more than one treatment during the experiment, and the group's metric data may reflect those multiple experiences. ================================================================================ # Switchback Tests URL: https://docs.statsig.com/experiments/types/switchback-tests ================================================================================ # Switchback Tests A switchback test switches an entire population back and forth between test and control treatments on a set cadence, instead of splitting the population into two fixed groups. Statsig compares the time windows when the population was in test against the windows when it was in control. Use a switchback test when one user's treatment changes the experience of other users, as in a two-sided marketplace, or when giving different users different variants isn't feasible for fairness, legal, or logistical reasons. If user experiences are independent, run a standard [A/B test](https://docs.statsig.com/guides/abn-tests) instead. Warehouse Native projects run switchback experiments with [Switchback V2](https://docs.statsig.com/experiments/types/switchback-v2). Switchback tests are common in marketplaces, where a traditional A/B test on one side of the marketplace can change the rest of the marketplace through network effects and bias the results. A switchback test often runs across multiple buckets, typically regions or other defined groups, that Statsig flips between test and control over the course of the experiment. ## Example: rideshare pricing Consider a rideshare platform that wants to test pricing. A standard A/B test splits riders into two groups: one with a higher price and one with a lower price. Riders with the lower price request rides at a higher rate and consume the available driver supply in an area. Riders with the higher price then face both a higher ride estimate and longer ETAs, which makes them even less likely to request a ride. The decreased request rate in the higher-price group could come from the higher prices or from the longer ETAs, so the experiment design has introduced bias into the results. A switchback test resolves this. Instead of splitting users, 100% of riders and drivers in a given metro switch in and out of the new pricing plan hourly. The test then measures the impact on overall ride request rates during hours when prices were higher against hours when they were lower. ## How Statsig computes switchback results Statsig computes results in three steps: it attributes events to switchback buckets, calculates bucket-level and variant-level metrics from those events, then calculates the difference in means between test and control with bootstrapped confidence intervals. ### Event attribution Statsig attributes events to a bucket based on the timestamp and `unit_id` of the exposure, the length of the attribution window, and the timestamps of subsequent events for that `unit_id`. A time window and a grouping attribute define each bucket. For example, Statsig exposes user 123 to bucket A at 9:15 AM, and the test has an attribution window of 90 minutes. Statsig includes all events that user 123 triggers between 9:15 AM and 10:45 AM in the metric calculations for bucket A. ### Bucket-level metrics After Statsig has all the events for a bucket, it calculates the scorecard metrics from those events. ![Bucket metrics table summarizing switchback exposures](https://docs.statsig.com/images/experiments/types/switchback-tests/adf0e2b0-0e4c-47b9-8a04-d0f01f130f7c.png) For sum and count metrics, Statsig uses the mean value per unit exposed to that bucket. ![Metric detail view showing per-unit averages within a bucket](https://docs.statsig.com/images/experiments/types/switchback-tests/8f234be9-7848-46fa-a84d-6d6c7facf51b.png) ### Variant-level metrics Statsig calculates overall metric means for test and control by aggregating values across all buckets in that variant. If there are `M` buckets in the test group, the mean value of a ratio metric is: ![Formula showing ratio metric mean calculation across switchback buckets](https://docs.statsig.com/images/experiments/types/switchback-tests/8239da03-6f94-47b0-b9b5-39e87566f7fc.png) The mean of a sum or count metric is: ![Formula for sum or count metric averages in switchback tests](https://docs.statsig.com/images/experiments/types/switchback-tests/220515f6-e0b0-4f64-a441-e5facdde5530.png) ### Deltas and confidence intervals Statsig calculates the treatment effect as: ![Equation for treatment effect delta between test and control](https://docs.statsig.com/images/experiments/types/switchback-tests/1fb290c9-f253-4be0-9bef-b212f74f6e0a.png) Statsig obtains the bootstrapped confidence intervals as follows: 1. Collect a bootstrap sample with replacement from the set of test buckets, and separately from the set of control buckets. 2. Calculate the difference in means between the test and control samples. 3. Repeat steps one and two 10,000 times to produce a distribution of metric deltas. 4. Take the 95% confidence interval as the range from the 2.5% quantile to the 97.5% quantile of that distribution. In general, the confidence interval with significance level $\alpha$ is: ![Bootstrap confidence interval formula for switchback tests](https://docs.statsig.com/images/experiments/types/switchback-tests/bea68643-3ade-4daf-a6fa-79e39a7274d7.png) ## Set up a switchback test When you create an experiment, go to _Advanced Settings > Experiment Type_ and select **Switchback Test**. ![Experiment type menu selecting switchback test](https://docs.statsig.com/images/experiments/types/switchback-tests/359bcb6f-5cc4-4126-ac78-354c8f3b0474.png) Switchback test configuration adds two aspects to the standard experiment setup: 1. **Targeting**: The population or populations you run your experiment on. 2. **Schedule**: The switching frequency and the starting treatment for each pre-defined population. ### Targeting There are two ways to define targeting: - **Targeting Gate**: Specify a targeting gate to define your target experiment population, the same as any other experiment on Statsig. - **Bucketing Method**: Bucket users either by pre-defined buckets or by randomizing across an ID type. ![Switchback targeting configuration showing gate and bucketing options](https://docs.statsig.com/images/experiments/types/switchback-tests/a3e951fb-9a62-48be-9fec-59fcc2003d17.png) With pre-defined buckets, you specify the buckets yourself, such as Country, Locale, or a custom field you log. Use this option when you have a few pre-defined populations that you want to switch in and out of test and control over the course of the experiment. ![Buckets configuration table listing predefined regions](https://docs.statsig.com/images/experiments/types/switchback-tests/e53ea760-91c1-40e3-85fd-3da3d886d1ed.png) With an ID type, Statsig randomizes across the ID type you choose. For example, choosing a custom ID such as CityID randomizes different CityIDs across test and control over the switchback windows. Use this option when you have a very large or changing number of experiment units to randomize across. > **Info:** > > Randomized bucketing is an advanced feature. Contact the support team, your sales contact, or the [Slack community](https://statsig.com/slack) so they can enable it. ![Randomized ID bucketing interface selecting custom ID](https://docs.statsig.com/images/experiments/types/switchback-tests/3c79d1c1-8b15-401c-9635-6b3d4b08d416.png) ### Schedule The _Schedule_ section of experiment setup has these fields. Which fields appear depends on the bucketing method you select. | Field | Applies to | Description | | --- | --- | --- | | Start time | Both bucketing methods | When the switchback test begins. | | Duration | Both bucketing methods | How long the test runs, in days. | | Assignment window size | Both bucketing methods | The length of each switchback window, in minutes. | | Burn-in and burn-out periods | Both bucketing methods | Time intervals, in minutes, at the start and end of each switchback window whose exposures Statsig discards from analysis. Use these when the previous treatment might bleed over while a population switches between test and control. | | Starting phase | Pre-defined bucketing only | The treatment group each bucket starts in. | ![Switchback schedule editor specifying assignment windows and bucket starting phases](https://docs.statsig.com/images/experiments/types/switchback-tests/67ed1aee-f5aa-49b6-b684-a9919b59d5ca.png) ## Reading results Diagnostics and metric lift results for switchback tests resemble Statsig's traditional A/B tests, with a few differences: - **No hourly results**: Because a switchback experiment starts with all-test or all-control exposures, Statsig disables hourly results until there is a meaningful amount of data. Use the _Diagnostics_ tab in the meantime to verify that checks arrive and bucket as expected. - **No time series**: Switchback tests don't support the Daily or Days Since First Exposure time series. The bootstrapping methodology pools all available days together to achieve sufficient statistical power. - **No dimension breakdown**: Switchback tests don't support breaking down a metric by user property or event property. - **No CUPED or sequential testing**: Switchback tests don't yet support CUPED and sequential testing. ![Switchback experiment pulse results showing bucket-level metrics](https://docs.statsig.com/images/experiments/types/switchback-tests/657cce2d-22b0-41cf-8b43-2d3f05cfefb8.png) ================================================================================ # Running an A/A Test URL: https://docs.statsig.com/experiments/types/aa-test ================================================================================ # Running an A/A Test An A/A test splits traffic into two groups that receive the same experience, so you can confirm that exposures flow into Statsig and that your metrics compute correctly before you run a real A/B test. Because neither group changes the product, the test is a low-stakes way to check your setup. Run an A/A test before your first A/B test, or after you change metric definitions. This tutorial creates and implements an A/A test as a feature gate in Statsig. Statsig also runs simulated A/A tests for you every day without any code on your side; use those results when you want to validate the stats engine itself rather than your instrumentation. You need a [Statsig account](https://console.statsig.com/sign_up) and the [Statsig client SDK](https://docs.statsig.com/sdks/quickstart) integrated into an existing application. ## Step 1: Create a feature gate in the console The easiest way to run an A/A test in Statsig is with a [feature gate](https://docs.statsig.com/feature-flags/overview). You can also use an [experiment](https://docs.statsig.com/guides/abn-tests), but this tutorial uses a feature gate. Log into the [Statsig console](https://console.statsig.com/) and select **Feature Management > Feature Gates** in the left-hand navigation panel. Click **Create** and enter a name and optional description for your feature gate. This example calls the feature gate `aatest_example`. Click **Create**. ![Empty create feature gate dialog](https://docs.statsig.com/images/experiments/types/aa-test/163246908-24494f12-9d2e-4d8b-8e3e-4fc0ad9c7e41.png) On the _Setup_ tab, define the rules for this feature gate. Click **+ Add New Rule**. You can run an A/A test on a specific user group or platform, but this tutorial divides all traffic 50/50 and delivers the same experience to each group. ![Empty add new rule dialog](https://docs.statsig.com/images/experiments/types/aa-test/163247089-360857f8-ada3-46af-ac82-e41fc99274b5.png) Under **Criteria**, select **Everyone** (you may need to scroll up), name your rule, and set the **Pass Percentage** to 50%. Click **Add Rule**, then click **Save Changes** in the upper right-hand corner. ![Add new rule dialog with Everyone criteria and 50% pass percentage](https://docs.statsig.com/images/experiments/types/aa-test/163247141-30c96f8a-8257-4b39-aa9f-830bb3c89228.png) Your feature gate setup now looks like this: ![Feature gate setup showing the completed 50% rule](https://docs.statsig.com/images/experiments/types/aa-test/163247211-aacb2c54-1088-4c4a-ab7b-64e393383bdb.png) Verify that the gate works by entering some sample user IDs in the console. Roughly 50% of the IDs should pass and 50% should fail. ![Gate check showing a sample user ID passing](https://docs.statsig.com/images/experiments/types/aa-test/163247281-c0fb8089-f418-41af-a3a7-d8e684a3cdf3.png) ![Gate check showing a sample user ID failing](https://docs.statsig.com/images/experiments/types/aa-test/163247287-7d565983-8253-4841-a65a-0f74d2e103b2.png) ## Step 2: Check the feature gate in your code Copy the code snippet from the upper right corner of your feature gate page (under the **< >** symbol) and add it to your application at the point where you want to call the A/A check. ```jsx statsig.checkGate("aatest_example") ``` When a user renders this page in their client application, a live log stream appears in the Statsig console on the _Diagnostics_ tab of your feature gate. ![Diagnostics log stream showing live gate checks](https://docs.statsig.com/images/experiments/types/aa-test/163247712-4610d7b4-188f-4418-a696-127b3c2f54da.png) ## Step 3: Review A/A test results Within 24 hours of the gate going live, cumulative exposures appear on the _Pulse Results_ tab of your feature gate. ![Cumulative exposures chart on the Pulse Results tab](https://docs.statsig.com/images/experiments/types/aa-test/163247787-be1e816c-f715-4fd3-ad59-3a6caf48027a.png) The _Pulse Results_ tab shows your logged exposures and their distribution. If the distribution looks incorrect, check the _Diagnostics_ tab for day-by-day exposure breakdowns at both the check and user level. The _Metric Lifts_ panel shows how all your tagged metrics perform. ![Pulse results with metric lifts for an A/A test](https://docs.statsig.com/images/experiments/types/aa-test/163248267-7bd7419a-59e0-4d58-b8e5-8ace95ed74d9.png) Check two things in the results: - **Exposures**: Confirm that exposures flow through from your product as expected. If you don't see exposures, use the _Diagnostics_ tab and the _Exposure Stream_ to debug. - **Metric results**: Roughly 5% of your metrics should show a statistically significant change, because Statsig's stats engine uses a 95% confidence interval. Run your A/A test for at least a week, and long enough to reach most of your weekly active users. ## Simulated A/A tests Statsig runs for you Statsig runs simulated A/A tests every day in the background for every company on the platform. Like the test in this tutorial, a simulated A/A test has the structure of an A/B test, but both groups receive the same experience. A/A tests can be online or offline. An online A/A test, like the one in this tutorial, runs on real users: your app checks a gate or experiment through the Statsig SDK, Statsig logs the assignment, and users see no difference in experience. Because there is no real effect, you expect to see only statistical noise. With 95% confidence intervals, only about 1 in 20 metrics shows a stat-sig difference between control and test. ### Offline A/A tests An offline A/A test runs on one unit type per request and works like this: 1. Query a representative sample of your data. 2. Randomly assign subjects to test or control. 3. Compute the relevant metrics for test and control and run them through the stats engine. 4. Measure the percentage of false positives. With a typical p-value cutoff of 0.05, expect a false positive rate of about 5%. Statsig runs 100 tests per request. Download the running history of your simulated A/A test performance from the _Tools_ menu in the Statsig console. ### Simulated A/A test file columns | Column name | Description | | --- | --- | | `metric_name` | Name of the metric | | `metric_type` | Type of metric | | `unit_type` | The unit used to randomize (for example, `userID`) | | `n_tests` | The number of tests run | | `pct_ss_95_pct_confidence` | The percentage of tests that have a stat-sig result for this metric | | `avg_units_per_test` | The number of units (often users) sampled into the A/A test | | `avg_participating_units_per_test` | The number of units in the test with a value for this metric | ![A/A test results table showing statistical significance percentages](https://docs.statsig.com/images/experiments/types/aa-test/199562491-84d9b7c4-1cea-4308-a0a9-c04a14a41671.png) ================================================================================ # SEO Experimentation with Statsig URL: https://docs.statsig.com/experiments/types/seo-testing ================================================================================ # SEO Experimentation with Statsig SEO experimentation tests changes to your web pages, such as titles, metadata, structured data, or layout, to measure how they affect search rankings and organic traffic. Because search crawlers need a consistent version of each URL, you randomize by page instead of by user. Statsig hashes each canonical URL into a control or test bucket, then compares metrics such as impressions, average position, and organic sessions across the two groups. Use it when you run a large, templated site and want proof that a page change moves organic traffic before you roll it out everywhere. If your change affects a shared system over time rather than individual pages, run a [switchback test](https://docs.statsig.com/experiments/types/switchback-tests) instead. Airbnb's growth team developed this approach in 2017 to test a new landing page template across more than 100,000 city URLs, where user-level randomization was impossible because crawlers needed consistent page versions. ## Select a deterministic page bucket Crawlers must see a consistent version of each URL during the test window, so you can't randomize by user. Instead, hash the canonical URL into buckets. In Statsig, add `page_url` as a custom unit ID: 1. From _Project Settings_, go to _Custom Unit IDs_. 2. Enter a name and description. The custom unit ID is immediately available to experiments, gates, and dynamic configs. Statsig then deterministically hashes each page into control or test and keeps the assignment stable across sessions. > **Note:** > > Strip the `http` or `https` scheme and any query parameters from `page_url`, so that Statsig hashes only the stable base URL. ## Define metrics before shipping Make sure the metrics you want to measure are in your data warehouse, keyed on `page_url`. Register them in Statsig's metric catalog. Because the same pipeline powers feature experiments, your existing CUPED or stratified-sampling settings apply automatically. ### Example metrics | Layer | Metric source | Why it matters | | --- | --- | --- | | Indexing lag | Impressions, average position (Search Console) | Early signal during re-crawling | | Primary KPI | Organic sessions keyed by `page_url` (Statsig events) | Measures traffic that lands | | Quality guardrail | Conversion, bounce, read-depth, revenue | Confirms the traffic is useful | ## Implement the change behind an experiment 1. Create an experiment in the Statsig console, for example `seo_title_test`. 2. Target the custom unit ID `page_url` with a 50/50 split across control and test. 3. Expose the variant in the template renderer or CDN edge function. ## Ship, monitor, and decide 1. Use [power analysis](https://docs.statsig.com/experiments/power-analysis) to determine how long to run the experiment based on traffic volume. 2. Expect first signals in 2 to 7 days. Wait for re-indexing to plateau before you treat results as stable. 3. Merge the winner into your template and archive the test. Experiment summaries remain searchable after archival. ### SEO-specific guardrails | Guardrail | What to watch | Why it protects you | | --- | --- | --- | | Indexation change | `indexed_pages` compared with baseline | A template change that blocks crawling (robots, canonicals, noindex) shows a sharp drop long before traffic falls | | Cannibalization ratio | Average URLs served per query | Multiple pages newly ranking for the same query dilute CTR and can reduce combined traffic | | HTTP response mix | Percentage of 410, 301, and 200 responses | A bulk 410 (gone) or misconfigured 301 can remove long-tail pages from the index | | Core Web Vitals drift | LCP and CLS at p75 | Page-speed regressions can hurt rankings without other symptoms | | Crawl budget | Average TTFB and bytes per page | Slow or bloated pages decrease crawl rate | ## Page-level changes worth testing | Theme | Why it might move organic traffic | Typical implementation | | --- | --- | --- | | Title and meta variants | Query matching, CTR uplift | Add or remove a brand suffix, switch noun phrasing to verb phrasing, insert a dynamic price | | Structured data | Rich-result eligibility | Inject FAQ, HowTo, Breadcrumb, or Product schema blocks | | Internal-link blocks | Crawl priority and PageRank flow | Reorder the related-articles widget; test link count caps | | Content snippets | Relevance and long-tail keywords | Auto-generate a 50-word intro compared with none; expand FAQ length | | Canonical and hreflang tags | Duplicate-content handling | Toggle self-canonical compared with cluster canonical; add `hreflang="x-default"` | | Media handling | CLS and LCP scores influence rankings | Defer off-screen images; inline the critical hero image; switch to AVIF | | Pagination model | Crawl depth and index coverage | Compare classic `?page=` URLs, `rel="next/prev"`, and load-more buttons | | Performance budgets | Core Web Vitals ranking factor | Split JS into 200 ms chunks compared with baseline; purge CSS and inline critical CSS | | Ad layout | CLS penalties, user engagement | Reserve fixed ad slots compared with dynamic slots; lazy-load below the first viewport | | Schema position | Parser friendliness | Move the JSON-LD block to `` compared with the end of `` | ================================================================================ # Contextual Bandit (Autotune AI) URL: https://docs.statsig.com/autotune/contextual/introduction Updated: 2025-09-18 ================================================================================ # Contextual Bandit (Autotune AI) Contextual Multi-Armed Bandits are a subset of Multi-Armed Bandits that use context about a user to personalize their experience. Autotune AI predicts outcomes for each variant and selects the best outcome while accounting for uncertainty. Autotune AI prefers variants with high uncertainty over variants with slightly better predictions but low uncertainty, which drives exploration. Use a contextual bandit to personalize the variant Statsig serves each user based on their context features. Use a non-contextual multi-armed bandit to converge on one global winner for all users. ## Use cases Contextual bandits bridge the gap between un-personalized solutions and fully fledged ranking solutions. The main limitation is that contextual bandits: - Have a fixed output set of variants they can show - Have limited ability to account for complex context on the "object" being seen/predict for novel content (e.g. video ranking) Their simplicity also provides advantages. Statsig's Autotune AI evaluates in near-real-time on both the server and client, taking a few milliseconds or less to return the ideal experience for a given user context. Contextual bandits are also simple to set up and test. You can set up a test in less than an hour, get model results the next hour, and start seeing experiment results in the Statsig console the hour after that. For more discussion on use cases and motivations, refer to the [Statsig blog](https://www.statsig.com/blog/statsig-autotune-contextual-bandits-personalization). ## Methodology Statsig's autotune AI uses a LinUCB based approach. This paper is a good introduction to the topic: [Li, Chu, Langford, Schapire](https://arxiv.org/pdf/1003.0146). For coverage of regret analysis, these lecture notes from [Jain from the University of Washington](https://courses.cs.washington.edu/courses/cse599i/18wi/resources/lecture10/lecture10.pdf) are a useful resource. Autotune AI works with categorical and numerical features. Statsig converts key-value pairs attached to the custom object on the Statsig user into categorical or numerical features based on their data type. Statsig one-hot-encodes categorical features. You don't need to build complex training pipelines, though many customers pass pre-evaluated user attributes or predictions as context objects. > **Note:** > > Statsig's console supports specifying features in advance, and an optional excluded feature list for keys to leave out of training. Specifying features can help you identify which features to fetch for the bandit when lookups are expensive or live. For how the feature list and excluded feature list interact, refer to [Training settings](https://docs.statsig.com/autotune/contextual/getting-started#training-settings). For Warehouse Native customers, planned work allows joining entity properties during analysis, enabling you to plug in your own feature store for Autotune AI analysis, similar to the approach used with [CURE](https://docs.statsig.com/statsig-warehouse-native/cure/introduction). Statsig selects the best model (for example, Ridge or Logistic regression) based on your data types and performance, then generates a model from your data. The estimated standard error of the model produces a prediction confidence interval. During evaluation, Statsig uses user context to predict an outcome for each variant and applies the corresponding confidence interval to that prediction. The best variant is the one with the highest upper end of a 95% confidence interval. To adjust the interval size, modify the exploration parameter on the Autotune setup page. For a detailed discussion, refer to the [Methodology](https://docs.statsig.com/autotune/contextual/methodology) page. > **Note:** > > You can also fetch a ranked list from Statsig and manually expose the variants you show to the user. This approach is useful when you have client-side filtering or want to show multiple options. Refer to [Advanced Usage](https://docs.statsig.com/autotune/using-bandits). ## Drawbacks Because Statsig manages the models, it can't guarantee perfect model tuning, and Statsig doesn't offer more advanced models such as neural networks. If recommendations are a critical business problem, this feature can serve as a starting point but isn't an appropriate long-term solution. The current approach balances simplicity, speed, and regret minimization. Statsig may not fully support specific use cases such as real-time updates. Because the models generally assume linearity, they may not capture complex user interactions. This approach works best for broad-level effects, though feature interaction terms can provide reasonable predictive power for conditional relationships between predictors and outcomes. ## Outcome types Autotune AI supports multiple model types internally, covering both classification use cases (for example, whether a user clicks a button) and continuous outcomes (for example, how much time a user spends reading articles). You can optimize for both "outcomes" and "metrics." To minimize a metric such as latency, disable the "higher is better" setting for that metric. For classification cases, Autotune AI identifies whether any outcome occurs within its attribution window. For continuous cases, Autotune AI requires an event name and field name, and uses the numerical value associated with that field. ## Training Statsig runs training pipelines hourly. For Warehouse Native customers, Statsig processes data in your warehouse and uses an anonymized feature set to train the models. Statsig exports exposures on-demand for each load up to the first million, and in daily batches after that. Outcomes come from metric sources you connect from your warehouse. For cloud customers, Statsig processes and trains the data entirely on its servers. Statsig doesn't use [private attributes](https://docs.statsig.com/guides/private-attributes) as features for training. ## SDK support Statsig supports contextual autotune in all Client SDKs, but only in the following server SDKs: - [Node](https://docs.statsig.com/server-core/node-core) - [Python](https://docs.statsig.com/server-core/python-core) - [Java](https://docs.statsig.com/server-core/java-core) - [Elixir](https://docs.statsig.com/server-core/elixir-core) - [Rust](https://docs.statsig.com/server-core/rust-core) - [Go](https://docs.statsig.com/server/go) v1.39.0+ - [Ruby](https://docs.statsig.com/server/ruby) v2.4.0+ ================================================================================ # Get Started with Autotune AI URL: https://docs.statsig.com/autotune/contextual/getting-started Updated: 2025-09-18 ================================================================================ # Get Started with Autotune AI Autotune AI personalizes which variant each user sees based on their context features, automatically optimizing a single goal metric. Setting it up takes a few steps: create a contextual autotune in the Statsig console, choose the goal metric to optimize, define your variants, then fetch the assigned variant in your app code. Use it when you want to optimize per user instead of picking one winning variant for everyone. > **Warning:** > > Statsig supports contextual autotune in all Client SDKs, but only in the following server SDKs: > > - [Node](https://docs.statsig.com/server-core/node-core) > - [Python](https://docs.statsig.com/server-core/python-core) > - [Java](https://docs.statsig.com/server-core/java-core) > - [Elixir](https://docs.statsig.com/server-core/elixir-core) > - [Rust](https://docs.statsig.com/server-core/rust-core) > - [Php](https://docs.statsig.com/server-core/php-core) > - [Ruby](https://docs.statsig.com/server/ruby) ## Set up your Contextual Autotune Configure your contextual autotune in the Statsig console. You can also configure it programmatically through the Statsig console API. ## Create the contextual autotune Log in to your Statsig console and navigate to _Experimentation > Autotune_. ![Statsig console navigation with Autotune section highlighted](https://docs.statsig.com/images/autotune/contextual/getting-started/167d5e87-c155-4465-9419-bcf018c496cb.png) Select **Create**. Name your contextual autotune and, optionally, specify the goal so other users can understand the motivation behind it. ![Create contextual autotune dialog with name and goal fields](https://docs.statsig.com/images/autotune/contextual/getting-started/b16fb9a6-80f4-495c-8ebc-b0cdcdb1d8a8.png) Set your autotune type to **Contextual**. ![Autotune type selector set to Contextual](https://docs.statsig.com/images/autotune/contextual/getting-started/4398ae6f-0763-49c0-a49b-804daece4da8.png) ## Configure optimization If optimizing for discrete outcomes such as: - User clicks - Checkouts - Actions Choose **Event Occurring** as the outcome type. If optimizing for a continuous output such as: - Revenue - Latency Choose **Event Value** and set the directionality. Also choose the field from your log or metric source (Warehouse Native) to use for the value. For Warehouse Native customers, specify the metric source and any optional filters for your target event. ![Optimization settings screen choosing event outcome and metric source](https://docs.statsig.com/images/autotune/contextual/getting-started/4885eac2-38ec-42f1-bd52-592b728623a0.png) Statsig highly recommends wrapping contextual autotunes in an experiment, but doesn't require it. You can set this up before or after your contextual autotune. The experiment wraps autotune calls in code and measures the overall impact of using this contextual autotune in your project. ## Training settings The remaining settings have defaults, but you can tune them as needed: - **Exploration window**: How long to serve traffic randomly to bootstrap bandit exploration. This is for solving the cold start / no data problem. The initial time period where Autotune equally splits traffic. This is useful for noisy or temporal metrics where hourly data swings can bias Autotune's initial measurements. - **Attribution window**: How long after a user sees your variant to count outcome events. If you set it to 1 hour, a user has 1 hour to take action after seeing the experience. - **Exploration rate**: Controls how much the bandit favors exploration over exploitation. 0 uses only the best prediction without confidence intervals. 1 uses the 99.9% CI instead of the 95% CI for exploration. - **Long-term exploration allocation %**: The percentage of traffic that Statsig always randomly assigns. Use higher values for contextual autotunes you plan to run for a long time, to help avoid model drift. - **Feature list**: A list of features Statsig should use to train the model. This acts as a filter. If you leave it empty, Statsig reads every custom attribute, except keys on the excluded feature list. The main use case is fetching the feature list through the Console API to understand which features a given contextual autotune requires for on-demand evaluation. For categorical features, include the raw name. For example, `onboarding_industry`, not `onboarding_industry: BANKING`. - **Excluded feature list**: Optional keys to leave out of model training. Each key matches a custom attribute you send on the Statsig user. Statsig applies the feature list first, then drops these keys. Statsig excludes a key that appears on both lists. When the feature list is empty, Statsig trains on every custom attribute except the excluded keys. For categorical features, use the raw key, for example, `email`, not an encoded value. You can set this on cloud and Warehouse Native contextual autotunes. Send the list as `excludedFeatureList` in the Console API and MCP. On update, omit `excludedFeatureList` to keep the saved list, or send `[]` to clear it. Statsig applies the updated lists on the next hourly training run. If your attribution window is longer than your exploration window, Autotune continues to split traffic equally until the attribution window ends. Until then, Autotune doesn't have complete outcome data. ![Training settings configuration showing exploration and attribution options](https://docs.statsig.com/images/autotune/contextual/getting-started/8c87e142-247d-42b3-8baa-04f8967ae400.png) Set up your variants. Variants are configurations you fetch in code. For example, the configuration below sends a `red` value to your codebase, which you can pass to the color setting on a button. ![Variants list showing configuration keys and values for contextual autotune](https://docs.statsig.com/images/autotune/contextual/getting-started/591c0b49-2a40-4bb9-9bef-311bd1d64651.png) ![Variant detail editor specifying contextual parameters like button color](https://docs.statsig.com/images/autotune/contextual/getting-started/10b13396-9bb5-4045-b514-45b0861885cb.png) ## Use the Contextual Autotune in code (Python example) The following code assumes you have your server secret key. Before running Python, install the SDK: `pip install statsig-python-core` First, import and initialize Statsig: ```python from statsig_python_core import Statsig, StatsigUser key = autotune_name = statsig = Statsig(key) statsig.initialize().wait() ``` Then, create a user object and fetch your config: ```python user = StatsigUser('user_id', custom={'key1': 'value1', 'key2': 'value2'}) cfg = statsig.get_experiment(user, autotune_name) ``` Now you have your config and can apply it: ```python color = cfg.get_string("color", "default color") print(f"Going to use {color} for my color now") ``` After you run this code, you can: - Confirm that you fetched a value from one of your variants. - Navigate to the diagnostics page of your autotune and see a log of the user ID along with the corresponding variant. Your code is now serving personalized variants to your users. ## Important considerations Statsig requires a few hundred units to train a model and doesn't start training until those units' attribution window has elapsed. To test the functionality, you can simulate events to confirm things work as expected. Use logic like: ```plaintext fetch_autotune_value() if(user country == 'us'): log_click() ``` to conditionally send events and verify that the model picks up on the conditional behavior. ================================================================================ # Monitoring your Contextual MAB URL: https://docs.statsig.com/autotune/contextual/monitoring Updated: 2026-09-23 ================================================================================ # Monitoring your Contextual MAB There are three primary ways to monitor autotune performance. ## Linked experiments The most reliable way to evaluate whether a bandit is working is to measure whether it drives more of the targeted behavior compared to a baseline experience. You can set up and link an A/B test in Statsig to evaluate this, which also lets you monitor other user behaviors and guardrail metrics. Linking an A/B test is the most rigorous form of measurement, and Statsig highly encourages it. Standard practice is to wrap the Autotune in an experiment with a binary parameter. The wrapping experiment has two groups: a treatment group that receives the Autotune, and a control group that receives a default experience. Only users in the treatment group reach the Autotune, which then allocates them across its own variants. This is why the wrapping experiment and the Autotune can have a different number of variants. Common splits are 50/50 or a 90/10 holdback, where 90% of users receive the Autotune and 10% receive the default experience. For example, a 90/10 holdback around an Autotune with three variants splits traffic like this: ```text 90% → Autotune ├─ Variant A ├─ Variant B └─ Variant C 10% → Default experience ``` The two results answer different questions: - The wrapping experiment measures whether the Autotune outperforms the default experience. Its treatment result combines all Autotune variants. - The Autotune results show which variant performs best and how Statsig allocates traffic among variants. Linking the experiment to the Autotune only displays the experiment's results on the Autotune page. Linking doesn't route traffic. Your code must check the experiment and call the Autotune only for users in the treatment group: ```python experiment_value = statsig.get_experiment('wrapping_experiment').get('flag') default_param = '...' if experiment_value: param = statsig.get_experiment('autotune').get('param_name') else: param = default_param # use param in code ``` Start this experiment at the same time you launch your Autotune. ## Success rate Statsig tracks the cumulative and daily success rate of your variants over time. The success rate can be difficult to interpret. For example, variant A may have lower CTR, but the users being served variant A might have had even lower CTR on other variants. Use this view for tracking and understanding, and to identify outlier variants with notably high or low performance. ## Traffic allocation Traffic allocation shows where Statsig is sending users who see your Autotune. Use this view to identify whether a variant is dominating traffic or receiving no traffic. ## Model features Statsig tracks and surfaces coefficients and feature importance. This information helps you identify which features are worth further study, or which populations may have unmet needs in your product. - Importance is an estimate of the influence of a feature on the outcome: how much the feature contributes to the prediction. - A positive coefficient means that feature leads to an outcome being more likely (or for continuous outcome spaces is associated with a higher outcome). A negative coefficient means the outcome is less likely, or is associated with a lower continuous outcome. ================================================================================ # Contextual Bandit Methodology URL: https://docs.statsig.com/autotune/contextual/methodology Updated: 2025-09-18 ================================================================================ # Contextual Bandit Methodology ## How contextual bandits work Statsig runs contextual bandits with the same high-level approach across cloud and Warehouse Native deployments. Implementation details change frequently as Statsig experiments and optimizes its approaches, so this documentation stays intentionally high-level. ## Core approach The implementation follows the disjoint model methodology from [Li, Chu, Langford, Schapire](https://arxiv.org/pdf/1003.0146). Statsig trains one model per variant and computes estimated confidence intervals (CIs) for each. When you trigger contextual autotune, the latest model version estimates the user's outcome and adds the upper end of the 95% CI to that estimate. ![methodology workflow](https://docs.statsig.com/images/experiments/whn/linucb.png) Statsig models categorical outcomes as logistic regression with L2 penalty. Statsig models continuous outcomes as multivariate ridge regression. ## Training data and sampling To keep data relevant, Statsig upsamples contextual autotune data to prefer recent dates. Sampling uses these mechanisms: - Statsig selects a flat number of samples, preferring the most recent records. - Per day, over the last two weeks, Statsig chooses samples to prefer more recent records. - Statsig strictly prefers samples from the explore dataset, but may use non-explore data to satisfy sample requirements. Statsig then prioritizes records by a unit-ID hash to maintain stability in the training set between runs and avoid major jitter. - Statsig chooses a sample set per variant to avoid bias from a dominant model being overrepresented in the training data. If a model has very low volume, it has low representation in the training data. Lower representation causes higher CIs, which increases the upper bound and makes Statsig more likely to select that variant. This acts as a bounce-back mechanism for low-traffic variants. ## Model and feature updates Statsig updates models hourly. If a model definition changes (features or target outcome), Statsig resets all data, and the model retrains to match the new definition on the next hourly update. The pre-training data pipeline appears in the history view on the results page, showing the SQL used and the caching tables where Statsig stores data. You can use this data to validate or explore modeling approaches. ## Feature encoding Statsig treats features with numerical-only values as continuous random variables. Statsig string-encodes and one-hot-encodes all others into binary variables for regression, using the top 25 levels available in the data with more than 1% coverage. Statsig doesn't support arrays of categories or tags, or encodes only the most common tag sets. Provide tags as individual key-value pairs in the user custom object instead. ## Model monitoring Statsig doesn't offer diagnostics for model characteristics over time. Model coefficients are visible in the results tab. You can view a comparison of performance between naive random traffic and targeted traffic to determine whether model performance relative to blind allocation improves or degrades over time. ================================================================================ # Autotune (Bandits) URL: https://docs.statsig.com/autotune/overview ================================================================================ # Autotune (Bandits) Autotune and Autotune AI are Statsig's Multi-Armed Bandit solutions. They automatically find the best variant among a group of candidates while dynamically allocating traffic to optimize for a single target metric. Unlike a standard A/B test, Autotune shifts traffic toward the winning variant to maximize a target metric. A standard A/B test instead holds traffic allocation fixed to measure each variant's impact. Autotune, the Multi-Armed Bandit solution, allocates traffic toward high-performing variants and can eventually identify a winning variant. ## How Autotune works Autotune is Statsig's [Bayesian Multi-Armed Bandit](./multi-armed-bandit). It tests and measures different variations and their effect on a target outcome. The multi-armed bandit continuously adjusts traffic toward the best-performing variations until it can confidently pick the best variation, which then receives 100% of traffic. Bandits balance the explore/exploit problem: exploiting the current best-known solution versus exploring to gather more information about other solutions. The blog posts on [Multi-Armed Bandits](https://docs.statsig.com/autotune/multi-armed-bandit) and [Contextual Bandits](https://www.statsig.com/blog/statsig-autotune-contextual-bandits-personalization) go into depth on use cases and considerations. | | A/B/n Test | Multi-Armed Bandit (Autotune) | Contextual Bandit (Autotune AI) | Ranking Engine | | --- | --- | --- | --- | --- | | Typical # Variants | 2-3 | 4-8 | 4-8 | Arbitrary # | | Personalization Factor | None | None | Moderate | High | | Input Data Required | None | Very Little (100+ samples) | Little - generally 1000+ samples | Tens of thousands to millions of samples | | Model Efficacy | None | Basic | Moderate | High | | Identifies Best Variant | Yes | Yes | No | No | | Consistent User Assignment | Yes | No | No | No | ## Implementing Autotune Implementing an Autotune requires checking an experiment in Statsig. After initialization, or on server SDKs, the check has sub-millisecond latency. Autotune has a JSON config associated with each variant. The SDK returns this config. You can use the config to modify elements of your webpage, such as an image URL or button color. You can also use the config to identify which variant is active, so you know which code to run. ## When to use Autotune Autotune has two major differences from A/B testing (Statsig Experiments): 1. The traffic split isn't fixed over the duration of the test. This allows Autotune to divert more traffic to the winner and less to losers while making fewer mistakes. However, the user experience may not be consistent upon repeated visits. 2. Autotune can only optimize for a single metric. Autotune can't accurately measure a collection of metrics, and isn't a reliable way to understand secondary effects of your changes. It works best when the metric is well-understood and has a direct, immediate relationship to the change being tested. Because of these differences, Statsig recommends Autotune in the following scenarios: 1. The cost of exposing users to a losing treatment is high. For example, sending new users to an inferior landing page may result in lost revenue or churn. Testing two registration flows may cause some users to never sign up. Autotune avoids permanently losing users because it adapts quickly to feedback, unlike a static A/B test. 2. You want the decision to be automated. Because Autotune automatically selects the winner, it requires no human decision-making. Automated selection is well-suited for launching many simultaneous tests or running a long-term unmonitored test. 3. It's acceptable for users to see different experiences upon return visits. For example, when changing text or recommendation algorithms. 4. You have one simple metric to optimize for (for example, click-through rate) with an immediate effect on the test. 5. You want to test multiple variations. Autotune quickly eliminates poor performers while focusing traffic on the best variants. Avoid Autotune in the following scenarios: 1. When you have a complex ecosystem and want to understand secondary effects, tradeoffs between variants, and user behavior. 2. When you're optimizing for complex metrics or delayed effects. For these cases, use A/B testing with [Experiments](https://docs.statsig.com/experiments/overview). In general, it's also a best practice to run Autotune within an experiment. Use a small holdback group that doesn't receive the Autotune, so you can measure its impact. ================================================================================ # Get Started With Autotune URL: https://docs.statsig.com/autotune/setup Updated: 2025-09-18 ================================================================================ # Get Started With Autotune Autotune adjusts traffic among variants to optimize a success event and select one winning variant for all users. Use it when you want one global winner. Use contextual Autotune to personalize variant selection based on each user's context features. ## How to set up Autotune 1. To create a new Autotune experiment, navigate to the [Autotune section on the Statsig console](https://console.statsig.com/autotune). 2. Click **Create**, enter a name and a goal for the Autotune experiment, and set its ID type. Optionally assign a team, target applications, and tags. Click **Create** again. Statsig opens the Autotune's _Setup_ tab, where you configure the rest. 3. In _Groups and Parameters_, provide the variants to test. Each variant needs a name, and a corresponding JSON value. Statsig returns the variant listed as Control/Default when the Autotune experiment isn't running. ![Autotune experiment variant configuration interface](https://docs.statsig.com/images/autotune/setup/131385189-5f0c1d93-ba87-4159-8995-3c30991587a0.png) 4. Select the success event to optimize for. You can further specify an optional [event value](https://docs.statsig.com/guides/logging-events). ![Autotune success event selection interface](https://docs.statsig.com/images/autotune/setup/131385239-5a76d253-022b-457e-a370-f9ee7ce566a1.png) You can specify a few parameters: | Parameter | Description | | --- | --- | | Measurement Experiment | An existing experiment whose results Statsig shows alongside this Autotune, so you can measure the Autotune experience against a fixed baseline. Selecting one doesn't split traffic or change evaluation: your code creates the comparison by checking that experiment and calling the Autotune in its treatment branch. Go to [Linked experiments](https://docs.statsig.com/autotune/monitoring#linked-experiments). | | Exploration Window | The initial time period where Autotune equally splits traffic. This is useful for noisy or temporal metrics where hourly data swings can bias Autotune's initial measurements. | | Attribution Window | The maximum duration between the exposure and success event that counts as a success. Statsig recommends 1 hour for most applications; adjust if you expect the success event to lag the exposure event by several hours. | | Winner Threshold | The "probability of best" threshold a variant must reach for Autotune to declare it the winner, stop collecting data, and direct all traffic. A lower value results in faster decisions but increases the probability of selecting the wrong winner. | If your attribution window is longer than your exploration window, Autotune continues to split traffic equally until the attribution window ends. Until then, Autotune doesn't have complete outcome data. Click **Create** to finalize the setup. 6. As with Feature Gates and Experiments, Statsig provides a code snippet for the exposure check event to add to your code. Select **Start** when you're ready to launch your Autotune test. ![Autotune code snippet and launch interface](https://docs.statsig.com/images/autotune/setup/131384977-144dd868-787b-45ad-9ff1-fc9afbd4c769.png) ## Schedule the start time Instead of launching an Autotune right away, you can schedule it to start at a specific time. This is useful when you want a test to begin during a particular window, such as after a holiday, without having to start it manually. To schedule the start: 1. Select **Start** to open the start dialog. 2. Turn on **Schedule Autotune Start Time**. 3. Choose the date and time you want the Autotune to begin. You can schedule a start up to one year in advance, and times snap to the nearest 15-minute interval. The picker uses your local time zone. 4. Select **Schedule Start**. The Autotune shows a Scheduled status until the start time, when it launches automatically. To change or remove a scheduled start before it begins, use the **Edit Scheduled Start** or **Cancel Scheduled Start** option on the Autotune. ================================================================================ # Autotune URL: https://docs.statsig.com/autotune/monitoring Updated: 2026-09-23 ================================================================================ # Autotune ## How to monitor your Autotune test ### Computations and traffic allocation The results tab within Autotune provides a view of your ongoing and completed Autotune tests. Statsig computes Autotune hourly, with metrics and traffic allocation updated throughout the day. Statsig ingests results from exposures after the attribution window is complete. For example, Statsig doesn't count an exposure at 1pm with a 6-hour attribution window until 7pm. ### Result ![Autotune test results summary](https://docs.statsig.com/images/autotune/monitoring/150008289-2119f756-ff71-4634-af85-fca840cf1e4c.png) This section shows a summary of your Autotune test. The top bars show a 95% Bayesian Credible interval for the estimated conversion rate (exposure to success event). There's a 95% chance that the real value is within this interval. The table shows the number of exposures, success events, and overall success rate for each variation across the duration of the test. It also includes a plain-language description of the current test state. ### Details ![Autotune test detailed analytics charts](https://docs.statsig.com/images/autotune/monitoring/150009034-74a9f2b9-42ee-4d24-9c95-5fe6dff35334.png) There are several charts provided: 1. Probability of Best - shows the progress of the Autotune test, and which variant is currently winning. 2. Cumulative success rate - shows the overall success rate (exposure -> success) to date. 3. Daily success rate - shows the success rate for each variation per day. 4. Traffic allocation - shows the daily number of exposures allocated to each variation on a given day. ### Linked experiments The most reliable way to evaluate whether a bandit is working is to measure whether it drives more of the targeted behavior compared to a baseline experience. You can set up and link an A/B test in Statsig to evaluate this, which also lets you monitor other user behaviors and guardrail metrics. Linking an A/B test is the most rigorous form of measurement, and Statsig highly encourages it. Standard practice is to wrap the Autotune in an experiment with a binary parameter. The wrapping experiment has two groups: a treatment group that receives the Autotune, and a control group that receives a default experience. Only users in the treatment group reach the Autotune, which then allocates them across its own variants. This is why the wrapping experiment and the Autotune can have a different number of variants. Common splits are 50/50 or a 90/10 holdback, where 90% of users receive the Autotune and 10% receive the default experience. For example, a 90/10 holdback around an Autotune with three variants splits traffic like this: ```text 90% → Autotune ├─ Variant A ├─ Variant B └─ Variant C 10% → Default experience ``` The two results answer different questions: - The wrapping experiment measures whether the Autotune outperforms the default experience. Its treatment result combines all Autotune variants. - The Autotune results show which variant performs best and how Statsig allocates traffic among variants. Linking the experiment to the Autotune only displays the experiment's results on the Autotune page. Linking doesn't route traffic. Your code must check the experiment and call the Autotune only for users in the treatment group: ```python experiment_value = statsig.get_experiment('wrapping_experiment').get('flag') default_param = '...' if experiment_value: param = statsig.get_experiment('autotune').get('param_name') else: param = default_param # use param in code ``` Start this experiment at the same time you launch your Autotune. ================================================================================ # Methodology URL: https://docs.statsig.com/autotune/multi-armed-bandit Updated: 2025-09-18 ================================================================================ # Methodology ## Model The base Autotune implementation uses a Thompson Sampling (Bayesian) algorithm to estimate each variant's probability of being the best variant and allocate a proportional amount of traffic. For example, if a given variant has a 60% probability of being the best, Autotune allocates 60% of the traffic to it. The multi-armed bandit algorithm adds more users to a treatment as soon as it determines that treatment is clearly better at maximizing the reward (the target metric). Throughout the process, higher-performing treatments receive more traffic and underperforming treatments receive less. When the winning treatment beats the second-best treatment by a specified margin, the process ends. Some helpful references: - [Statsig Blog](https://www.statsig.com/blog/introducing-autotune) - [Goyal and Agrawal (Microsoft Research)](https://proceedings.mlr.press/v23/agrawal12/agrawal12.pdf) Regret Analysis - [Doordash Engineering](https://doordash.engineering/2022/03/15/using-a-multi-armed-bandit-with-thompson-sampling-to-identify-responsive-dashers/) Summary Blog ## Advantages The main advantage of the base Multi-Armed Bandit over a contextual bandit is its ability to converge and identify the best variant. When a single solution works well for all users, the Multi-Armed Bandit efficiently allocates traffic and determines the correct long-term solution while minimizing regret. Regret is the cost of exposing many users to a worse variant, as happens in an A/B test. ## Disadvantages The main disadvantage of a Multi-Armed Bandit compared to a contextual bandit is its inability to personalize. When user attributes interact with variants, Autotune can identify a global maximum that is worse than serving each user their individual best variant. For example, even if the "US Flag" variant had the highest overall CTR, it would be a poor choice for Canadian users. In such cases, both groups converge to a sub-optimal variant. | | A/B/n Test | Multi-Armed Bandit (Autotune) | Contextual Bandit (Autotune AI) | Ranking Engine | | --- | --- | --- | --- | --- | | Typical # Variants | 2-3 | 4-8 | 4-8 | Arbitrary # | | Personalization Factor | None | None | Moderate | High | | Input Data Required | None | Very Little (100+ samples) | Little - generally 1000+ samples | Tens of thousands to millions of samples | | Model Efficacy | None | Basic | Moderate | High | | Identifies Best Variant | Yes | Yes | No | No | | Consistent User Assignment | Yes | No | No | No | ================================================================================ # Bandit FAQs URL: https://docs.statsig.com/autotune/bandit-faq Updated: 2025-09-18 ================================================================================ # Bandit FAQs ### When should I see data show up in a bandit Diagnostic data appears in near-real time in the logstream on your bandit. Data in the models/results section depends on your settings. Statsig doesn't count units as enrolled until their attribution window has elapsed. For example, if you have a 24-hour attribution window, it takes 24 hours to see your first units and model updates. Statsig trains models hourly with a few minutes of data delay, so there may be 1 to 2 additional hours of delay beyond that period. This operation doesn't have a strict SLA on Statsig's side. Delays may occur due to data quality checks or other investigations to prevent bad model training data from affecting your production environment. ### What do I put into the Variant JSON The variants return this JSON as a config, similar to dynamic configs or experiments. You can put an identifier for the variant, or specify a set of attributes that your code accesses to avoid writing conditional statements to fetch the corresponding attributes. ### Why use a linked experiment Bandits optimize for a single target metric or event, which alone doesn't provide a detailed analysis of how the bandit affects your users. To get deeper insights into a bandit's impact on end users, wrap the bandit in an experiment. In that experiment, the control group receives a default experience and the variant group receives the bandit's experience. Statsig highly recommends this step. ### Where is my Autotune data available Statsig downloads Autotune data hourly into the `statsig_first_exposures` metric source. Select the history modal on the autotune to view the SQL and tables generated for an individual autotune. ### Why was a "losing" variant chosen Autotune assumes that a metric is consistent over time. A metric with strong seasonality (for example, a metric that drops on weekends) isn't a good candidate for an Autotune experiment. With seasonality, the following situation is possible: - A variant that consistently performs worse than others receives less and less traffic until it has essentially zero traffic. - Other variants, still receiving traffic, see their metric drop when seasonal effects occur. - The variant with zero traffic doesn't see that metric drop (because no traffic is allocated to it), which causes Statsig to select it as the winning variant. This seasonality effect can sometimes cause Statsig to choose a "losing" variant as the winner. ### How do I complete or conclude an Autotune test Autotune concludes automatically when a variant reaches the winner threshold. At that point, Autotune declares the winner, stops collecting data, and directs 100% of traffic to it. There's no manual completion step. Until the winner threshold is reached, the only manual action is **Reset Autotune**, which discards all learning and restarts the test from scratch. To end early with the current leader, ship that variant's value in code and remove the Autotune check. ================================================================================ # Advanced Bandit Usage URL: https://docs.statsig.com/autotune/using-bandits Updated: 2025-09-18 ================================================================================ # Advanced Bandit Usage You manage both contextual and non-contextual bandits on Statsig's console, or through Statsig's [console API](https://docs.statsig.com/console-api/introduction) for programmatic creation. Both bandit types use a common, streamlined API, so you can explore either use case without significant changes from using experiments. Statsig's bandits provide the power of complex bandits through a simple interface. A key observation from development is that many such systems fail because of implementation issues. Using a bandit requires no additional steps beyond a regular experiment check. For contextual multi-armed bandits, attach any context to your user object (usually at initialization) before making the experiment check. You can confirm this in the diagnostics tab of your bandit in the console. ### Checking a bandit Check bandits using your standard experiment call. For example, in React, configure a bandit's variant JSON like this: ```plaintext { "text": "", ... } ``` Then access it in code using the same pattern as [experiments](https://docs.statsig.com/guides/abn-tests): ```plaintext const banditText = useExperiment('contextual_bandit').config.get('text'); ``` The bandit check is separate from a bandit's linked experiment call to reduce excessive logging. If you have a linked wrapping experiment, wrap the call after checking the experiment. Statsig automatically detects and differentiates categorical and numerical features based on cardinality. ### Getting a list Getting a ranked list of variants is a common requirement. Client-side filtering or other constraints may prevent showing a particular variant. Statsig supports getting a list of scored outcomes, but requires manual exposure logging so that Statsig knows which variant you displayed to the user. ### Outcomes In Statsig Cloud, log an outcome event (as a flag, or with a value) to Statsig, and Statsig handles connecting exposures to outcome events within your configured time periods. In Statsig Warehouse Native, provide your outcome dataset as a metric source. > **Note:** > > Data latency matters: if your output dataset has more than 24 hours of lag, bandit exploration can slow down significantly. ================================================================================ # Layers URL: https://docs.statsig.com/experiments/layers-overview ================================================================================ # Layers A layer (also called a universe) is a pool of users that Statsig divides among several experiments so that no user is in more than one experiment in that layer. A layer also owns shared parameters: your code reads one layer parameter, and each experiment in the layer sets its value. Use a layer when experiments touch the same surface and could interfere with each other, or when you iterate on the same parameter repeatedly. A standalone experiment doesn't need a layer you manage; by default, Statsig runs it in its own layer. ![Layer concept diagram showing mutually exclusive experiments](https://docs.statsig.com/images/experiments/layers-concept.png) ## Create and manage layers Create a layer in either of two places: the _Layer_ field of the experiment creation dialog, or the _Experiment Layers_ page at _Experimentation > Layers_, where **Create** opens a dialog for the layer's name, description, unit type, team, tags, and target applications. ![Experiment creation modal with layer selection](https://docs.statsig.com/images/experiments/layers-create.png) Choose the layer before the experiment starts. Statsig locks an experiment's layer when the experiment starts, so you can't add a running experiment to a layer or move it to a different layer. After you create a layer, manage it from _Experimentation > Layers_ in the Statsig console. The list shows each layer's experiment count and its **Remaining Allocation**, the share of the layer an experiment can still claim. To override a user into an experiment in a layer, add the override on the layer, not on the experiment. Refer to [Overrides](https://docs.statsig.com/experiments/setup/overrides). ![Layers overview tab listing active layers](https://docs.statsig.com/images/experiments/layers-tab.png) The layer details page shows the layer's shared parameters. ![Layer details page showing shared parameters](https://docs.statsig.com/images/experiments/layer-details.png) ## Share parameters across experiments Parameters exist at the layer level, and experiments within the layer share them. Your code works only with layer parameters, so multiple experiments that change the same parameter can run and iterate without code changes. Suppose your product has a signup dialog with text that your team tests frequently. Some tests run in parallel, and others iterate on previous experiments. If your code calls each experiment directly, it grows like this over time: ```jsx let signUpText = DEFAULT_SIGNUP_TEXT; const signUpTestV1 = statsig.getExperiment("sign_up_dialog_text_test_v1"); const signUpTestV2 = statsig.getExperiment("sign_up_dialog_text_test_v2"); const specialSignUpTest = statsig.getExperiment("sign_up_test_special_offer"); const holidaySignUpTest = statsig.getExperiment("sign_up_test_holiday"); if (signUpTestV1.get("is_in_test", false)) { // original test, added in app version v1.2 signUpText = signUpTestV1.get("dialog_content", DEFAULT_SIGNUP_TEXT); } else if (signUpTestV2.get("is_in_test", false)) { // v2 of the original test, added in app version v1.6 because we wanted to test a new copy but don't want to stop v1 signUpText = signUpTestV2.get("dialog_content", DEFAULT_SIGNUP_TEXT); } else if (specialSignUpTest.get("is_in_test", false)) { // test showing a special offer in the text, added in v2.0 signUpText = specialSignUpTest.get("dialog_content", DEFAULT_SIGNUP_TEXT); } else if (holidaySignUpTest.get("is_in_test", false)) { // test showing some holiday greetings in the dialog, added in v2.1 signUpText = holidaySignUpTest.get("dialog_content", DEFAULT_SIGNUP_TEXT); } // Then we display the text in the dialog ``` Every time you add a test, you change the code, and the change ships only with a new release. With a layer, the code reads one parameter: ```jsx let signUpText = statsig .getLayer("sign_up_tests") .get("sign_up_dialog_text", DEFAULT_SIGNUP_TEXT); // Then we display the text in the dialog ``` To add a test, add a new experiment to the same layer and choose `sign_up_dialog_text` as a parameter. The SDK serves the value from whichever experiment Statsig allocates the user to, with no code change or app release. ## Use getLayer for layered experiments Layered experiments remain accessible through `getExperiment`, but that API evaluates only the current experiment. Use `getLayer` so the SDK honors layer-level decisions, mutual exclusion, and shared parameters. ## How Statsig assigns users in a layer Statsig assigns a user to an experiment in a layer in two independent steps: 1. **Layer allocation**: Statsig hashes the user's unit ID with the layer's salt and places the user in one of 1,000 layer buckets. Each experiment in the layer owns a specific set of buckets, and no two experiments share a bucket. The experiment that owns the user's bucket receives the user. If no experiment owns the bucket, the user receives the layer's default values. 2. **Group assignment**: Statsig hashes the unit ID again with the experiment's own salt to choose the user's group, such as control or test. The two steps use different salts, so a user's layer bucket doesn't influence the user's group assignment. Statsig always places the same unit ID in the same layer bucket, so assignment stays consistent across sessions and SDKs. Statsig checks the experiment's targeting gate after layer allocation. A user who fails the targeting gate receives the layer's default values. Statsig doesn't move the user to another experiment in the layer. Overrides and holdouts apply before layer allocation. For the full evaluation order, refer to [How evaluation works](https://docs.statsig.com/sdks/how-evaluation-works#evaluation-order). ## Change an experiment's allocation in a layer An experiment's allocation in a layer is the share of layer buckets it owns. Changing one experiment's allocation doesn't reassign users in the other experiments in the layer. - **Increase allocation**: Statsig gives the experiment more buckets from the layer's unallocated buckets. Users already in the experiment keep their buckets and groups. The increase can't exceed the number of unallocated buckets in the layer. - **Decrease allocation**: Statsig removes some of the experiment's buckets. Users in the removed buckets leave the experiment and receive the layer's default values. Users in the remaining buckets keep their assignment. Decreasing allocation biases your results, so reset the experiment instead where possible. Refer to [Allocation](https://docs.statsig.com/experiments/setup/allocation-and-targeting#allocation). - **Decrease, then increase**: The buckets the experiment regains can contain different users from the users who left. Only users in buckets the experiment kept throughout stay in the experiment continuously. - **Shift allocation between experiments**: When you decrease one experiment's allocation and increase another's, the second experiment can receive the freed buckets. Users who stay in either experiment keep their assignment. Experiment allocation works differently from a feature gate's percentage rollout. A gate uses a fixed threshold, so changing a gate's rollout from 50% to 0% and back to 50% re-exposes the same users. An experiment owns an explicit set of buckets, so the same change to an experiment's allocation doesn't guarantee the same users. ## Stop or ship an experiment in a layer When an experiment in a layer stops, its buckets become unallocated. Statsig doesn't rearrange the other experiments' buckets. A new experiment receives buckets from all unallocated buckets in the layer. Those buckets can include both previously unallocated buckets and buckets that the stopped experiment released. When you [make a decision](https://docs.statsig.com/experiments/ending/make-decision) on an experiment in a layer, the result depends on whether the experiment has a targeting gate: - **Without a targeting gate**: The shipped group's parameter values become the layer's default values, and Statsig releases the experiment's buckets. Users who aren't in another experiment in the layer receive the shipped values. - **With a targeting gate**: Statsig adds an override to the layer. Users who pass the gate receive the shipped values. Users who fail the gate receive the layer's default values. Mutual exclusion applies only to experiments that run at the same time. A layer doesn't track which buckets a stopped experiment used, so users in a new experiment might have been in an earlier experiment in the layer. ## Plan layer capacity All experiments in a layer share one 100% allocation, even when their audiences can't overlap. For example, if one experiment targets users in the US and another targets users in Japan, both still draw from the same layer buckets. Statsig places some users in Japan in the US experiment's buckets. Those users fail the US experiment's targeting gate, and Statsig doesn't move them to the Japan experiment. As a result, those users don't enter either experiment. For experiments with separate audiences, choose one of these options: - To keep experiments mutually exclusive within each audience, create one layer per audience. - If overlap between experiments is acceptable, run them as standalone experiments. Each standalone experiment runs in its own layer. ## How exposures work with layers Calling `getLayer("layer_name")` by itself doesn't log an exposure. Statsig logs a `statsig::layer_exposure` event when you read a specific parameter with `getLayer("layer_name").get("parameter_name")`. - If Statsig assigns the user to an experiment within the layer, the `statsig::layer_exposure` event is billable. - If Statsig doesn't assign the user to an experiment within the layer, the `statsig::layer_exposure` event isn't billable. > **Note:** > > Repeated reads of the same layer parameter for the same user within the deduplication window count as a single billable exposure. Reads of different layer parameters use separate dedupe keys and may count separately. > > Deduplication window lengths: > > - **Client SDKs (JS/web, iOS, Android)**: 10 minutes per user, layer, and parameter combination. > - **Server SDKs**: About 1 minute. The dedupe set resets every 60 seconds. ================================================================================ # Holdouts URL: https://docs.statsig.com/experiments/holdouts-introduction Updated: 2025-09-18 ================================================================================ # Holdouts A holdout withholds a small percentage of users, typically 1% to 2%, from a set of new features so you can measure the features' combined effect over months. An experiment measures one feature; use a holdout when you want to know what all your launches together did to a metric. Statsig compares the held-out group (control) against an equal-sized sample of users who received the features through the normal rollout or experiment behavior (test). ## How to use holdouts A holdout applies only to experiments and feature gates that use the same randomization unit as the holdout. If your team runs experiments on both `userID` and `stableID`, create two holdouts to evaluate the cumulative impact of each type. Creating a holdout takes two stages: a dialog that creates the holdout, then its _Setup_ tab, where you configure how it behaves. To create a holdout: 1. In the Statsig console, go to [Holdouts](https://console.statsig.com/holdouts) and click **Create**. 2. Enter the name and unit type, and optionally a description, team, and tags. Click **Create**. To configure it, open the holdout's _Setup_ tab and use the _Settings_ section: 1. Choose a global or selected holdout with the **Holdout is global** toggle: - A global holdout captures the aggregate impact of all features developed after the holdout began. Statsig automatically enforces it on new gates, experiments, and layers with the same unit type, and you can opt individual features out. - A selected holdout captures the aggregate impact of a specific set of features. List them under **Include Gates** and **Include Layers**. 2. Choose the **Population**. By default, a holdout applies to a percentage of all users (Population = Everyone). To target a subset of users, apply a targeting gate (Population = Targeting Gate). For example, to create an iOS-only holdout, apply a targeting gate that passes only iOS users. 3. Set **Holdout %** between 1% and 50%. Statsig recommends a small percentage to limit the number of users who don't see new features. The _Setup_ tab also holds **Monitoring Metrics**, the metrics Statsig tracks for impact as you roll out changes. ![Holdout creation interface](https://docs.statsig.com/images/experiments/holdouts-introduction/81b634c7-f05e-493e-88c1-4c58d770a1d4.png) ![Holdout configuration settings](https://docs.statsig.com/images/experiments/holdouts-introduction/82c06037-7a12-4335-9ebf-81156a54d798.png) ## How to read holdouts Holdouts use the same [equal variant methodology](https://docs.statsig.com/feature-flags/view-exposures#gate-exposures) as feature gate rollouts: Statsig computes metric lifts using equal-sized groups. For the reasoning behind this methodology, go to ["A/B Testing Intuition Busters: Common Misunderstandings in Online Controlled Experiments"](https://drive.google.com/file/d/1oK2HpKKXeQLX6gQeQpfEaCGZtNr2kR76/view) by Ron Kohavi, Alex Deng, and Lukas Vermeer. The Cumulative Exposures panel for a holdout shows the holdout's total exposures broken down into three groups: - **In holdout (Control)**: Units that Statsig included in the holdout and used for analysis. - **Not in holdout (Test); used for analysis**: Units that Statsig didn't include in the holdout but selected for comparison against the holdout group. - **Not in holdout (Test); not used for analysis**: Units that Statsig didn't include in the holdout and didn't use in the lift calculation. Statsig selects the two "Not in holdout" groups by random sampling and sizes the analysis group to match the holdout group. Holdout metric lifts represent the cumulative impact of launched and active experiments on the holdout group. The "Not in holdout (Test); used for analysis" group isn't necessarily made up of users who saw every held-out feature; those users follow the normal non-holdout behavior for each included gate or experiment. In the following example, the 1% holdout compares users in the holdout against 1% of users not in the holdout, not against the full remaining 99%. The launched features have an overall negative effect on the "Add to Cart" metric. ![Holdout pulse results showing metric lift comparison between holdout and exposed users](https://docs.statsig.com/images/experiments/holdouts-introduction/b6c3724d-784d-45e3-ad6e-230bd9d82214.png) ### Balance Holdout Analysis The **Balance Holdout Analysis** checkbox controls how Statsig selects the "Not in holdout (Test); used for analysis" group. On Cloud, balanced analysis is on by default: Statsig sizes the analysis group to match the holdout group. On Warehouse Native, balanced analysis is opt-in; with it off, Statsig compares the holdout group against the full non-holdout population instead of a balanced sample. ## Best practices - **Size**: Statsig recommends a low single-digit holdout percentage, such as 1% to 2%, to limit the number of users who don't see new features. - **Duration**: Statsig recommends running a holdout for three to six months, then releasing it. A longer holdout increases software complexity, because you must maintain a functioning product with no new features for a longer period. - **Back testing**: Occasionally you may want to turn off a set of already-released features to measure their effectiveness. Statsig doesn't recommend this approach because it turns off features that users already use. However, when a back measurement is critical, you can use a holdout to turn off a set of features and automatically compute their impact. ## Unit ID types By default, holdouts use `userID`. To use a different ID type, select it from the drop-down menu during holdout creation. ![Holdout unit ID type selection](https://docs.statsig.com/images/experiments/holdouts-introduction/cb2125f0-7fe2-4fbe-b6a3-3405dc300715.png) ## Change a holdout's salt A holdout's salt determines how Statsig hashes units into the holdout group. Set the salt to a value you choose to align salts across holdouts or projects, so the same units land on the same side of each holdout. Aligned salts help when you migrate a holdout or need consistent assignment across projects. Saving a salt change requires the Launch to Production permission. Changing a salt affects future assignment only: it isn't retroactive, doesn't reload historical data, and doesn't change existing assignments. To view a holdout's salt, open the holdout's **More Actions** menu and click **View Salts**. Any viewer can open the salts dialog. To change the salt, enter the value you want in the dialog and save the change. Editable salts apply to holdouts only. ## How holdouts affect SDK results ### Feature gates For users in the holdout, gates always return `False`. ### Experiments - If the experiment isn't in a layer, calls to get experiment parameters for users in the holdout return the default value passed in code. - If the experiment is in a layer, calls to get experiment parameters for users in the holdout return the values defined in the layer defaults in the Statsig console. > **Note:** > > When you ship an experiment in a layer, Statsig normally updates the layer defaults. Users in the holdout don't see those defaults. Instead, the layer keeps a separate set of default parameters only for held-out users: ![Layer holdout parameters](https://docs.statsig.com/images/experiments/layer_holout_params.png) ## Ending a holdout To end a holdout and let users in the holdout group see all held-out features, disable the holdout. Disabling the holdout stops tracking the effects of those features, but Statsig retains the results for future reference. Alternatively, delete the holdout if you created it by mistake or no longer need to keep the results. ================================================================================ # Introduction URL: https://docs.statsig.com/experiments/statistical-methods/introduction Updated: 2025-09-18 ================================================================================ # Introduction The Statsig Stats Engine is the set of statistical calculations behind the experiment results you read on the [Results tab](https://docs.statsig.com/experiments/interpreting-results/read-results). It turns exposure and metric data into a metric delta, confidence interval, and p-value for each metric, applies variance reduction, and supports frequentist, SPRT, and Bayesian analysis methods. Use these pages when you need the formula or assumption behind a number in your results. ## What the Stats Engine calculates and how - [Metric deltas](https://docs.statsig.com/experiments/statistical-methods/metric-deltas): The difference in mean metric value between the test and control groups, in absolute and relative terms. - [Standard error and mean variance](https://docs.statsig.com/experiments/statistical-methods/variance): How much each group's mean would vary across repeated samples. This is the input to every confidence interval and p-value. - [Confidence intervals](https://docs.statsig.com/experiments/statistical-methods/confidence-intervals): The gray, red, and green bars on the Results tab, which represent the uncertainty in each metric delta. - [p-values](https://docs.statsig.com/experiments/statistical-methods/p-value): The probability of observing a metric delta at least as extreme as the one measured, if the treatment has no effect on that metric. - [Topline and projected impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact): The daily effect of the experiment on a company metric, and the estimated effect if you launch the test group to all users. - [Variance reduction](https://docs.statsig.com/experiments/statistical-methods/variance-reduction): The techniques Statsig applies so the same effect reaches significance with fewer users. - [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped): Uses each user's pre-exposure data to reduce variance. Statsig applies it automatically. - [Pre-experiment bias](https://docs.statsig.com/experiments/statistical-methods/pre-experiment-bias): How Statsig detects groups that already differed before exposure and flags the affected metrics. - [Frequentist sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing): Adjusts p-values and confidence intervals so you can read results early without inflating false positives. - [Sequential probability ratio tests](https://docs.statsig.com/experiments/advanced-setup/sprt): Compares the likelihood of your data under the alternative and null hypotheses, and can accept either one. - [Bayesian experiments](https://docs.statsig.com/experiments/advanced-setup/bayesian): Reports chance to beat control and expected loss, with optional informative priors. ================================================================================ # Frequentist Sequential Testing URL: https://docs.statsig.com/experiments/advanced-setup/sequential-testing ================================================================================ # Frequentist Sequential Testing Sequential testing adjusts p-values and confidence intervals so you can read experiment results before the target sample size without inflating the false positive rate. Statsig implements it as a mixture sequential probability ratio test (mSPRT): each metric's confidence interval widens by an amount that shrinks as data accumulates. Use it on frequentist experiments when you need to catch regressions early or ship early on a statistically significant result. Statsig offers three analysis methods, which you choose with the _Analytics Type_ setting under Advanced Settings on the experiment Setup tab. Use frequentist analysis with sequential testing for standard p-values and confidence intervals that stay valid when you read results early. Use [SPRT](https://docs.statsig.com/experiments/advanced-setup/sprt) when you want unlimited peeking and the option to accept the null hypothesis as well as reject it. Use [Bayesian mode](https://docs.statsig.com/experiments/advanced-setup/bayesian) for chance-to-beat and expected-loss readouts, with optional priors from past experiments. ## Why peeking inflates false positives Traditional A/B tests (t-tests and z-tests) are fixed-horizon tests. When you design the experiment, you set the number of units to observe, and you read the metrics once, after you reach that target sample size. Sequential testing lets you read results and make valid decisions before that point. Continuous monitoring of an experiment, or peeking, inflates the false positive rate above the significance level you chose. Every time you consider ending an experiment early, you decide whether to reject the null hypothesis, and that decision can be wrong. Metric values and p-values fluctuate because of noise from random unit assignment and unpredictable user behavior, so results can move into and out of statistical significance even when there is no real effect. Noise levels vary by test and decrease over time as more users join and you observe them longer. When you decide based on an early snapshot, you're more likely to select a statistically significant result that wouldn't appear if you analyzed the data once at the planned end of the experiment. In frequentist procedures, early decisions can only increase the false positive rate, even when you intend to make a less biased decision. ## How sequential testing works for an A/B test Statsig automatically adjusts p-values and confidence intervals for each preliminary analysis window to compensate for the increased false positive rate that peeking introduces. The Results tab shows the adjustment: ![Sequential testing results visualization](https://docs.statsig.com/images/experiments/sequential_testing_example.png) Statsig expands the confidence interval for each metric and marks the expansion with wings on the ends of the bar. The wings show that sequential testing is on and how much the interval expanded. ![Statsig results table highlighting sequential testing adjusted confidence interval](https://docs.statsig.com/images/experiments/advanced-setup/sequential-testing/c233dc78-fc61-46cb-8068-e657853a3a1d.png) In this example, the sequential testing adjustment determines whether Statsig declares the result significant. Sequential testing supports early decisions when observations are strong enough to outweigh random fluctuations, while limiting the risk of false positives. Statsig discourages peeking in general, but regular monitoring with sequential testing is valuable in two cases: - **Unexpected regressions**: When an experiment has a bug or an unintended consequence that severely affects key metrics, sequential testing identifies the regression early and distinguishes significant effects from random fluctuations. - **Opportunity cost**: Delaying a decision can be costly, for example when you need to launch a feature ahead of a major event or fix a bug. Sequential testing can support an early decision if key metrics show improvement. Use caution: an early significant result on some metrics doesn't guarantee enough power to detect regressions in other metrics. Limit this approach to cases where only a small number of metrics matter to the decision. > **Tip:** > > You can use sequential testing anywhere you run an experimental analysis, including the experiment Results page and any [custom queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries). ## Enable sequential testing On the **Setup** tab of your experiment, expand _Advanced Settings_, set _Analytics Type_ to **Frequentist**, then select **Apply Sequential Testing** under _Frequentist Mode Settings_. You can toggle this setting at any time during the experiment; you don't need to turn it on before the experiment starts. ![Sequential testing configuration interface](https://docs.statsig.com/images/experiments/enable_freq_sequential_testing.png) ## Interpret sequential testing results On the _Results_ tab, select the pencil icon next to the Scorecard summary row to open [_Comparison & Stats_](https://docs.statsig.com/experiments/interpreting-results/read-results#significance-level-settings), then toggle **Sequential Testing** on or off. ![Pulse metrics sequential testing toggle](https://docs.statsig.com/images/experiments/advanced-setup/sequential-testing/191135447-5e094892-49e5-485e-8186-18732888662c.png) When you turn on sequential testing, Statsig adjusts the results it calculates before the target completion date of the experiment. ![Sequential testing confidence interval visualization](https://docs.statsig.com/images/experiments/advanced-setup/sequential-testing/191135645-0042dced-3e8f-479f-8f63-c814dfbd4923.png) The dashed line is the expanded confidence interval that results from the adjustment. The solid bar is the standard confidence interval without adjustment. If the adjusted confidence interval overlaps zero, the metric delta isn't significant yet, and the experiment should continue as planned. Early decisions often produce underpowered lift estimates with high uncertainty. If you need the correct ship decision, act on significant sequential testing results. If you need an accurate measurement of the effect size, wait for the full power that your pre-experiment power calculation estimates. Statsig doesn't calculate statistical power on post-hoc results; refer to the section "Post-hoc Power Calculations are Noisy and Misleading" in [Kohavi, Deng, and Vermeer, A/B Testing Intuition Busters](https://bit.ly/ABTestingIntuitionBusters). ## How Statsig implements sequential testing ### Two-sided tests #### Confidence intervals Statsig uses mSPRT based on the approach that [Zhao et al.](https://arxiv.org/pdf/1905.10493.pdf) propose. The two-sided sequential testing confidence interval with significance level $\alpha$ is: $$ CI^*(\Delta \overline{X}) = \Delta \overline{X} \pm Z^*_{\alpha/2} \cdot \sqrt{V} $$ where: - $Z^*_{\alpha/2}$ is the z-critical value, modified for sequential testing: $$ Z^*_{\alpha/2} = \sqrt{\frac{(V+\tau)}{\tau}\left(-2\ln(\alpha/2)-\ln(\frac{V}{V+\tau})\right)} $$ - $V$ is the standard [variance](https://docs.statsig.com/experiments/statistical-methods/variance) of the delta of means. You can obtain it from the sample variance of the test and control group means: $$ V = var(\Delta \overline X) = var(\overline X_t) + var(\overline X_c) = \frac{var(X_t)}{N_t} + \frac{var(X_c)}{N_c} $$ - $\tau$ is the mixing parameter: $$ \tau =(Z_{\alpha/2})^2\cdot\frac{var(X_t)+var(X_c)}{N_t+N_c} $$ - $Z_{\alpha/2}$ is the z-critical value used in the non-sequential test, for the significance level you want (1.96 for the standard $\alpha = 0.05$). Statsig has validated that this parameter satisfies the expected false positive rate and provides enough power to detect large effects early. For details, refer to [Statsig's sequential testing analysis](https://www.statsig.com/blog/sequential-testing-on-statsig). #### p-values To produce sequential testing p-values that are consistent with the expanded confidence intervals, Statsig modifies the standard [p-value methods](https://docs.statsig.com/experiments/statistical-methods/p-value). The goal is to evaluate the mSPRT test so that the Type I error remains approximately equal to $\alpha$, and so that the sequential testing p-value is consistent with the expanded confidence interval: a confidence interval that includes 0.0% has a p-value ≥ $\alpha$, and one that excludes 0.0% has a p-value < $\alpha$. The observed z-statistic (z-score) $Z$ remains unchanged. Instead of evaluating $Z$ on a standard normal distribution $N(0, 1)$, Statsig evaluates it against a normal distribution $N(0, \sigma^2)$ with mean zero and standard deviation $\sigma$. For a two-sided test, to limit the probability that an observed $Z$ exceeds $Z^*_{\alpha/2}$ under the null hypothesis to $\alpha$, solve for $\sigma$: $$ \sigma=\frac{Z_{\alpha/2}^*}{\sqrt{2} \cdot erf^{-1}(1-\alpha)} $$ where $erf^{-1}$ is the [inverse error function](https://en.wikipedia.org/wiki/Error_function#Inverse_functions). The two-sided sequential testing p-value is then: $$ \text{p-value}^* = 2 \cdot \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{-|Z|} \frac{e^{- \frac{t^2}{{2\sigma^2}}}}{\sigma}dt $$ where $Z$ is the observed z-statistic. ### One-sided tests Statsig modifies each step for one-sided sequential testing. $$ CI^*(\Delta \overline{X}) = \begin{cases} \left[\Delta \overline{X} - Z^*_{\alpha} \cdot \sqrt{V}, \quad +\infty \right) & \text{if right-sided test} \\ \\ \left(- \infty, \quad \Delta \overline{X} + Z^*_{\alpha} \cdot \sqrt{V} :\right] & \text{if left-sided test} \\ \end{cases} $$ $$ \text{p-value}^* = \begin{cases} 1 - \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z} \frac{e^{- \frac{t^2}{{2\sigma^2}}}}{\sigma}dt \quad \text{if right-sided test} \\ \\ \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z} \frac{e^{- \frac{t^2}{{2\sigma^2}}}}{\sigma}dt \quad \text{if left-sided test} \\ \end{cases} $$ where: - $Z^*_{\alpha}$ is the one-sided z-critical value, modified for sequential testing: $$ Z^*_{\alpha} = \sqrt{\frac{(V+\tau)}{\tau}\left(-2\ln(\alpha)-\ln(\frac{V}{V+\tau})\right)} $$ - $V$ is the variance of the delta of means, $var(\Delta \overline X)$. - $\tau$ is the mixing parameter: $$ \tau =(Z_{\alpha})^2\cdot\frac{var(X_t)+var(X_c)}{N_t+N_c} $$ - $Z_{\alpha}$ is the one-sided z-critical value used in the non-sequential test, for the significance level you want (1.645 for the standard $\alpha = 0.05$). - Statsig solves for $\sigma$ with: $$ \sigma = \begin{cases} \frac{Z_{\alpha}^*}{\sqrt{2} \cdot erf^{-1}(1 - 2 \alpha)} & \text{if right-sided test} \\ \\ \frac{- Z_{\alpha}^*}{\sqrt{2} \cdot erf^{-1}(2 \alpha - 1)} & \text{if left-sided test} \end{cases} $$ - $Z$ is the signed observed z-statistic (z-score). ================================================================================ # Sequential Probability Ratio Tests URL: https://docs.statsig.com/experiments/advanced-setup/sprt ================================================================================ # Sequential Probability Ratio Tests The sequential probability ratio test (SPRT) decides an A/B test by comparing how likely your data is under the alternative hypothesis versus the null hypothesis, and stops when that likelihood ratio crosses an upper or lower boundary set from your alpha and beta. You can read results at any time with no peeking penalty, and you can accept the null hypothesis as well as the alternative. SPRT requires a baseline mean, standard deviation, and minimum detectable effect (MDE) for each metric before the experiment starts. Statsig offers three analysis methods, which you choose with the _Analytics Type_ setting under Advanced Settings on the experiment Setup tab. Use frequentist analysis with [sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) for standard p-values and confidence intervals that stay valid when you read results early. Use SPRT when you want unlimited peeking and the option to accept the null hypothesis as well as reject it. Use [Bayesian mode](https://docs.statsig.com/experiments/advanced-setup/bayesian) for chance-to-beat and expected-loss readouts, with optional priors from past experiments. ![SPRT experiment results scorecard](https://docs.statsig.com/images/experiments/sprt/sprt_scorecard.png) ## Likelihood ratio and decision boundaries SPRT relies on the likelihood ratio (LR) and on upper and lower decision boundaries, A and B. The likelihood ratio compares the likelihood of two explanations for what you observe: - **Numerator**: The likelihood of the observed data if the alternative hypothesis, which you set, is correct. - **Denominator**: The likelihood of the observed data if the null hypothesis is correct. An LR of 5.8 means that what you observed is 5.8 times more likely under the alternative hypothesis than under the null hypothesis. You can report a result as "With an LR of 3.5, it's 3.5 times more likely that the feature worked." Your tolerances for Type I error (alpha) and Type II error (beta) determine the decision boundaries: - **A**: If the LR exceeds this upper boundary, accept the alternative hypothesis. - **B**: If the LR falls below this lower boundary, accept the null hypothesis. - If the LR falls between the boundaries, continue collecting data. ![SPRT Hover Card](https://docs.statsig.com/images/experiments/sprt/sprt_hover_card.png) ## Comparing SPRT to other analysis methods | Category | Frequentist | Bayesian | SPRT | | --- | --- | --- | --- | | Test statistic | p-value: the probability of observing results at least as extreme as the sample data if the null hypothesis is true | Posterior probability: the probability that test is better than control given the observed data and your prior information | Likelihood ratio: a comparison of the goodness of fit of two competing statistical models | | Decision threshold | Alpha (industry standard 5%) | Posterior probability and credible intervals | Upper and lower decision boundaries based on the alpha and beta you pick | | Decision framework | Reject/Fail to Reject the Null based on if p-value > 5% | Whether chance to beat control exceeds the pre-set decision threshold | Accept the null hypothesis, accept the alternative hypothesis, or continue, based on the comparison of the calculated likelihood ratio with the upper and lower decision boundaries | | Allows peeking | Yes, with sequential testing penalties | Yes, unlimited | Yes, unlimited | | Requires pre-setup | Yes: a sample size calculation based on the historical metric mean and MDE | Optional: you can define a prior distribution per metric if you have previous knowledge, which can accelerate the experiment or correct surprising results | Yes: historical information about each metric and an MDE | | Allows one- and two-sided tests | Yes, per metric | Yes, per metric | Yes, per metric | SPRT is a separate procedure from the sequential testing option. [Sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) adjusts a frequentist analysis to allow repeated looks at results; SPRT is a different decision framework. Both allow continuous looks at experiment results, but they're otherwise separate methods for designing and running an A/B test. SPRT isn't a drop-in replacement for frequentist methods. It requires thresholds and baseline assumptions for each metric, and for some experiment types traditional methods remain preferable. ## How to use SPRT in Statsig ### Enable SPRT Set _Analytics Type_ to **SPRT** under Advanced Settings on the experiment Setup tab. Selecting it reveals _SPRT Settings_, which holds the default confidence interval, the **Power Parameter**, a **Make all metrics one-sided** option, and _SPRT Sensitivity_. Under _SPRT Sensitivity_, choose a **Baseline Mode**: - **Use experiment control group**: Statsig derives the baseline from the experiment's own control group. This is the recommended option and needs no manual entry. - **Manual setup**: Set Cohen's d for each metric yourself by supplying an **MDE (%)**, a **Mean**, and a **Standard Deviation**, as described in [Power analysis and setting Cohen's d](#power-analysis-and-setting-cohens-d). To fill these from a previous experiment instead of typing them, pick that experiment under _Fetch baseline values from past experiment_ and select **Run Query**. The per-metric table also shows the **Estimated Decision Sample Size** and **Testing Direction** for each metric. Set these values before the experiment starts. ![SPRT power analysis configuration interface](https://docs.statsig.com/images/experiments/sprt/sprt_power_analysis.png) ### Interpret results The experiment Results tab shows the latest likelihood ratio for each metric and indicates when a metric reaches a decision boundary, so you can accept the null or alternative hypothesis. ![SPRT experiment results dashboard](https://docs.statsig.com/images/experiments/sprt/sprt_results_readout.png) ## Computing SPRT results Statsig uses an updated version of [Hajnal's two-sample t test](https://www.jstor.org/stable/2333131) ([Schnuerch and Erdfelder](https://doi.org/10.1037/met0000234), as modified by Derek Ho of Atlassian) in its SPRT calculations. The traditional ratio test using t- or F-distributions (Schnuerch and Erdfelder equations 8 and 10) simplifies to a ratio of standard normal distributions. $$ \begin{split} {LR} &= \frac {f(t^2| {df}, \Delta)} {f(t^2| {df}, 1)} \\ &= \frac {\phi(|z_{m}|; \theta, 1)} {\phi(|z_{m}|; 0, 1)} \\ \end{split} $$ where: - $\phi(x; \theta, 1)$ is the PDF of a normal distribution of shape $\mathcal{N}(\theta, 1)$ evaluated at $x$. - $z$ is the observed z-statistic between the groups: $$ z = \frac {\Delta \bar{X}} {\sigma_{\Delta\bar{X}}} = \frac {\bar{X}_B - \bar{X}_A} {\sigma_{\Delta\bar{X}}} $$ $$ \sigma_{\Delta\bar{X}}=\sqrt{\frac{var(X_A)}{N_A}+\frac{var(X_B)}{N_B}} $$ - $\theta$ derives from Cohen's d, which you set before the experiment for the metric under consideration: $$ \theta = \frac {\delta} {\sqrt{ \frac{1}{N_A} + \frac{1}{N_B} }} $$ - $N_A$ and $N_B$ are the number of observed units for each group. Because log likelihood ratios are a more convenient scale for reporting, taking the natural log of the LR simplifies the equation further: $$ \begin{split} LLR &= ln(LR) \\ &= |z_m \cdot \phi_m | - \frac{1}{2}{|\phi_m|}^2 \end{split} $$ ### Power analysis and setting Cohen's d SPRT requires that you set a value of [Cohen's d](https://en.wikiversity.org/wiki/Cohen%27s_d) before the experiment starts for each metric you evaluate. Setting the parameter requires three components: - **MDE**: A minimum detectable effect to measure, in units of percent. - **Mean**: A baseline average value for the metric, $\overline{X}$. - **Standard deviation**: A baseline standard deviation for the metric, $\sigma_{X}$. With these values, you can compute the Cohen's d parameter for each metric: $$ \delta = \frac{\text{MDE\%} \cdot \overline{X}}{100 \cdot \sigma_{X}} $$ You can automate this process with Statsig's built-in query tooling. If a past experiment ran on a set of units similar to the ones you expect in the upcoming experiment, select it as the _Baseline Experiment_; a query then pulls the relevant metric parameters automatically. You can also enter all three parameters manually. ### Estimating the decision sample size Statsig uses Cohen's d to compute experiment results after the experiment starts, and it can also estimate experiment duration in advance. Because SPRT lets you look at results as often as you want, this estimate isn't the same as the required sample size in traditional frequentist testing. The decision sample size is an estimate of the number of samples sufficient for a metric's SPRT result to exceed either boundary and accept one of the hypotheses. SPRT can shorten an experiment when the evidence for or against an effect is strong; if the effect is small or the data is noisy, the test may run longer than this estimate. Given: $$ A=ln\left(\frac{1-\beta}{\alpha}\right) $$ $$ k=\frac{n_{ec}}{n_{et}}=\frac{\text{units expected in control}}{\text{units expected in treatment}}=\frac{\text{\% units expected in control}}{\text{\% units expected in treatment}} $$ $$ n_{et} = \frac{A}{\frac{1}{2}\left(\frac{k}{1+k}\right)\delta^2} $$ the total number of expected units at decision time is: $$ n_e=n_{et}+n_{ec}=n_{et}(1+k) $$ ================================================================================ # Bayesian Experiments URL: https://docs.statsig.com/experiments/advanced-setup/bayesian ================================================================================ # Bayesian Experiments Bayesian mode reports each metric as a chance to beat control and an expected loss instead of a p-value, and can combine an informative prior with the observed data. Use it when stakeholders need probability readouts, or when you have reliable priors from past experiments. Experiments use frequentist analysis by default. Statsig offers three analysis methods, which you choose with the _Analytics Type_ setting under Advanced Settings on the experiment Setup tab. Use frequentist analysis with [sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) for standard p-values and confidence intervals that stay valid when you read results early. Use [SPRT](https://docs.statsig.com/experiments/advanced-setup/sprt) when you want unlimited peeking and the option to accept the null hypothesis as well as reject it. Use Bayesian mode for chance-to-beat and expected-loss readouts, with optional priors from past experiments. ## Turn on Bayesian mode To switch an experiment to Bayesian mode, set _Analytics Type_ to **Bayesian** under Advanced Settings on the experiment Setup tab. You can't change the analytics type after the experiment starts. Selecting Bayesian reveals _Bayesian Mode Settings_, where **Default Chance to Beat Threshold** sets the probability a variant must reach for Statsig to call it a winner. ![Bayesian experiment configuration interface](https://docs.statsig.com/images/experiments/advanced-setup/bayesian/c9c01a57-fe13-47a9-b734-20d6e8d715a4.png) Scorecard results and deep-dive analysis both reflect Bayesian statistics. ![Bayesian scorecard results showing credible intervals](https://docs.statsig.com/images/experiments/advanced-setup/bayesian/be912632-6200-4408-977c-92f48dfdd7bc.png) ![Bayesian deep dive analysis interface](https://docs.statsig.com/images/experiments/advanced-setup/bayesian/c9214142-d11f-48c8-92a4-53581bbc498c.png) ## Informative priors In Bayesian mode, you can set a prior belief on the relative average treatment effect. Statsig combines the prior distribution with the observed data and displays the prior-adjusted results. To turn on priors, select **Use Informative Priors** under _Bayesian Mode Settings_. ![Informative priors configuration interface](https://docs.statsig.com/images/experiments/advanced-setup/bayesian/0aa0a52c-4f97-42af-82dd-4d26dd1de7c0.jpg) ## Deriving a prior from historical data When you use informative priors, make sure your organization understands how the prior influences the experiment results, and base the prior on domain knowledge. Two common patterns: - Use the $AVG(\text{average treatment effect})$ of past experiments with a similar setup and population as the prior mean, and the standard deviation of those effects, or a multiple of it, as the prior standard error. - Use the $AVG(\text{observed standard error})$ of past experiments as the prior standard error. ## How Statsig computes the posterior Denote $\mathcal{N}(ATE_{prior}, STE_{prior}^2)$ as the prior distribution, where $ATE_{prior}$ is the average treatment effect and $STE_{prior}$ is the standard error. Denote $\mathcal{N}(ATE_{observed}, STE_{observed}^2)$ as the observed distribution. Statsig calculates the posterior distribution as: $$ ATE_{post} = \frac{ \frac{ATE_{prior}}{STE_{prior}^2} + \frac{ATE_{observed}}{STE_{observed}^2} }{ \frac{1}{STE_{prior}^2} + \frac{1}{STE_{observed}^2} } $$ $$ STE_{post}^2 = \frac{1}{ \frac{1}{STE_{prior}^2} + \frac{1}{STE_{observed}^2} } $$ If you don't specify a prior, Statsig uses $\mathcal{N}(0, \infty)$ as the prior distribution $\mathcal{N}(ATE_{prior}, STE_{prior}^2)$. ## Bayesian statistics glossary Bayesian A/B tests use different terminology from the frequentist framework. | Term | Definition | | --- | --- | | Credible interval | The interval that contains the true parameter at the given probability. | | Chance to beat | The probability that the test group is better than control. | | Expected loss | The average potential risk if you ship the test variant. | ================================================================================ # One-Sided Test URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/one-sided-test Updated: 2025-09-18 ================================================================================ # One-Sided Test A one-sided test (also called a one-tailed test or non-inferiority test) checks whether a metric moved in one direction that you specify in advance. It allocates the entire significance level ($\alpha$) to that direction. This gives the test more power to detect a change in that direction than the two-sided test Statsig runs by default. It also produces one-sided confidence intervals (CIs) that are narrower in the direction of interest. The trade-off is that a one-sided test never detects movement in the other direction. Use a one-sided test when detecting a change in only one direction is valuable and you can accept missing changes in the other direction, for example regressions in guardrail metrics. Keep the default two-sided test when either direction matters for your decision. For example, you may not care whether a new feature reduces crash rates, but you do care whether it increases them. In that case, you forgo detecting the reduction in favor of better detecting the increase. ## Enable a one-sided test By default, Statsig runs a two-sided test for each metric you add to an experiment. To change the test type, click the metric name on the experiment setup screen. In the popup, change the test type and select the direction you want to measure. > **Note:** > > V1 doesn't support Bayesian testing yet. ![One-sided test configuration interface](https://docs.statsig.com/images/snippets/stats-methods/one-sided-test/23044f21-6249-4fc1-9895-22111bb16010.png) ## Read one-sided test results Metrics using one-sided tests appear on the Results tab similarly to two-sided tests, except that the Results tab shows a one-sided CI rather than a two-sided CI. One-sided CIs extend to positive or negative infinity, because Statsig only detects changes in the specified direction. As with all CIs, the one-sided CI indicates that the true mean value of the metric likely falls within that range. ![One-sided confidence interval visualization](https://docs.statsig.com/images/snippets/stats-methods/one-sided-test/7ab3d680-b4c4-4321-b1fc-cc506b0ab21b.png) ## Why running two one-sided tests reduces power Running two one-sided tests results in a less powerful test. A one-sided test allocates all Type I error ($\alpha$) to one direction. Adding a second one-sided test in the other direction reintroduces the chance of a Type I error in that direction. This produces confidence intervals that appear tighter than warranted, and decision error rates higher than the specified confidence level (default 95%) implies. ================================================================================ # Bonferroni Correction URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction Updated: 2025-09-18 ================================================================================ # Bonferroni Correction Bonferroni correction divides an experiment's significance level ($\alpha$) by the number of comparisons, so the chance of any false positive across all metrics and variants stays at $\alpha$. That chance is the family-wise error rate. The [Benjamini-Hochberg (BH) procedure](https://docs.statsig.com/experiments/statistical-methods/methodologies/benjamini-hochberg-procedure) instead controls the false discovery rate, the share of significant results that are false positives. BH therefore rejects more null hypotheses than Bonferroni for the same p-values. Use BH when a scorecard has many metrics and a small, controlled share of false positives is acceptable. Use Bonferroni when any single false positive is costly. If you run a test with $\alpha$ = 0.05, the probability of a false positive is 5%. Each additional comparison at the same significance level is another opportunity for a false positive, so the chance of at least one false positive grows with the number of comparisons. Bonferroni correction is an optional setting on Statsig experiments. Turn it on under _Advanced Settings_ on the experiment's _Setup_ tab, in [Multiple Hypothesis Corrections](https://docs.statsig.com/experiments/setup/analysis-settings#significance-level-adjustments). You can't combine it with the Benjamini-Hochberg procedure on the same experiment. ## How Bonferroni divides the significance level You can apply Bonferroni correction based on one or both of the following: - **Test groups** (multiple treatment hypotheses): Statsig divides the significance level by the number of variants it compares against control. - **Metrics in the scorecard**: You select what percentage of your total $\alpha$ Statsig divides evenly among the primary metrics. Statsig splits the remaining $\alpha$ equally among the secondary metrics. If you select both corrections, Statsig applies them together: after dividing $\alpha$ among the metrics, Statsig divides each metric's $\alpha$ by the number of test groups. The following example applies the metric correction with a significance level of 0.05 and 60% of $\alpha$ assigned to primary metrics: | Tier | Count | $\alpha$ share | Per-metric $\alpha$ | | --- | --- | --- | --- | | Primary metrics | 2 | 60% | 0.6 \* 0.05 / 2 = 0.015 | | Secondary metrics | 4 | 40% | 0.4 \* 0.05 / 4 = 0.005 | To also correct for 2 test groups in this example, Statsig divides each per-metric $\alpha$ by 2. When you analyze dimensions with the metric correction enabled, Statsig applies the correction separately for the dimensional breakdown. Statsig uses the number of dimensions as the total metric count for the dimensional analysis. This doesn't affect top-line metrics. ![Bonferroni correction configuration interface](https://docs.statsig.com/images/snippets/stats-methods/bonferroni-correction/038d75eb-5745-4587-b180-86b88594ccb9.png) ## How the adjusted significance level appears in experiment results In the experiment scorecard, Statsig derives confidence intervals for applicable metrics from (1 - adjusted $\alpha$). Hovering over a confidence interval displays the adjusted $\alpha$ alongside other metric details. In the experiment explore section, Statsig calculates a new adjusted $\alpha$ based on your selections, and the confidence intervals use (1 - adjusted $\alpha$). ================================================================================ # Benjamini–Hochberg Procedure URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/benjamini-hochberg-procedure Updated: 2025-09-18 ================================================================================ # Benjamini–Hochberg Procedure The Benjamini-Hochberg (BH) procedure adjusts the significance level when a scorecard tests many metrics, so that only a controlled share of the results you call significant are false positives. That share is the false discovery rate. [Bonferroni correction](https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction) instead controls the family-wise error rate, the chance of at least one false positive. BH therefore rejects more null hypotheses than Bonferroni for the same p-values. Use BH when a scorecard has many metrics and a small, controlled share of false positives is acceptable. Use Bonferroni when any single false positive is costly. Enable the BH procedure for a single experiment under _Advanced Settings_ on its _Setup_ tab, in [Multiple Hypothesis Corrections](https://docs.statsig.com/experiments/setup/analysis-settings#significance-level-adjustments). Organization admins can turn it on by default for every experiment through [experiment policies](https://docs.statsig.com/access-management/org-admin/experiment_policy). ![Benjamini-Hochberg procedure configuration interface](https://docs.statsig.com/images/snippets/stats-methods/benjamini-hochberg-procedure/c865494e-0ae4-489c-a416-45848b4d10bc.png) ## How BH adjusts the significance level The BH procedure replaces your pre-set significance level ($\alpha$) with a new one. Statsig calculates it as follows: 1. Sort the metric p-values in ascending order. 2. Pair each p-value with a threshold. The threshold is the target false discovery rate ($q$) divided by the number of comparisons ($m$), multiplied by the rank ($k$) of that p-value in the ordered list. 3. Take the largest threshold that is higher than its paired p-value. That threshold becomes the new significance level ($\alpha$). Statsig can apply the BH procedure across one of the following sets of p-values: - **Test groups** (multiple treatment hypotheses): For each metric, Statsig aggregates the p-values from each variant and runs the BH procedure on that list. - **Metrics in the scorecard**: For each variant, Statsig aggregates the p-values from each metric and runs the BH procedure on that list. - **Both test groups and metrics**: Statsig aggregates all p-values and runs the BH procedure once. Statsig doesn't apply the BH procedure to the p-values of event-dimension or user-property breakdowns of an experiment metric. Statsig compares only the top-line metric results to the new significance level. ## How the adjusted significance level appears in experiment results In the experiment scorecard, Statsig derives confidence intervals for applicable metrics from (1 - adjusted $\alpha$). Hovering over a confidence interval displays the adjusted $\alpha$ alongside other metric details. In the experiment explore section, Statsig calculates a new adjusted $\alpha$ based on your selections, and the confidence intervals use (1 - adjusted $\alpha$). ================================================================================ # Variance Reduction URL: https://docs.statsig.com/experiments/statistical-methods/variance-reduction Updated: 2025-09-18 ================================================================================ # Variance Reduction Variance reduction shrinks the noise in an experiment metric so the same effect reaches statistical significance with fewer users or in less time. Statsig applies CUPED to every experiment automatically, applies winsorization to count and sum metrics, and offers stratified sampling when you set up an experiment. Use this page to find which technique applies to your metric; the [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped), [winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization), and [stratified sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling) pages cover the derivations and setup. [Variance](https://docs.statsig.com/experiments/statistical-methods/variance) measures the noise in a metric or in experiment results. Higher variance produces wider confidence intervals and requires a larger sample to observe a statistically significant result for the same effect size. Reducing variance shortens experiment run times. ## CUPED CUPED (Controlled-experiment Using Pre-Existing Data) uses each user's data from before the experiment to reduce variance and increase confidence in experiment metrics. Statsig's implementation follows [Deng, Xu, Kohavi, and Walker (2013)](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf). Statsig applies CUPED automatically to experiments and to the topline results on key metrics on the Results tab, and it reduces variance for most metrics where Statsig can apply it. For the derivation, refer to [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped); for background, refer to the [CUPED launch post](https://blog.statsig.com/cuped-on-statsig-d57f23122d0e). At Statsig, the pre-experiment data covers the 7 days before each user's exposure, rather than a fixed window before the experiment starts for all users. This per-user window helps reduce bias in experiments where the groups differed by chance before exposure. Statsig Cloud uses stratification alongside CUPED to account for users without pre-experiment data. Statsig groups users into strata based on the available pre-experiment information, estimates treatment and control effects within each stratum, aggregates them into an overall result, and then applies the standard difference-in-means and variance estimation. This approach retains users with missing pre-experiment data while still reducing variance where it can. ## Winsorization Winsorization reduces noise by limiting the influence of outliers. It measures the percentile $P_x$ of a metric and sets all values above $P_x$ to $P_x$, which reduces the influence of extreme outliers from causes such as logging errors or bad actors. For the default percentile and variants, refer to [winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization). ## Stratified sampling [Stratified sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling) balances the test and control groups on a metric or attribute before the experiment starts, which reduces the variance of the measured delta for low-volume or high-variance populations. ## Metric selection The metrics you choose also affect the sensitivity of your analysis. Winsorization and CUPED, combined with techniques such as threshold-based flags, let you trade exact numbers for more statistical power. For more, refer to the [blog post on understanding and reducing variance](https://www.statsig.com/blog/understanding-and-reducing-variance-and-standard-deviation). ================================================================================ # CUPED URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped Updated: 2025-09-18 ================================================================================ # CUPED CUPED (Controlled-experiment Using Pre-Existing Data) reduces a metric's variance by adjusting each user's metric value with that user's pre-exposure data. Pre-exposure data is the same metric measured over the 7 days before the user's exposure. Statsig defines this window per user, not as a fixed window before the experiment starts for all users. The adjustment increases confidence in experiment metrics and reduces pre-exposure bias, for example when groups were randomly different before you applied any treatment. Use CUPED when a metric is autocorrelated over time. Use [CURE](https://docs.statsig.com/statsig-warehouse-native/cure/introduction), which extends CUPED on Warehouse Native, when you need covariates beyond the metric's own pre-exposure history, such as in new-user experiments or for metrics that aren't autocorrelated. Statsig Cloud always uses the 7-day pre-exposure window. On Warehouse Native, Statsig recommends the 7-day window, but you can set any length. For how CUPED fits with Statsig's other variance reduction options, refer to [Variance reduction](https://docs.statsig.com/experiments/statistical-methods/variance-reduction). ## CUPED for simple aggregations The original [Microsoft paper](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf) describes the methodology for simple aggregations, as does Statsig's [in-depth CUPED article](https://www.statsig.com/blog/cuped). Statsig Cloud uses stratification alongside CUPED to account for users who have no pre-exposure data. Statsig groups users into strata based on the pre-exposure data available, estimates treatment and control effects within each stratum, then aggregates the strata to produce an overall result. Statsig then applies the standard difference-in-means and variance estimation. This approach retains users with missing pre-exposure data while still reducing variance where pre-exposure data exists. ## CUPED for ratio metrics The Microsoft paper also describes how to implement CUPED for metrics with a different analysis unit (Appendix B). Statsig extends this methodology to ratio metrics, where a numerator and a denominator represent each experiment unit. The variance reduction process finds the variance of the experiment data, the variance of the pre-exposure data, and the covariance between the two. Denote the numerator, denominator, pre-exposure numerator, and pre-exposure denominator of a unit as $Y$, $N$, $X$, and $M$, respectively. Using the CUPED-reduced variance formula, $$ Var(\frac{Y_{cv}}{N_{cv}})=Var(\frac{Y}{N})+\theta^2 Var(\frac{X}{M})-2\theta Cov(\frac{Y}{N}, \frac{X}{M}) $$ where Statsig finds optimal $\theta$ as $$ \frac{Cov(\frac{Y}{N}, \frac{X}{M})}{Var(\frac{X}{M})} $$ expanded to $$ \frac{Cov(\frac{Y}{\mu_N}-\frac{\mu_Y N}{\mu^2_N}, \frac{X}{\mu_M}-\frac{\mu_X M}{\mu^2_M})}{Var(\frac{X}{\mu_M}-\frac{\mu_X M}{\mu^2_M})} $$ This gives: $$ \frac{\hat{Y_{c}}}{\hat{N_{c}}}=\frac{Y_{c}}{N_{c}}-\theta( \frac{X_{c}}{M_{c}} - \mathbb{E}[R]) $$ $$ \frac{\hat{Y_{t}}}{\hat{N_{t}}}=\frac{Y_{t}}{N_{t}}-\theta( \frac{X_{t}}{M_{t}} - \mathbb{E}[R]) $$ Because $\mathbb{E}[R]$ is hard to derive, the expectation term is the same for both groups. Substituting $\mathbb{E}[R]$ with $\frac{X_{c}}{M_{c}}$ transforms these two formulas into the following: $$ \frac{Y_{cv}(control)}{N_{cv}(control)}=\frac{Y(control)}{N(control)} $$ $$ \frac{Y_{cv}(test)}{N_{cv}(test)} :=\frac{Y(control)}{N(control)} - (\frac{Y(control)}{N(control)} - \theta \frac{X(control)}{M(control)}) + (\frac{Y(test)}{N(test)} - \theta\frac{X(test)}{M(test)}) :=\frac{Y(test)}{N(test)} - \theta\frac{X(test)}{M(test)} + \theta \frac{X(control)}{M(control)} $$ Using the optimal $\theta$, Statsig reduces group-level variance by applying the parameter to calculate the adjustment. An across-group $\theta$ doesn't necessarily reduce the variance for one group, or the sum of variances of all groups, but in most cases it does. Simulations show that 98.3% of metrics saw a decrease through CUPED. Statsig applies the CUPED-reduced variance when all of the following are true: - The core assumptions of the CUPED model hold. Rounding error or other data artifacts can violate them: - $E(\hat{X}) = E(X)$ - The pooled variance of the adjusted population across groups is less than the variance of the unadjusted population. - More than 100 units have pre-exposure values. - More than 5% of units have pre-exposure values. ================================================================================ # Winsorization URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization Updated: 2025-09-18 ================================================================================ # Winsorization Winsorization caps a metric's extreme values at a percentile $P_x$: Statsig measures the $P_x$ value of the metric and sets every unit-level value above $P_x$ to $P_x$. This reduces noise from outliers in experiment results without dropping any units. Statsig Cloud winsorizes at the 99.9th percentile by default; Warehouse Native lets you set upper and lower bounds per metric. Use metric capping instead when you know the business maximum for a metric, such as a maximum purchase amount per day, rather than a percentile. Statsig computes $P_x$ from all non-zero, non-null unit-level values of the metric, aggregated from rows or events. The value of the unit at $P_x$ is the threshold Statsig applies to the other units' values. ## Default percentile and configurable bounds by deployment #### Statsig Cloud In Statsig Cloud, the default percentile for winsorization is 99.9%. This default reduces the influence of extreme outliers caused by factors such as logging errors or bad actors. Statsig applies winsorization to sum, event count, mean, ratio, and funnel metrics, including imported metrics. Winsorization doesn't apply to participation or user accounting metrics. #### Warehouse Native In Warehouse Native, you configure winsorization per metric and choose the upper bound, the lower bound, or both. ![Winsorization configuration interface](https://docs.statsig.com/images/snippets/stats-methods/winsorization/6d058842-27f7-4b6b-9bd8-245a5f894f90.png) Statsig applies winsorization to sum, event count, mean, and ratio metrics. ## Metric capping Metric capping handles outliers by setting a maximum value for a metric. You define the maximum for each unit type configured for that metric, and Statsig adjusts any value that exceeds the cap downward to the cap. For example, if purchases greater than $10,000 per day shouldn't skew analysis, Statsig adjusts any transaction exceeding that threshold downward to $10,000. Statsig supports capped metrics for event count and aggregation (sum) metric types. ================================================================================ # Stratified Sampling URL: https://docs.statsig.com/experiments/advanced-setup/stratified-sampling ================================================================================ # Stratified Sampling Stratified sampling balances the test and control groups on a metric or attribute you choose before the experiment starts. Statsig does this by trying many randomization salts and keeping the one that produces the most balanced split. Use it for low-volume or high-variance populations, such as B2B experiments where a few accounts drive most of a metric; for large consumer populations, a standard random split balances the groups on its own. ## What stratified sampling does Stratified sampling divides the population into homogeneous groups called strata and draws random samples from each stratum. For example, if you have XS and XL customers and randomize them into Control and Test, you want both groups balanced across XS and XL customers. You can also stratify on a metric such as revenue per user. With large populations, randomization usually produces this balance. In B2B and other low-volume or high-variance scenarios, stratified sampling enforces it. Statsig supports automated and manual stratified sampling. In tests where a small tail of power users drives a large share of a metric, stratified sampling reduces false positive rates and makes results more consistent. In Statsig's simulations, it decreased the variance of reported results by around 50%. ## Automated stratified sampling ### How Statsig selects a salt The Statsig SDKs use a salt to randomize experiment subjects into groups; refer to [how bucketing works in the Statsig SDKs](https://docs.statsig.com/faq#how-does-bucketing-in-the-statsig-sdks-work). When you turn on stratified sampling, Statsig tries a set of candidate salts (100 by default) and evaluates how balanced the resulting groups are, based on either a metric you select or an attribute that describes your experiment subjects. It then saves the best salt. For background, refer to the [stratified sampling launch post](https://statsig.com/blog/introducing-stratified-sampling). ![Stratified sampling algorithm diagram](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/99f72b83-9f14-45a3-aa6e-ffcbd6211ec7.png) The salt selection space is large enough that stratifying multiple experiments on the same metric doesn't cause overlap between them. In Statsig's simulations, the groups were as independent as expected, consistent with the published literature. [Morgan and Rubin (2012)](https://projecteuclid.org/journals/annals-of-statistics/volume-40/issue-2/Rerandomization-to-improve-covariate-balance-in-experiments/10.1214/12-AOS1008.full) cover the history, philosophy, and proofs of re-randomization, including how it reduces the randomization variance of the difference in means. The paper notes that standard asymptotic analysis procedures that don't account for re-randomization are statistically conservative. To keep results consistent and comparable across methods, Statsig stays conservative and uses the standard t-test. ### Turn on stratified sampling On the experiment setup page, under Advanced Settings, select **Stratified Sampling**. You can stratify in two ways. If you choose a metric to stratify on, Statsig uses that metric to balance the groups. ![Stratified sampling metric selection interface](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/0cfc499d-4fdf-44a8-ba2a-3537ba5bb904.png) If you instead choose an attribute or classification (for example, S, M, L, XL), Statsig uses that to balance the groups. On Statsig Cloud, you upload a CSV; this option is in Early Access. On Statsig Warehouse Native, you use entity properties. ![Entity properties configuration for stratified sampling](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/102a839f-37fd-4443-807a-4b269f137490.png) After you select **Stratify**, Statsig analyzes a set of salts and picks the best one. ![Stratification analysis results interface](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/412f5c78-8c4f-4f16-88d3-60d3d3555ffd.png) ## Best practices ### Population Statsig uses when balancing When evaluating salts, Statsig computes balance using pre-experiment data for the entire targeted population of the experiment's unit type (for example, all `userID`s or all `customerID`s) over the selected lookback window. Statsig doesn't filter on exposure because the experiment hasn't started. Every candidate salt is assessed over the same population; only the randomization that the salt induces changes. ### New units after stratification The chosen salt assigns units that weren't in the pre-experiment data deterministically, which is effectively random with respect to the balancing metric. These new units don't influence the salt selection and may cause some drift from the initial balance. ### When to use stratified sampling Stratification adds time and compute cost that scales with the number of units, and it adds steps before the experiment starts. Use it when you expect imbalance from heterogeneous units (for example, whales) or skewed metrics. If you don't expect meaningful imbalance, use a standard random split. ### Allocation below 100% Statsig evaluates all candidate salts assuming full (100%) allocation of the targeted population. If you run the experiment at a lower allocation, random sampling of that subset can reintroduce imbalance; for example, some high-impact units may fall disproportionately into one arm by chance. Prefer 100% allocation for the period you care most about for inference. Use lower allocations briefly for safe rollouts rather than for the full experiment duration. ### Stratification duration Duration depends on the number of units and the metric or source Statsig queries. There is no fixed SLA; larger populations take longer. ## Manual assignment for stratified sampling When you set up an experiment, you can configure overrides, for example to force user X or Segment A into Control and user Y or Segment B into Test. Overrides are for testing, so Statsig excludes overridden users from experimental analysis in experiment results. To use manual assignment for stratified sampling, select the **Include Overrides in Pulse** checkbox, which includes manually overridden users in each variant in all metric lift analyses. You can assign 100% of experiment participants to variants manually, or assign a subset manually and randomly assign the remainder. > **Note:** > > You can add overrides for an ID type that differs from the ID type of the experiment. Those ID evaluations don't resolve to the ID type of the experiment and don't contribute to experiment results. When the Statsig SDK handles assignment, it handles randomization. When you control assignment, you're responsible for balancing users across experiment groups. ![Manual assignment override configuration](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/230964234-8cc81f66-f4f8-4f37-b6df-6d36d0d7ab98.png) ================================================================================ # SRM Checks URL: https://docs.statsig.com/stats-engine/methodologies/srm-checks ================================================================================ # SRM Checks ## SRM - sample ratio mismatch Sample ratio mismatch (SRM) occurs when the observed allocation of unique users between test groups differs from the expected allocation or split of the test. Refer to the [Statsig blog post on sample ratio mismatch](https://www.statsig.com/blog/sample-ratio-mismatch) for background. SRM is a signal that there may be unknown bias in the test. Unknown bias is a significant problem because, without a clear diagnosis of the imbalance, it's difficult to know how much the bias affects your results. ## SRM checks Statsig runs SRM checks on all experiments and feature gates as part of Health Checks (refer to [Health Checks](https://docs.statsig.com/experiments/monitor)). Statsig uses a Chi-squared test to identify whether the split of users between groups indicates a sample ratio mismatch. ![SRM health check results interface](https://docs.statsig.com/images/experiments/srm-checks-health.png) Statsig automatically analyzes data by common dimensions that the Statsig SDK logs to identify potential drivers of SRM. These include sdk\_type, sdk\_version, reason, is\_bot, browser\_name, browser\_version, os, os\_version, and region. ![SRM dimension analysis breakdown](https://docs.statsig.com/images/experiments/srm-checks-dimensions.png) ================================================================================ # Managing SRM URL: https://docs.statsig.com/experiments/monitoring/srm Updated: 2025-09-18 ================================================================================ # Managing SRM Sample ratio mismatch (SRM) means the number of units in each experiment group differs from your configured split by more than randomness explains. Statsig runs a chi-squared test on exposures and shows SRM in the experiment's health checks as a warning or an alert. Treat a persistent alert as a data-quality problem: the groups are no longer comparable, so you can't trust metric lifts until you find the cause or restart the experiment. ## What SRM looks like The following exposure crosstab shows an experiment with SRM. The group percentages look similar. However, if an assignment system splits traffic evenly, an imbalance this extreme or greater has less than a 0.01% chance of occurring randomly. ![Exposure crosstab of an experiment with sample ratio mismatch](https://docs.statsig.com/images/experiments/srm.png) Statsig and most experiment platforms normalize metrics per user: they measure a count metric as total count divided by unique users in the experiment. In isolation, having more users in one group isn't a problem. ## Why SRM biases results SRM is usually non-random: the extra or missing traffic isn't identical to the original traffic. Common causes of SRM include: - A bug causes a user's client or browser to crash before it can send an exposure log. Statsig doesn't re-expose users who don't return, but includes users who return. This introduces bias in measurement. - A conditional dependency filters which users Statsig exposes based on some characteristic for one or more groups, which makes those groups non-identical to other groups and biases measurement. - A script bulk-exposes users one group at a time, and the system truncates logs after a certain count, which cuts off the last group's exposures. SRM checks detect these effects even at low rates, and even low-rate SRM can lead to inaccurate experiment readouts. ## How Statsig detects SRM Statsig detects SRM with a [chi-squared test](https://en.wikipedia.org/wiki/Chi-squared_test), which determines whether observed frequencies match expected frequencies. In the crosstab example on this page, the expected distribution is 167.85k units per group, but the observed counts are 166.08k, 171.18k, and 166.30k. A low p-value rejects the null hypothesis that the groups are identical and indicates a difference between the groups' observed and expected assignment rates. ## What to do if an experiment has SRM When Statsig detects SRM, it sets the experiment's health check to a warning or failure state, depending on how extreme the SRM is. For the p-value thresholds behind each state, go to [Monitor an experiment](https://docs.statsig.com/experiments/monitor#srm-thresholds). ![Experiment health check showing an SRM failure](https://docs.statsig.com/images/experiments/srm_failure.png) Teams often hesitate to reset an experiment and lose collected data, and an underlying issue may reproduce after a reset. Follow these steps to diagnose and address SRM. ### Check the time series data Statsig generates a chart of the SRM p-value over time. If the chart is noisy and fluctuates, the alert is more likely a false positive. If the p-value consistently trends down to 0, a real assignment issue is likely. The following p-value chart indicates a real issue. ![SRM p-value chart trending toward zero over time](https://docs.statsig.com/images/experiments/bad_pvalue.png) ### Look for a clear root cause Use Statsig's SRM debugger or analyze exported exposures to determine whether a specific segment drives the SRM. Often a bug affects only one platform, such as Android, or only users with slow internet connections. If you find and fix the bug, you can restart the experiment safely. If the experiment was expensive or required a long data collection period, and the issue is clearly isolated to one segment, you can instead filter that segment out of the analysis. ### Decide how to proceed In most cases, the best path is to investigate, fix, and restart the experiment. Statsig recommends against proceeding without investigation and considers restarting the experiment a best practice, ideally after you investigate any potential SRM cause. If the SRM is mild enough, and the experiment low-risk enough, you may accept a decision based on the affected data. ================================================================================ # Pre-Experiment Bias URL: https://docs.statsig.com/experiments/statistical-methods/pre-experiment-bias Updated: 2025-09-18 ================================================================================ # Pre-Experiment Bias Pre-experiment bias is a difference in a metric's average between the test and control groups that existed before exposure, so experiment analysis can mistake it for a treatment effect and make a result appear more or less significant than it is. Statsig runs its standard results test on each scorecard metric's pre-exposure data and flags metrics where the groups already differed. Treat the flag as a caution when the metric is critical and you need an exact lift; proceed when the delta is small or CUPED absorbs it. [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) helps correct this bias but can't fully account for it. Some metrics, such as retention, aren't candidates for CUPED, and you can't easily adjust them. ## How Statsig detects pre-experiment bias Statsig measures the pre-experiment values of all scorecard metrics for all experiment groups by running the standard [results](https://docs.statsig.com/experiments/interpreting-results/read-results) calculation on the pre-experiment period. The lookback covers one week on Statsig Cloud, and your configured CUPED lookback window on Warehouse Native. Statsig then calculates the p-value for the null hypothesis that the groups are identical, and flags results using thresholds that balance awareness against false positives from a high number of scorecard metrics or groups. When Statsig detects bias, it notifies you and places a warning on the affected results. The _Days Since Exposure_ view helps you identify novelty effects and pre-experiment effects. In the following example, the test group had a consistently higher mean than the control group in the week before exposure. ![Pre-experiment bias visualization showing test group with consistently higher mean than control group](https://docs.statsig.com/images/snippets/stats-methods/pre-experiment-bias/246545035-22ff2db6-9c08-4227-a53d-8faa8feb5e92.png) ## What to do when Statsig flags a metric Pre-experiment bias can occur by chance and isn't always a problem: - If the total delta is small, it may not meaningfully change your interpretation of results. - If CUPED can account for the bias, the bias shouldn't affect your results. In many cases the warning is informational, and you can proceed while treating the affected metrics with caution. Proceeding is appropriate when the metric isn't critical to the experiment, or when you care more about the direction of movement than the exact number. When the bias has no systemic source, running longer also reduces it, because new users dilute the initial imbalance. If the metric is critical to your analysis and you need the exact value, consider resalting and restarting the experiment. ================================================================================ # Bot Traffic URL: https://docs.statsig.com/experiments/monitoring/bots ================================================================================ # Bot Traffic Statsig removes exposures from known bots, such as search crawlers, AI scrapers, and link previewers, before it computes exposure counts and experiment results, so metrics reflect real users. Bots still receive gate and experiment values from the SDK; filtering affects analysis only. Follow the segment procedure on this page when you also need to control what bots see, for example to stop a search engine from indexing an unreleased homepage variant. ## How bot filtering works Statsig filters known bots out of exposures data for feature gates, holdouts, layers, and experiments, so the exposure counts and analytics you see reflect real users only. Without filtering, bot traffic from search engines and AI scrapers makes it harder to measure how many real users see your changes. For background, refer to the [Statsig guide to online bot filtering](https://www.statsig.com/blog/guide-online-bot-filtering). After Statsig filters bot data from your exposures data, the bot data isn't viewable in the Statsig console. Contact Statsig in Slack if you have questions about filtered data. ## Control what bots see in gates and experiments Statsig doesn't block bots from receiving your feature gates and experiments. The API and SDK serve bots configs and variants following your setup; Statsig filters only their exposures from analysis data and from the exposure count on the Results tab. To restrict what bots see, for example to keep search engines from indexing a new homepage variant before release, create a segment of known bots and apply it to your gates and experiments. ### Create a Known Bots segment Create a new segment named "Known Bots" for your project. The segment must be a conditional segment. ![New conditional segment setup for capturing known bots](https://docs.statsig.com/images/experiments/monitoring/bots/5bc62f62-7613-41d2-bcca-6f89f13baa3a.png) After you create the segment, add a rule. Set _Criteria_ to **Browser Name** and leave _Operator_ as **Any Of**. In the _Values_ field, paste the full string from the [Bot list](#bot-list) section (use the copy button to the right of the list). The Statsig console splits the pasted list into individual bot names. ![Segment rule showing browser name filter populated with bot list](https://docs.statsig.com/images/experiments/monitoring/bots/97c1cdfe-9d65-42ae-acc7-ed47b583fce6.png) You can reuse this segment for all your launches. ### Apply the segment to gates and experiments For gates, create a new rule that controls the bot experience. ![Feature gate rule ensuring known bots fail the rollout](https://docs.statsig.com/images/experiments/monitoring/bots/d6b51af0-ecfc-49c4-9e48-73bd276836ef.png) For experiments, create a conditional override that forces units in this segment to receive the variant you want. ![Experiment conditional override mapping bot segment to control variant](https://docs.statsig.com/images/experiments/monitoring/bots/97ec1bcd-6f03-4b51-b0fe-9859f11559b1.png) ## Opt out of bot filtering Statsig configures bot filtering at the project level. Admins can opt out of filtering in the console settings. ![Bot filtering settings interface](https://docs.statsig.com/images/experiments/monitoring/bots/4c171000-6733-4136-a383-4cfd2b738ccb.png) ## Suggest new bots to Statsig If you discover bots that Statsig doesn't include in the default set, contact Statsig in Slack. You can also ask Statsig to apply your company's internally managed bot list to all bot filtering. ## Bot list Paste this list into the _Values_ field of the Known Bots segment rule. ```text Scomplerbot, WincherBot, fixbot, keys-so-bot, MojeekBot, Gulper Web Bot, Mattermost-Bot, SerendeputyBot, uipbot, WebCrawler, HearsayPDFBot, WRTNBot, BublupBot, InsytfulBot, DingTalkBot, uk_ldfc_renderbot, crawlers, ImagesiftBot, idealo-bot, taboolabot, KlaxoonBot, SemrushBot, archiver/3.1.1 +http://www.archive.org/details/archive.org_bot, StractBot, crawler_eb_germany_2, exabot, DocBase Crawler, co Bot, Superfeedr bot, Pokey_Bot, GooglePlusBot, OtherwebBot, PubMatic Crawler Bot, SiteAuditBot, Gensparkbot, wpbot, archive.org_bot, Audisto Crawler, amazon-product-discovery-bot, Atomseobot, Googlebot-Mobile, hubspot crawler, XoviOnpageCrawler, PerplexityBot, QualifiedBot, YodaoBot, BitSightBot, GG PeekBot, SMTBot, amazonproductbot, FAST-WebCrawler, TwitterCommerceBot, WellKnownBot, PAGEFREEZER CRAWLER, dbot, htc_botdugls, RavenCrawler, oBot, notebot, ViberBot, KStandBot, scoopit-crawler, SpeechifyBot, Spider_Bot, txt Crawler, net/bot, BugBountyBot, Letianpai_Robot, by fynd.bot, discobot, LineBotWebhook, ahrefsbot, Veoozbot, tkbot, coccocbot, Googlebot-Video, Streamline3Bot, Zoombot, adbeat_bot, msnbot, Nextdoorbot, node DuckAssistBot, redditbot, Xing Bot, DocSearch Crawler, ; bot, Storebot, playwright-bot, 47_safeAreaBottom, online-webceo-bot, SmarshBot, BeeperBot, ChannelBot, BrightEdge Crawler, //boteden, Quantcastbot, SpringserveBot, IAS Crawler, managr-webcrawler, ) Bot, Dragonbot, crawler4j, tyseobotmobile, IVW-Crawler, SEBot, sap-search-web-crawler, AndersPinkBot, Dcard-link-preview-bot, Mediumbot, Light Crawler, dataforseobot, Better Uptime Bot, CCBot, es_bot, DuckAssistBot, SeznamBot, telegrambot, crawler, Jugendschutzprogramm-Crawler, SeoCherryBot, GroupMeBot, HyperMegaBotGettingOnlyHTMLsFromYourWebsite, our-crawler, Slackbot-LinkExpanding, YandexMobileBot, Web-Crawler, PaperLiBot, Swiftbot, Paqlebot, YandexRenderResourcesBot, MetaJobBot, SynologyChatBot, GenomeCrawlerd, robot, StatusCakeBot, node bitlybot, Your robot, Pharosbot, TSMbot, WalluBot, slackbot, AmazonAdBot, AspiegelBot, EzoicBot, TiggeritoBot, eventseekerBot, AwarioBot, Leikibot, Timpibot, like Gecko) bot, Quora-Bot, JobBot, googlebot, PetalBot, eu bot, LinkArchiver twitter bot, DF Bot, Screaming Frog Wise SEO Spider, Clickagy Intelligence Bot, BLP_bbot, bitlybot, WazzupCrawler, web-crawler, pingbot, yoozBot, triptease-bot, Plesk screenshot bot, Magus Bot, node Screaming Frog SEO Spider, YextBot, seobilitybot, tyseobot, applebot, bingbot, GetLocalBot, TwitterBot, rogerbot, Preview Service; bot, traq-ogp-fetcher-curl-bot, seesawbot, Greppr Web Crawler, ResearchBot, web-bot, iAskBot, JobboerseBot, CriteoBot, FandomOpenGraphBot, com feedbot, Amazon-Advertising-ad-standards-bot, MotoMinerBot, peer39_crawler, Discordbot, DuckDuckGo-Favicons-Bot, KeybaseBot, adsbot, Open Graph Bot, emulate-seobots, bountybot, InfobipCrawler, GoogleBot, macox bot, Google-bot, captify-crawler, Robot, aiHitBot, fedistatsCrawler, ExtendedStayBot, NetpeakCheckerBot, com/bots, Automattic Analytics Crawler, Blog Rssbot, Dubbotbot, Rightlander Crawler, ClarityBot, Cookiebot, UOrgTestingBot, AcademicBotRTU, SEMrushBot, Server Crawler, Diffbot, DiscourseBot, chatbot, VirusTotalBot, SaberBot, TZUnfurlBot, Mail.RU_Bot, Monsidobot, YandexAccessibilityBot, preview service; bot, ecoresearchCrawler, PulsePoint-Crawler, DataForSeoBot, petalbot, Xbot, LinkedInBot, GnowitNewsbot, vebidoobot, Bawaab_bot, Brightbot, ClineCrawler, ; Bot, MSIECrawler, MoodleBot, Testcrawler, AASA-Bot, GPTBot, StrapBot, 5) bot, mj12bot, screaming frog seo spider, HubSpot Crawler, COIBotParser, OcelotBot, com crawler, Pinterestbot, VelenPublicWebCrawler, Firefox superpagesbot2, Parser Robot, GrapeshotCrawler, Mediatoolkitbot, am a bot, semrushbot, SearchAtlas Bot, DiffeoBot, IBM-Crawler, spbot, DatoCmsSearchBot, SISTRIX Crawler, bountybotttt, Summalybot, ID bot, node AppleNewsBot, DotBot, TesseractBotAgent, foundeebot, BadooBot, BacklinksExtendedBot, wowLink Crawler, about-crawlers, find-seo-bot, GraphiteBot, Sidetrade indexer bot, BLEXBot, rc-crawler, FacebookBot, nerdybot, Senutobot, Facebot, //botim, WallabyupBot, TurnitinBot, XBot_Senior, node ZoominfoBot, AhrefsBot, Exabot, PhaverBot, Applebot, TermlyBot, SemjiBot, Space Unfurl Bot, Slackbot, bidswitchbot, //botsin, AdsBot-Google, Morningscore Bot, DuckDuckBot, UptimeRobot, ClaudeBot, naverbookmarkcrawler, PingdomBot, Web Crawler, PlurkBot, node GrowSEOBot, WebExplorerSearchBot, node FullStoryBot, WebwikiBot, bot, policy adbeat_bot, trendictionbot0, ezoicbot, Catrobatbot, AdsTxtCrawlerTP, com/bot, Nigooutbot, PiBot, pinterestbot, http-spiders-bot, Ocarinabot, msnbot-media, AppsFlyerBot, SeobilityBot, Impressumscrawler, SurdotlyBot, cXensebot, Amazonbot, Rankabot, 2ip bot, harsilbot, FullStoryBot, com bot, Rhobot, FreshpingBot, twitterbot, Twitterbot, Caliperbot, Googlebot-Image, osapon ) bot, yandexbot, MJ12bot, Taboolabot, ActiveComplyBot, MixrankBot, 48_safeAreaBottom, compatible; botify, LoomlyBot, Googlebot, ev-crawler, pagefreezer crawler, AwarioSmartBot, iCjobs Stellenangebote, jbot, aixnew_aibot, SemanticScholarBot, Wire LinkPreview Bot, Elastic-Crawler, UCMore Crawler, x28-job-bot, ISSCyberRiskCrawler, AnytypeBot, clever tech bot, LivelapBot, Screaming Frog SEO Spider, RyteBot, SiteGuruCrawler, XBot, SuperBot, TypetalkBot, RepoLookoutBot, obot, TimeTreeBot, siteauditbot, iASD_SpiderBot, semaltbot, PopeTech-ScanBot, SummalyBot, aka-bot, YandexBot, HatenaBlog-bot, Googlebot-News, yacybot, SiteCheckerBotCrawler, node AwarioSmartBot, turbotime, net-Robot, reurl-bot, Google-Display-Ads-Bot, node CCBot, fr_bot, CapterraBot, seo-audit-check-bot, gptbot, Testomatobot, Snap-URL-Preview (bot, robots, ZumBot, hstspreload-bot, Fedicabot, serpstatbot, Synapse (bot, NetSeer crawler, uk_ldfc_bot, PartnerOptimizer-bot, Scrapbox Bot, domainsbot, NE Crawler, startmebot, VelaBot, SeekportBot, Radius Compliance Bot, AdkernelTopicCrawler, Linkbot, AppleNewsBot, Jones Searchbot, DropboxPreviewBot, ZoominfoBot, edansbot, Baiduspider-render, Python Requests, YisouSpider, OAI-SearchBot, AliyunSecBot, Baiduspider, Bytespider, TikTokSpider, Claude-SearchBot, Qwantbot, Thinkbot, ABEvalBot, HanaleiBot, OpenindexSpider, VamosBot, StartmeBot, Bingbot, parisbot, BetaLiveCrawlBot, MetaBot, CharSiuBot, PlagAwareBot, io/bot, ShowUpCrawler, ScraperBot, Monibot, ShellBot, IbouBot, MatchboxBot, CookieYesbot, Stripebot, Clearscopebot, quillbot, Sogou web spider, Checker Spider, AI2Bot, Google-Extended, GoogleOther, Storebot-Google, carbon-umbrella-bot, facebookexternalhit, meta-externalads, meta-externalagent, meta-webindexer, ``` ================================================================================ # Confidence Intervals URL: https://docs.statsig.com/experiments/statistical-methods/confidence-intervals Updated: 2025-09-18 ================================================================================ # Confidence Intervals A confidence interval is the range of metric deltas consistent with your experiment data at a chosen confidence level. Statsig draws it as the gray, red, or green bar on each metric on the Results tab; a 95% interval that excludes zero is statistically significant at $\alpha = 0.05$. Read the interval, not only the [p-value](https://docs.statsig.com/experiments/statistical-methods/p-value), when you need to know how large the effect could plausibly be. A 95% confidence interval contains the true effect 95% of the time: if you ran an experiment 100 times, the true metric delta would fall inside the interval about 95 times. If the true effect is zero, you expect the interval to exclude zero only 5% of the time (a false positive). A wider interval means less certainty about the exact size of the effect. ![Confidence interval visualization showing statistical significance](https://docs.statsig.com/images/snippets/stats-methods/confidence-intervals/168382034-73afed14-d9f5-42cb-ade1-034526002a0b.png) ## Computing confidence intervals Statsig calculates confidence intervals with a two-sample z-test. The test requires the variance of the metric delta, which Statsig derives differently for each metric type; refer to [standard error and mean variance](https://docs.statsig.com/experiments/statistical-methods/variance). After establishing the variance of the delta, Statsig computes the confidence interval. ### Two-sided tests For the absolute metric delta, Statsig computes the confidence interval as: $$ CI(\Delta \overline{X}) = \Delta \overline{X} \pm Z_{\alpha/2} \cdot \sqrt{{var(\Delta \overline{X})}} $$ where: - $Z_{\alpha/2}$ is the z-critical value for the significance level you want (1.96 for the standard $\alpha=0.05$ and 95% confidence interval) for a two-sided test. - $var(\Delta \overline{X})$ is the [variance of the absolute delta](https://docs.statsig.com/experiments/statistical-methods/variance). The confidence interval for the relative metric delta uses one of two methods: [Fieller Intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals) or the [Delta Method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method). You can choose either method. Statsig turns on Fieller Intervals by default for new customers. With Fieller Intervals, the relative metric delta confidence interval is: $$ CI(\% \Delta \overline{X} ) = \frac{1}{1-g} ( \frac{\overline{X_T}}{\overline{X_C}} - 1 \pm \frac{Z_{\alpha/2}}{\sqrt{n_C} \cdot \overline{X_C}} \sqrt{(1-g) \cdot \frac{var(X_T)}{n_T(n_T-1)} + \frac{\overline{X_T} var(X_C)}{\overline{X_C} n_C (n_C-1)}}) $$ With the Delta Method, the confidence interval is: $$ \begin{split} CI(\Delta \overline X\%) &= \Delta \overline X\% \pm Z_{\alpha/2} \cdot\sqrt{{var(\Delta \overline X\%)}}\\ &= \frac{\Delta \overline X}{\overline X_c} \pm Z_{\alpha/2} \cdot\sqrt{(\frac{\overline X_t}{\overline X_c})^{2} \cdot (\frac{var(X_c)}{n_c \cdot \overline X_c^2} + \frac{var(X_t)}{n_t \cdot \overline X_t^2})} \cdot 100\% \end{split} $$ If you use the Delta Method and the control mean isn't significantly different from zero, the interval simplifies to: $$ \begin{split} CI(\Delta \overline X\%) &= \Delta \overline X\% \pm Z_{\alpha/2} \cdot\sqrt{{var(\Delta \overline X\%)}} \\ &= \frac{\Delta \overline X}{\overline X_c} \pm Z_{\alpha/2} \cdot \frac{\sqrt{{var\left(\Delta \overline X\right)}}}{\overline X_c} \cdot 100\% \end{split} $$ A statistically significant p-value and a relative delta confidence interval that excludes zero don't always align. The p-value of the absolute difference between test and control can be significant while uncertainty in the control mean affects the relative delta interval. With the Delta Method, the relative delta confidence interval may cross zero; with Fieller Intervals, it may appear as a point estimate. ### One-sided tests For one-sided tests, the confidence interval calculation changes to redistribute the false positive rate toward the direction you're testing, either increases or decreases in the metric: $$ CI(\Delta \overline{X}) = \begin{cases} \left[\Delta \overline{X} - Z_{\alpha} \cdot \sqrt{{var(\Delta \overline{X})}}, \quad +\infty \right) & \text{if right-hand test}\\ \\ \left(-\infty, \quad \Delta \overline{X} + Z_{\alpha} \cdot \sqrt{{var(\Delta \overline{X})}} : \right] & \text{if left-hand test} \end{cases} $$ where: - $Z_{\alpha}$ is the z-critical value for the significance level you want (1.645 for the standard $\alpha=0.05$ and 95% confidence interval) for a one-sided test. - $var(\Delta \overline{X})$ is the variance of the absolute delta. - The interval Statsig uses depends on whether the one-sided test looks for increases or decreases in the metric. ## Welch's t-test for small sample sizes For small sample sizes, Statsig uses Welch's t-test instead of a z-test. Welch's t-test handles samples of unequal size or variance without increasing the false positive rate. The confidence interval has the same form as the two-sample z-test interval for one- and two-sided tests, with the t-critical value with $\nu$ degrees of freedom in place of the z-critical value. For a two-sided test, the confidence interval is: $$ CI(\Delta \overline{X}) = \Delta \overline{X} \pm t_{\alpha/2} \cdot \sqrt{{var(\Delta \overline{X})}} $$ $$ \nu = \frac{\left(var(\overline X_t) + var(\overline X_c)\right)^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} = \frac{var(\Delta\overline{X})^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} $$ where $N_t$ and $N_c$ are the number of users in the test and control groups. For a large number of degrees of freedom, the t-statistic converges with the z-statistic, so Statsig uses Welch's t-test only when $\nu < 100$. ## Comparing experiment data to a fixed baseline with a one-sample t-test To answer a question such as "Does my test variant lead to a click-through rate higher than 0.5?", define a fixed-baseline comparison when you add metrics to the experiment. For details, refer to [one-sample tests](https://docs.statsig.com/experiments/statistical-methods/methodologies/one-sample-test). Statsig calculates the confidence interval as: $$ CI(\Delta \overline X) = (\overline X_{group} - fixed \ value) \pm Z \cdot\sqrt{{var( \overline X_{group})}} $$ ================================================================================ # p-Value Calculation URL: https://docs.statsig.com/experiments/statistical-methods/p-value Updated: 2025-09-18 ================================================================================ # p-Value Calculation The p-value is the probability of observing a metric delta at least as large as the measured one if the treatment had no effect, which is the null hypothesis. Statsig marks a metric statistically significant when its p-value is below the Type I error threshold $\alpha$ (0.05 by default), using a two-sample z-test, or Welch's t-test when the degrees of freedom $\nu$ are below 100. Use the p-value to decide whether an effect exists; use the [confidence interval](https://docs.statsig.com/experiments/statistical-methods/confidence-intervals) to judge how large it is. In both tests, the p-value depends on the metric [mean](https://docs.statsig.com/experiments/statistical-methods/metric-deltas) and [variance](https://docs.statsig.com/experiments/statistical-methods/variance) that Statsig computes for the test and control groups. A p-value below $\alpha$ usually coincides with a confidence interval that doesn't cross zero. For the exception with relative deltas under the Delta Method and Fieller Intervals, refer to [confidence intervals](https://docs.statsig.com/experiments/statistical-methods/confidence-intervals). ## Two-sample tests ### Two-sided z-test Statsig computes the z-statistic (z-score) of a two-sample z-test. The following forms are equivalent: $$ \begin{split} Z &= \frac{\overline X_t - \overline X_c}{\sqrt{var(\overline X_t)+ var(\overline X_c)}} \\ &= \frac{\overline X_t - \overline X_c}{\sqrt{var(\Delta \overline{X})}} \\ &= \frac{\overline X_t - \overline X_c}{\sqrt{\sigma_{\overline{X}_t}^2 + \sigma_{\overline{X}_c}^2}} \end{split} $$ where: - $Z$ is the observed z-statistic, not the z-critical value $Z_{\alpha/2}$. - $var(\Delta \overline{X})$ is the variance of the absolute delta of means. - $var(\overline{X}_i)$ is the [variance of the sample mean](https://docs.statsig.com/experiments/statistical-methods/variance) of the control or treatment group. - $\sigma_{\overline{X}_t}$ is the standard error of the mean of the control or treatment group. The Results tab shows these values on the _Statistics_ tab of a metric. The two-sided p-value comes from the standard normal cumulative distribution function: $$ p-value = 2 \cdot \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{-|Z|}{e^{-t^2/2}dt} $$ ### Welch's t-test For smaller sample sizes, Welch's t-test produces lower false positive rates when group sizes and variances are unequal. On the Results tab, Statsig applies Welch's t-test automatically when the degrees of freedom $\nu < 100$. Statsig computes the t-statistic (t-score) with the same formula as the two-sample z-statistic, and the degrees of freedom $\nu$ as: $$ \nu = \frac{\left(var(\overline X_t) + var(\overline X_c)\right)^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} := \frac{var(\Delta\overline{X})^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} $$ Statsig then obtains the p-value from the t-distribution with $\nu$ degrees of freedom. ### One-sided z-test For a one-sided z-test, Statsig computes the z-statistic $Z$ with the same formula as the two-sided test, and takes the p-value from the standard normal cumulative distribution function with these differences: $$ p-value = \begin{cases} 1 - \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z}{e^{-t^2/2}dt} &\text{if right-hand test}\\ \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z}{e^{-t^2/2}dt} &\text{if left-hand test} \end{cases} $$ where $Z$ is the signed z-statistic, not the absolute value that the two-sided p-value uses. ================================================================================ # Metric Deltas URL: https://docs.statsig.com/experiments/statistical-methods/metric-deltas ================================================================================ # Metric Deltas A metric delta is the difference in mean metric value per user between two experiment groups, by default test minus control. The Results tab shows an absolute delta (the difference in means) and a relative delta (the absolute delta as a percentage of the control mean). Read the absolute delta to size an impact in metric units; read the relative delta to compare impact across metrics with different baselines. ## Computing metric deltas The metric delta represents the impact measured in experiment results. To account for the different number of users (or units) in each group, Statsig compares the mean metric value per user, not the total. > **Note:** > > Statsig defines all deltas as the difference between a treatment group and a presumably unchanged control group, but you can compare any two groups. If you reverse the order of comparison on the Results tab to control versus treatment, Statsig reverses all deltas and inverts the direction of change. The absolute delta is the difference between the two means: $$ \Delta \overline{X}=\overline{X}_t-\overline{X}_c $$ The relative delta expresses the impact relative to the baseline value of the metric. For example, an absolute delta of +1 clicks per user is a 100% increase against a baseline of 1 and a 1% increase against a baseline of 100. Statsig computes the relative delta with the control group mean as the baseline: $$ \Delta \overline{X} \%=\frac{\overline{X}_t-\overline{X}_c}{\overline{X}_c} \times 100 \% $$ ## Computing means The method for calculating metric means depends on the metric type. ### Event count and sum metrics These metrics represent totals: the number of times an event occurs, the sum of time spent, the total purchase amount, and similar values. The mean is the average user-level total during the analysis period. The mean value of the metric $X$ for a group is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} X_{i, d} $$ where: - $N$ is the number of users in the group. - $n_i$ is the number of days during the analysis period that user $i$ was in the experiment. - $X_{i,d}$ is the metric value for user $i$ on day $d$. > **Note:** > > In the group mean, Statsig includes only user metrics recorded after it exposes a user to the experiment. ### User accounting and event user metrics `event_user` metrics set to _Daily Participation Rate_ capture the number of distinct users who have the event each day. In experiment results, Statsig normalizes these values by the number of days the user is in the experiment, which gives the probability that a user is daily active for that event: the daily participation rate. The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \frac{1}{n_i} \sum_{d=0}^{n_i} X_{i, d} $$ where: - $X_{i,d}$ takes the value 0 or 1 depending on whether user $i$ has the event on a given day $d$. Statsig computes the user accounting metrics in the following table in the same way. The new user accounting metrics use a different group mean. | Metric | Type | | --- | --- | | `DAU` | User accounting | | `WAU` | User accounting | | `MAU_28day` | User accounting | | `L7` | User accounting | | `L14` | User accounting | | `L28` | User accounting | | `new_DAU` | New user accounting | | `new_WAU` | New user accounting | | `new_MAU_28day` | New user accounting | For new user accounting metrics, Statsig counts users that are new xAU (new daily, weekly, or monthly active users) at some point during the analysis window. The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \max \left(X_i\right) $$ where $\max(X_i)$ is the maximum value of the new xAU metric for user $i$. > **Note:** > > `event_dau` metrics are in legacy support only, and Statsig no longer creates them for new events. Existing `event_dau` metrics remain available for your new experiments, and Statsig continues to compute them daily. For new events, create an `event_user` metric to measure daily active users. ### Custom ratios, means, retention, and stickiness metrics These are metrics such as click-through rate, average purchase value, and sessions per user. Statsig computes them by dividing a numerator value, $X$, by a denominator value, $Y$. The mean value of a ratio metric $R$ for an experiment group is: $$ \overline{R}=\frac{\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} X_{i, d}}{\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} Y_{i, d}}=\frac{\overline{X}}{\overline{Y}} $$ where $N$ is the number of users in the experiment group that participate in the metric, that is, users with a non-zero denominator value. $X_{i,d}$ and $Y_{i,d}$ are the $X$ and $Y$ values for user $i$ on day $d$. Different approaches exist for ratio metrics in experiments. Statsig chose this implementation because: - $R$ is the ratio of two means of independent observations: a set of user-level $X$ values and a set of user-level $Y$ values. You can therefore use the central limit theorem to obtain the summary statistics of $X$ and $Y$ separately. - Statsig computes the group means in the same way as the topline metric value, which makes the means easier to interpret and relate to the topline metric. ### Event user one-time event For custom `event_user` metrics with _One-Time Event_ selected, Statsig computes how many users have the event at any time after the user enters the experiment. Statsig doesn't normalize this result by the number of days a user is in the experiment. The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N X_{i} $$ where: - $N$ is the number of users in the group. - $X_{i}$ takes the value 0 or 1 depending on whether user $i$ has the event at any point after entering the experiment. ================================================================================ # Standard Error & Mean Variance URL: https://docs.statsig.com/experiments/statistical-methods/variance Updated: 2025-09-18 ================================================================================ # Standard Error & Mean Variance The standard error of a group's mean measures how much that mean would vary across repeated samples. Statsig uses it to build the confidence interval and p-value for every metric delta. It equals the sample standard deviation of $X$ divided by the square root of the number of users in the group, and the Results tab shows it as _Std Err_ next to each group's units and mean. This page gives the variance formula for each metric type. $$ \sigma_{\overline X} = \frac{\sigma_{X}}{\sqrt{N}} = \sqrt{\frac{var(X)}{N}} = \sqrt{var(\overline{X})} $$ Standard deviation is the square root of the variance. Because variances are easier to manipulate algebraically, Statsig derives the variance for each metric type and then takes the square root to obtain the confidence intervals. ## Computing variance The variance of the absolute metric delta is the sum of the variances of the test and control means: $$ var(\Delta \overline X) =var(\overline X_t - \overline X_c) = var(\overline X_t) + var(\overline X_c) $$ The task is therefore to compute the variance of the mean for each group. ### Count and sum metrics For count and sum metrics, Statsig derives the variance of the sample mean for a group directly from the sample variance: $$ var(\overline{X}) = \frac{var(X)}{N} = \frac{\frac{1}{N-1}\sum_{i=0}^{N}(X_i-\overline{X})^2}{N} $$ where: - $N$ is the number of users in the group. - $X_i$ is the metric value for user $i$. - $\overline{X}$ is the user-level average of $X$ for users in that group. ### Ratio and mean metrics Ratio and mean metrics combine two variables, a numerator $X$ and a denominator $Y$, which are typically correlated because both come from the same users. For example, in a clicks per session metric, clicks and sessions are two sets of observations from the same group of users, so they aren't independent. The metric $R$ has a group mean $\overline{R}$ and a group variance of the mean $var(\overline{R})$. To account for this correlation, Statsig obtains the variance of the mean of a ratio metric $R$ with the [delta method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method): $$ var(\overline R) = var\left(\frac{\overline X}{\overline Y}\right) := \left(\frac{\overline X}{\overline Y}\right)^2 \cdot \left(\frac{var(\overline X)}{\overline X^2} + \frac{var(\overline Y)}{\overline Y^2} - 2 \cdot \frac{covar(\overline X, \overline Y)}{\overline X\cdot \overline Y} \right) $$ where Statsig computes the variance of the numerator and denominator means with the same formula as for count and sum metrics, and the covariance is: $$ covar(\overline X, \overline Y) = \frac{covar(X, Y)}{N} = \frac{\frac{1}{N-1}\sum_{i=0}^{N}(X_i-\overline X)\cdot (Y_i-\overline Y)}{N} $$ ================================================================================ # Delta Method URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method Updated: 2025-09-18 ================================================================================ # Delta Method The delta method approximates the variance of a ratio metric, such as clicks per session, from the variances of its numerator and denominator and the covariance between them. Statsig uses it because the numerator and denominator come from the same users and are correlated. For confidence intervals on relative lifts, Statsig recommends [Fieller intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals) instead; the delta method is the large-sample approximation to the Fieller interval. ## Delta method for ratio metrics Statsig uses the delta method to calculate the variance of metrics that have a numerator and a denominator. The variance of ratio and mean metrics depends on the numerator and denominator variables, which are typically correlated. For example, consider a clicks per session metric. The number of clicks and the number of sessions are two sets of observations from the same group of users, so they aren't independent of each other. To account for this correlation, Statsig obtains the variance of a ratio metric $R$ using the delta method: ![Delta method variance formula](https://docs.statsig.com/images/snippets/stats-methods/delta-method/167956015-cc3f9fca-2c4d-410c-bff1-3f13dd16d105.png) Statsig computes the variance of the numerator and denominator means the same way it does for count metrics (refer to [Variance](https://docs.statsig.com/experiments/statistical-methods/variance)). The covariance is ![Covariance calculation formula](https://docs.statsig.com/images/snippets/stats-methods/delta-method/167956127-c17017ef-07b2-4f76-88c4-00539eec50a7.png) ## Delta method for relative lifts Statsig can also use the delta method to calculate the confidence interval for relative lifts. The alternative, which Statsig recommends, is [Fieller intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals). The delta method is an approximation of the Fieller interval that converges to it as the sample size grows. ================================================================================ # One-Sample Test URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/one-sample-test Updated: 2025-09-18 ================================================================================ # One-Sample Test A one-sample test compares one experiment group's metric against a fixed baseline instead of against a control group, and reports whether the difference is statistically significant. In Statsig, you set the fixed baseline for a metric with the _Use Fixed Baseline as Control_ option on the experiment setup page. The scorecard then compares the group against that value. Use a one-sample test when only one group can produce the metric, or when you're testing against a known target such as a 50% success rate. Use a standard two-group test whenever a real control group exists. ## When to use a one-sample test A one-sample test fits these situations: - **Single-group events**: When only one group can trigger certain events (for example, feature usage or error types), compare that group against an expected fixed baseline. - **Algorithm testing**: Test whether an algorithm performs better than random (for example, whether a success rate differs from 50%). ## Enable a fixed baseline for a metric 1. Go to the setup page of an experiment. 2. Click the metric name. 3. Select **Use Fixed Baseline as Control**. The following screenshots show the metrics section of the experiment setup page, the metric name menu, and the fixed baseline dialog. ![Experiment setup screen highlighting metrics section](https://docs.statsig.com/images/experiments/statistical-methods/methodologies/one-sample-test/742634e0-0db9-44f9-b849-0a205f604a76.png) ![Metric name dropdown showing configure options](https://docs.statsig.com/images/experiments/statistical-methods/methodologies/one-sample-test/3a645771-4771-480e-a263-15a6af951284.png) ![Fixed baseline control dialog for one-sample test configuration](https://docs.statsig.com/images/experiments/statistical-methods/methodologies/one-sample-test/9c7e85d6-e0b0-40bb-a22c-a96d7084d3e7.png) ================================================================================ # Fieller Intervals URL: https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals Updated: 2025-09-18 ================================================================================ # Fieller Intervals Fieller intervals give an exact confidence interval for the relative change between test and control groups, accounting for the uncertainty in the control mean that forms the denominator. Statsig recommends Fieller intervals over the [delta method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method), which approximates the variance of the ratio and builds a confidence interval from that approximation. Fieller intervals stay reliable when sample sizes are small or denominators are noisy; the two methods agree in most other cases. ## How Statsig calculates a Fieller interval ### Check that the Fieller interval is well defined Before applying Fieller's theorem, Statsig checks that the denominator of the relative lift metric, $\overline{X_C}$, is significantly distinct from 0. Statsig calculates the parameter $g$: $$ g = \frac{Z_{\alpha/2}^2 \cdot \mathrm{var}(X_C)}{(n_C-1) \cdot \overline{X_C}^2} $$ Where: - $Z_{\alpha/2}$ is the critical value for the confidence level you select. - $\mathrm{var}(X_C)$ is the variance of the control group metric values. - $n_C$ is the number of units in the control group. - $\overline{X_C}$ is the mean of the control group metric values. When $g$ is less than 1, the control mean is significantly different from 0, and Statsig uses the Fieller interval. ### Apply the Fieller interval formula Because the control and test group results are independent of each other, Statsig drops the covariance terms in Fieller's theorem. $$ CI(\% \Delta \overline{X} ) = \frac{1}{1-g} \left( \frac{\overline{X_T}}{\overline{X_C}} \pm \frac{Z_{\alpha/2}}{\overline{X_C}} \sqrt{ \frac{\overline{X_T}^2}{\overline{X_C}^2} \cdot \frac{\mathrm{var}(X_C)}{n_C-1} + (1-g)\frac{\mathrm{var}(X_T)}{n_T-1} } \right) - 1 $$ Where: - $\overline{X_T}$ is the mean of the test group metric values. - $\mathrm{var}(X_T)$ is the variance of the test group metric values. - $n_T$ is the number of units in the test group. ### Handle a control mean that isn't distinct from zero In rare cases (less than 5% of observed metric comparisons on Statsig), $g$ is greater than or equal to 1, which means the control group's mean isn't statistically distinguishable from 0. When $\overline{X_C}$ isn't statistically different from zero, the denominator of the relative lift calculation is unstable, so the confidence interval for the percent difference between test and control is unbounded. When the confidence interval is unbounded, Statsig surfaces the relative lift observed during the experiment: $$ \% \Delta \overline{X} = \frac{\overline{X_T}-\overline{X_C}}{\overline{X_C}} $$ ## Enable Fieller intervals in Statsig Configure the relative confidence interval methodology in your _Experimentation Settings_ at the organization level. Changing this setting affects only experiments created after the change. ![Experimentation settings configuration interface](https://docs.statsig.com/images/snippets/stats-methods/fieller-intervals/9c8b90f8-1f0b-472f-883d-c3f30bd78696.png) In the experiment scorecard, Fieller intervals appear as shown: ![Experiment scorecard with Fieller intervals](https://docs.statsig.com/images/snippets/stats-methods/fieller-intervals/1cb4ebb6-0425-49bf-a319-48794d25ce96.png) ================================================================================ # Feature Flags URL: https://docs.statsig.com/feature-flags/overview ================================================================================ # Feature Flags **Feature Gates**, commonly known as feature flags, allow you to toggle the behavior of your product in real time without deploying new code. Developers often use Feature Gates to turn on certain features for a small percentage of the total user base. This approach enables safer, gradual software releases because you can monitor the impact on system behavior. Feature Gates also let you limit application behavior for a specific set of users, such as dogfooding [environments](https://docs.statsig.com/guides/using-environments). ![Feature Gates hero image](https://docs.statsig.com/images/feature-flags/featuregates.png) ## When to use #### Use when you need to - Schedule gradual feature rollouts to safely deploy new code - Set up dev staging environments before code hits production, like dogfooding - Have an emergency disable switch that lets you immediately turn off a particular code branch for users in production - Modify the user experience based on attributes like username, email, or other identifiers - Change app behavior based on context like device, browser type, version, and other environment attributes #### Not recommended if - You need to return structured or multi-value data based on targeting rules and conditions: use a [Dynamic Config](https://docs.statsig.com/dynamic-config/overview) instead. - You want to test complex hypotheses beyond simple A/B tests and launch impact: set up an [Experiment](https://docs.statsig.com/experiments/overview) instead. ## How it works 1. [Create a Feature Gate](https://docs.statsig.com/feature-flags/create) with [targeting rules](https://docs.statsig.com/feature-flags/conditions) in the Statsig console. 2. To have the Feature Gate impact users, integrate the [Statsig SDK](https://docs.statsig.com/sdks/getting-started) into your product code. The SDK queries the gate value at runtime and returns a true/false result based on user attributes, environment data, and other conditions you define. 3. [Test a Feature Gate](https://docs.statsig.com/feature-flags/test-gate) to confirm it behaves as expected before rolling it out. 4. For finer targeting control, set up [Feature Gate overrides](https://docs.statsig.com/feature-flags/overrides) to allow specific users to bypass the gate. 5. After your Feature Gate is live, [view Feature Gate exposures](https://docs.statsig.com/feature-flags/view-exposures) in the Statsig console to monitor who encounters your gate. 6. Set up deprecation rules and clean up old flags by [managing Feature Gate lifecycles](https://docs.statsig.com/feature-flags/feature-flags-lifecycle). ## Key capabilities ### Scheduled rollouts Gradually deploy a feature over time by setting up a Feature Gate as a [Scheduled Rollout](https://docs.statsig.com/feature-flags/scheduled-rollouts). ### Overrides and bypass lists Implement Feature Gates with [Overrides](https://docs.statsig.com/feature-flags/overrides) to allow a specific list of users to bypass your gate. ### Chained flag dependencies Chain Feature Gates together in parent-child or other dependent relationships so a top-level gate can enable or disable all its dependent flags at once. This is useful for global disable switches that guard sub-features. ### Built-in A/B tests Run simple A/B tests without additional setup using [Pulse](https://docs.statsig.com/feature-flags/view-exposures). In practice, treat the users who see the new feature as the "treatment" group. Treat the gated users, who don't see the new feature yet, as the "control" group. ### Feature Gate testing [Test your Feature Gates](https://docs.statsig.com/feature-flags/test-gate) with Statsig's built-in tools to check whether your Feature Gate targets the right people. ## FAQs #### How are Feature Gates different from Dynamic Configs? Dynamic Configs are key-value configs that let you return structured data (not just true/false) based on targeting rules. They're more for customizing behavior, tuning parameters, or supporting complex logic _beyond booleans_. Feature Gates are simpler on/off switches for gating access to a feature. Technically, you can set up a Dynamic Config as a Feature Gate. #### When should I use Feature Gates instead of Experiments (and vice versa)? Go to [Choosing Feature Flags vs. Experiments](https://docs.statsig.com/guides/featureflags-or-experiments) for a full guide. Use Feature Gates to measure the general impact of a feature rollout. Use Experiments when you have a more specific hypothesis or test in mind. ## Related tutorials - [Set up dev environments with Feature Gates](https://docs.statsig.com/guides/using-environments) - [Customize dev environments with Feature Gates](https://docs.statsig.com/guides/testing) - [Choosing Feature Flags vs. Experiments](https://docs.statsig.com/guides/featureflags-or-experiments) - [Best Practices for Feature Gates](https://docs.statsig.com/feature-flags/best-practices) ================================================================================ # Build Your First Feature URL: https://docs.statsig.com/guides/first-feature ================================================================================ # Build Your First Feature > **Info:** > > Statsig refers to feature flags as _feature gates_ across the console and SDKs. The terms are interchangeable throughout this guide. A feature gate controls who sees a new feature and rolls it out gradually without deploying code. This tutorial creates a feature gate, targets mobile platforms and internal testers, then checks it live with the JavaScript SDK in your browser console. 1. **Create a feature gate** Navigate to the [Feature Gates page](https://console.statsig.com/gates) and click **Get Started** (or **Create** if you already have gates). ![Feature Gates page with Create button](https://docs.statsig.com/images/guides/first-feature/feature-gates-page.png) Give the gate a clear name and description. For example, `Mobile Registration` with a note about the new mobile sign-up flow. 2. **Target mobile platforms** New gates default to returning `false` until you add targeting. Click **Add New Rule**, choose **Operating System → Any of**, and select **Android** and **iOS**. Set the pass percentage to 100% and click **Add Rule**, then **Save**. ![Adding a mobile targeting rule](https://docs.statsig.com/images/guides/first-feature/add-rule.png) 3. **Add an internal testing rule** Add a second rule for your team. For example, use **Email → Contains any of** with your company domain so employees can exercise the feature regardless of device. ![Gate with mobile and email rules](https://docs.statsig.com/images/guides/first-feature/gate-rules.png) 4. **Generate a client API key** Go to [Project Settings → API Keys](https://console.statsig.com/api_keys) and copy the **Client API key**. Keep server secret keys on backends only, and use console API keys for programmatic configuration work. 5. **Load the JavaScript SDK** > **Tip:** > > Statsig supports many platforms. Refer to [Client SDK options](https://docs.statsig.com/sdks/getting-started) for alternatives. This walkthrough uses the browser SDK so you can experiment directly in DevTools. Paste the snippet below into the browser console on any site to load the SDK from jsDelivr: ```js const script = document.createElement('script'); script.src = 'https://cdn.jsdelivr.net/npm/@statsig/js-client@3/build/statsig-js-client+session-replay+web-analytics.min.js'; document.head.appendChild(script); ``` ![Injecting the SDK via DevTools](https://docs.statsig.com/images/guides/first-feature/add-sdk-script.png) 6. **Initialize and check the gate** Replace `YOUR_SDK_KEY` with the client key from Step 4 and run: ```js const client = new window.Statsig.StatsigClient('YOUR_SDK_KEY', {}); await client.initializeAsync(); ``` Then call: ```js client.checkGate('mobile_registration'); ``` You should see `false` because the current session isn’t mobile and doesn’t use the employee email domain. 7. **Simulate a mobile environment** Enable the mobile device toolbar in Chrome DevTools. ![Chrome DevTools mobile device toolbar icon](https://docs.statsig.com/images/guides/first-feature/devtools-mobile-toolbar.png) Re-evaluate the user to pick up the new environment and re-check the gate: ```js await client.updateUserAsync({}); client.checkGate('mobile_registration'); ``` The gate should now return `true` for the mobile profile. ![Gate returning true for mobile rule](https://docs.statsig.com/images/guides/first-feature/mobile-rule-true.png) 8. **Test the employee backdoor** Switch DevTools back to the desktop view and update the user with a company email: ```js await client.updateUserAsync({ email: 'teammate@statsig.com' }); client.checkGate('mobile_registration'); ``` The gate passes again because of the email rule. ![Gate returning true via email rule](https://docs.statsig.com/images/guides/first-feature/email-rule-true.png) 9. **Flush exposures and inspect diagnostics** ```js client.flush(); ``` Open the gate’s **Diagnostics** tab to confirm each exposure, including the failing desktop check, mobile pass, and employee pass. ![Diagnostics exposure stream showing recent checks](https://docs.statsig.com/images/guides/first-feature/diagnostics-stream.png) ## Use the gate in production Wrap feature logic in a gate check so only targeted users see the experience: ```js if (client.checkGate('mobile_registration')) { show(mobileRegistrationPage); } else { show(oldRegistrationPage); } ``` Your feature gate is ready for production. ================================================================================ # When to Use Feature Gates vs. Experiments? URL: https://docs.statsig.com/guides/featureflags-or-experiments ================================================================================ # When to Use Feature Gates vs. Experiments? > **Info:** > > Statsig calls feature flags **feature gates**. The terminology is interchangeable throughout this guide. Use a feature gate to control who sees a feature and roll it out gradually; use an experiment to compare variants and measure how a change affects your metrics. Both create control and test groups, so this guide shows how to pick the right one for your launch and measurement goals. --- ## Quick guidance - **Choose a feature gate** when you want to roll out a feature gradually or monitor impact as you ramp. - **Choose an experiment** when you need to compare multiple variants and quantify the lift across metrics. --- ## Key differences ### Variants - **Feature gate** → Two experiences only: pass vs. fail. - **Experiment** → Any number of variants. When viewing gate exposures you see three buckets: _Pass_, _Fail_, and _Fail – Not in Analysis_. Statsig uses only the balanced subset of the fail group for metric comparisons. Learn more in the [gate exposure methodology](https://docs.statsig.com/feature-flags/view-exposures#gate-exposures). ### Return values - **Feature gate** → Boolean (`true`/`false`) so your application toggles code paths. - **Experiment** → JSON config that describes the variant (colors, copy, thresholds, etc.). ### Ramping knobs - **Feature gate** → Adjust **Pass %** to send more traffic to the new experience. You can go beyond 50/50 (e.g. 99% vs 1%). - **Experiment** → Adjust **Allocation %** to enroll more users, but splits cap at 50/50. After Statsig assigns a user, neither control reshuffles existing users. You can safely ramp without re-bucketing. ![Pass% versus Allocation% controls](https://docs.statsig.com/images/guides/featureflags-or-experiments/pass-vs-allocation.png) --- ## When experiments shine Use experiments when you need: 1. **Multiple variants or personalization**: compare more than two options or tailor experiences using contextual bandits or layers. 2. **Stable identifiers and custom IDs**: analyze behavior before signup with stable IDs, or use custom IDs for sessions, workspaces, or geography. 3. **Isolated universes**: run parallel experiments safely by placing them in their own layers. --- ## When feature gates shine Feature gates are great for: - **Safe rollouts**: gradually increase exposure while observing metrics. - **Targeting audiences**: use gates as pre-filters before enrolling users in an experiment. In experiment setups, gates often act as targeting criteria. The flow looks like this: 1. **Targeting gate** picks the eligible audience. 2. **Allocation %** (experiment) decides how much of that audience participates. 3. **Split %** distributes participants across variants. After you choose a winner, lift the targeting gate and let the winning variant reach everyone. --- ## Summary: choosing the right tool - Start with a feature gate if you have a single variant to launch carefully. - Choose experiments when you need quantitative comparisons across variants. - Combine both when you want precise audience control plus rigorous measurement. For more detail, refer to: - [Feature gate exposures](https://docs.statsig.com/feature-flags/view-exposures) - [Experiments overview](https://docs.statsig.com/experiments/overview) - [Layers for mutual exclusion](https://docs.statsig.com/experiments/layers-overview) ================================================================================ # Create a Feature Gate URL: https://docs.statsig.com/feature-flags/create ================================================================================ # Create a Feature Gate ## In the Statsig console ### Create a new feature gate 1. Log into the Statsig console at https://console.statsig.com. 2. On the left-hand navigation panel, under **Feature Management**, select **Feature Gates**. 3. Click on the **Create** button. 4. Enter the name and description of the Feature Gate you want to create. Name your gate based on what you're rolling out, such as "Zippy Home Page" for a new homepage. ![Feature gate creation form](https://docs.statsig.com/images/feature-flags/create/a14bc4f3-b768-4e6c-a84a-7bae449b2c7c.png) 5. Click **Create** to complete creating your Feature Gate. 6. You have created a new Feature Gate without any evaluation rules or conditions. ![Newly created feature gate without rules](https://docs.statsig.com/images/feature-flags/create/64a7bc9a-bd3e-4d98-a853-4f91f16ef82e.png) ### Add a rule to your feature gate By default, a Feature Gate returns `false` when there are no rules configured. Statsig blocks all users from seeing the feature until you set rules for who gets to "pass". The following steps walk through adding evaluation rules or conditions for a Feature Gate. 1. In Statsig console, under **Feature Management**, select **Feature Gates**. 2. Select the feature gate where you want to add a targeting rule. 3. Click the **+ Add New Rule** button. ![Add rule button interface](https://docs.statsig.com/images/feature-flags/add-rule.png) 4. Name your rule with something descriptive that other teammates understand, such as "Mobile Users Only". 5. Configure your Feature Gate with the following options: - **Environment(s)**: The [staging environment(s)](https://docs.statsig.com/guides/using-environments) you want your gate to apply to - [**Criteria**](https://docs.statsig.com/feature-flags/conditions): Specific evaluation conditions for the rule. Learn more about [criteria and condition evaluation](https://docs.statsig.com/feature-flags/conditions). - **Split %**: The percentage of users who meet the criteria that you want to pass or fail the gate check. Statsig automatically calculates the Fail % based on the Pass % you set. - [**Overrides**](https://docs.statsig.com/feature-flags/overrides): A list of users you want to always bypass your gate (an allow list) 6. Statsig doesn't auto-save changes to Feature Gates and targeting rules. Select **Save** at the bottom right when you're ready for your changes to take effect. Statsig evaluates rules top to bottom and applies the first match, so [rule order matters](https://docs.statsig.com/feature-flags/conditions). To reorder rules, drag a rule by its `IF` / `ELSE IF` rail to a new position; to add a rule at a specific spot, hover between two rules and click **Insert new rule**. ## In your code The previous steps covered setting up Feature Gates in the web console. For these gates to impact the behavior of your application, you also need to update your product code. The Statsig SDK handles the evaluation so that gate decisions take effect in real time. ### Initialize the Statsig SDK If you haven't already initialized the Statsig SDK, follow the [Installation Steps](https://docs.statsig.com/client/React#installation) in the language of your choice. ### Check a feature gate Use the `checkGate` function in the Statsig SDK. You can find a code snippet for any particular gate on that gate's page in the Statsig console. Select the code snippet button, then select the SDK you want to use. ![Gate code snippet button](https://docs.statsig.com/images/feature-flags/create/b52add6e-4352-4be4-b902-56d77a33d28b.png) Here's an example in [React](https://docs.statsig.com/client/React#basics-check-gate): ```tsx const { client } = useStatsigClient(); return (
Gate is {client.checkGate("example_gate") ? "passing" : "failing"}.
); ``` In this example, the Statsig SDK checks from a client app whether you set up any rules named "Example Gate". Statsig renders the text "Gate is passing" for users who pass your gate conditions, and "Gate is failing" for users who fail the gate conditions. > **Tip:** > > Statsig offers over 20 client and server-side SDKs. Go to the full list of [SDKs](https://docs.statsig.com/sdks/quickstart#all-sdks) to find the one that best fits your needs. ## Common feature gate setups ### Kill switches Set up a kill switch by setting an `Everyone` criteria's Pass percentage to 100%. To completely disable the feature for all users after code deployment, set the Pass percentage to 0%. ### OS-based flags You can target users based on common application properties such as the operating system that the application is running on. For example, to target iOS users only, you can create a rule with the "Operating System" criteria, the "Any of" operator, and then listing "iOS" in the text field. ### Internal employees only You can target users based on known user attributes. For example, you can use the user's **Email** attribute and the **Contains any of** operator, then enter the email domain of your company to target only internal employees. ### Defined user segments You can also target users in a defined user [Segment](https://docs.statsig.com/segments/overview). ### Parent/child flags You can target users based on their eligibility of other Feature Gates, enabling powerful chaining, hierarchy, and dependencies of flags. [Flag lifecycle management](https://docs.statsig.com/feature-flags/feature-flags-lifecycle) makes it easy to manage, deprecate, and maintain dependent flags. ================================================================================ # Feature Gate rule criteria URL: https://docs.statsig.com/feature-flags/conditions ================================================================================ # Feature Gate rule criteria Statsig feature gates contain a list of rules that Statsig evaluates in order from top to bottom. Each rule's conditions determine which users qualify for the Pass or Fail treatment. The Pass percentage sets how many qualifying users see the new feature. ## Rule evaluation Statsig evaluates the rules you create in the order they're listed. For each rule, the criteria or conditions determine which users qualify for the Pass/Fail treatments. The Pass percentage further determines the percentage of qualifying users that Statsig exposes to the new feature. The remaining qualifying users see the feature disabled. For rules set up as shown below, the following flowchart illustrates how Statsig evaluates them. ![Example Rules Gate](https://docs.statsig.com/images/conditions/example-rules-gate.png) ![Statsig evaluates targeting rules in order. A user who fails rule 1 (Dogfooding) is evaluated against rule 2 (English locale), and a user who fails that is evaluated against rule 3 (Everyone else). A user who passes a rule joins that rule's user pool and isn't evaluated against later rules. Within each pool, the pass percentage decides who Statsig exposes to the feature and who sees it disabled: 100% and 0% for rule 1, 20% and 80% for rule 2, and 10% and 90% for rule 3.](https://docs.statsig.com/images/diagrams/gate-rules-evaluation.svg) ![Statsig evaluates targeting rules in order. A user who fails rule 1 (Dogfooding) is evaluated against rule 2 (English locale), and a user who fails that is evaluated against rule 3 (Everyone else). A user who passes a rule joins that rule's user pool and isn't evaluated against later rules. Within each pool, the pass percentage decides who Statsig exposes to the feature and who sees it disabled: 100% and 0% for rule 1, 20% and 80% for rule 2, and 10% and 90% for rule 3.](https://docs.statsig.com/images/diagrams/gate-rules-evaluation.dark.svg) After a user qualifies based on the condition in a given rule, Statsig doesn't evaluate subsequent rules for that user. Statsig then assigns the qualifying user to either the Pass or Fail group of that rule. In the example, the third rule for **Remaining Folks** captures all users who don't qualify for the previous two rules. Removing this third rule means only users in pools 1 and 2 qualify for this feature gate and for analysis, not your total user base. ### Client vs server SDKs All of the following conditions work on both client and server SDKs. Client SDKs handle several of these conditions automatically: if you don't provide a userID, client SDKs rely on an auto-generated stable identifier persisted to local storage. If you don't set an IP or User Agent (UA), the client SDK infers these attributes from the request. On mobile, the client SDK automatically passes your app version and locale to the server. Statsig can then evaluate conditions using these attributes without you setting them explicitly. ### Stability Evaluations at a given percentage are stable with respect to the unitID. For example, if the gate/config/experiment/layer has a unit type of "userID", and userID = 4 passes a condition at a 50% rollout, they always pass at that 50% rollout. The same applies for `customIDs`, if the unit type of the entity is that `customID`. Want to reset that stability? Refer to "Resalting" below. ### Resalting Gate evaluations are stable for a given gate, percentage rollout, and user ID. This stability is based on a salt associated with the feature gate. To reset a gate and reshuffle users, select "resalt" from the dropdown menu in the top right of the feature gate details page. ![Resalt UI](https://docs.statsig.com/images/conditions/resalt-ui.png) ### Partial rollouts A 0% rollout means "off for all users matching this rule" and a 100% rollout means "on for all users matching this rule." Each rule lets you specify a percentage of qualifying users who pass (and see the new feature). Specifying a number between 0% and 100% creates a random allocation of users in Pass/Fail or test/control groups for a simple A/B test. Use this to validate that a new feature doesn't regress existing metrics as you roll it out. Statsig recommends a 2% → 10% → 50% → 100% rollout strategy. Each progressive rollout generates its own Pulse Results, as shown below. ![Metric Lifts](https://docs.statsig.com/images/conditions/metric-lifts.png) ### User object fields Evaluation uses the set of properties defined in the [StatsigUser object](https://docs.statsig.com/sdks/user). There are a set of reserved top-level fields, but Statsig also reserves and recognizes these keywords in the `custom` and `privateAttributes` maps. For example, if you set `user.country`, `user.custom.country`, or `user.privateAttributes.country`, Statsig uses that value to evaluate a country condition (checked in that order: top level, then custom, then privateAttributes, case-insensitively). If `user.country` isn't defined but `user.custom.COUNTRY` is, Statsig uses `user.custom.COUNTRY` to evaluate the country condition. ## Supported conditions ### User ID Usage: Simple lists of User IDs to explicitly target or exclude from a gate. Supported Operators: `Any of, none of` Example usage: Add yourself (or a small group like your team) when you start building a new feature. Or exclude your designer until the feature is ready for review. ![User ID condition example](https://docs.statsig.com/images/conditions/user-id-condition-example.png) ### Email Usage: Target based on the email of the user Supported Operators: `any of, none of, contains any of, contains none of` Example: Show new feature to people in the Statsig company with an authenticated @statsig.com email address ![Email condition example](https://docs.statsig.com/images/conditions/email-condition-example.png) ### Everyone Usage: Percentage rollout on the remaining users that reach this condition. This condition represents everyone else: other rules or conditions may appear above it, but this condition sets what percentage of the remaining users pass. Supported Operators: `None. Percentage based only.` Example usage: 50/50 rollout to A/B test a new feature. Or 0% to hide the feature for all people not matching a set of rules. Or 100% to show the feature to the remaining users who did not meet a condition above. ![Everyone 50/50 condition example](https://docs.statsig.com/images/conditions/everyone-5050-condition-example.png) ### App Version Usage: Users on a particular version of your app/website pass. Particularly useful for mobile app development, where a feature may not be fully ready (or may be broken) in a particular app version. Supported Operators: `>=, >, <, <=, any of, none of` Example: Turn off a feature for all users on app versions 3.0.0 through 3.1.0 as it was broken. ![Disable broken versions example](https://docs.statsig.com/images/conditions/disable-broken-versions-example.png) ### Browser Version Usage: A particular version of a browser, parsed from the user agent. Should likely be combined with the browser name condition. Supported Operators: `>=, >, <, <=, any of, none of` Example: Turn off a feature for old versions of chrome which don't support a certain API ![Browser Name and Version Example](https://docs.statsig.com/images/conditions/browser-name-version-example.png) ### Browser Name Usage: A particular browser, parsed from the user agent: ('Chrome', 'Chrome Mobile', 'Edge', 'Edge Mobile', 'IE', 'IE Mobile', 'Opera', 'Opera Mobile', 'Firefox', 'Firefox Mobile', 'Mobile Safari', 'Safari'). Often combined with the Browser Version condition. Supported Operators: `>=, >, <, <=, any of, none of` Example: Turn off a feature for old versions of chrome which don't support a certain API To test: The Browser Name is inferred from the `userAgent`, but if you need to set it explicitly, you can set `browserName` in the user object. ![Browser Name and Version Example](https://docs.statsig.com/images/conditions/browser-name-version-example.png) ### OS Version Usage: A particular os version the user is on, parsed from the user agent. Should likely be combined with the Operating System condition. Supported Operators: `>=, >, <, <=, any of, none of` Example: Turn off a feature for versions of macOS which don't support a certain API ![OS name and version example](https://docs.statsig.com/images/conditions/os-name-version-example.png) ### Operating System Usage: A particular operating system, parsed from the user agent: ('Android', 'iOS', 'Linux', 'Mac OS X', 'Windows'). Often combined with the OS Version condition. Supported Operators: `any of, none of` Example: Turn off a feature for versions of macOS which don't support a certain API To test: The OS is inferred from the `userAgent`, but if you need to set it explicitly, you can set `deviceOS` in the user object. ![OS name and version example](https://docs.statsig.com/images/conditions/os-name-version-example.png) ### Device Model Usage: The device model of the mobile device the user is on. Supported Operators: `any of, none of, is null, is not null, contains any of, contains none of, regex` Example: Turn off a feature for older device models that your app doesn't support. To test: The Device Model is automatically inferred by the SDK, but if you need to set it explicitly, you can set `deviceModel` in the user object. ![Device Model Example](https://docs.statsig.com/images/conditions/device-model-example.png) ### Country Usage: A 2 letter country code, either passed as the user's country or determined by the IP address. Supported Operators: `any of, none of` Example: Show a cookie consent banner for users accessing your service from the EU. ![Country example](https://docs.statsig.com/images/conditions/country-example.png) ### IP address Usage: An IP address string Supported Operators: `any of, none of` Example: Show a different about us page on www.statsig.com to people in a certain IP address range ![Matching IP Addresses example](https://docs.statsig.com/images/conditions/matching-ip-addresses-example.png) ### Passes Target gate Usage: The condition passes if the referenced gate passes for the given user Supported Operators: `gate_id` Example: Only show feature X to people who also see feature Y: Only show a toggle to turn off ranking to people who also pass the new ranking algorithm gate. ![Passes Target Gate](https://docs.statsig.com/images/conditions/passes-target-gate.png) ### Fails Target gate Usage: Inverse of passes target gate: the condition passes if the referenced gate returns false for the given user Supported Operators: `gate_id` Example: Only show a new UI element to people who are not using the redesigned UI. ![Fails Target Gate](https://docs.statsig.com/images/conditions/fails-target-gate.png) ### User in Segment Usage: The condition passes if the user passes the rules defining the referenced segment. Refer to the [segments guide](https://docs.statsig.com/guides/using-environments) for more information on segments. Supported Operators: `segment_id` Example: Only show a new UI element to people who are not using the redesigned UI. ![In Segment](https://docs.statsig.com/images/conditions/in-segment.png) ### User not in Segment Usage: The condition passes if the user fails the rules defining the referenced segment. Refer to the [segments guide](https://docs.statsig.com/guides/using-environments) for more information on segments. Supported Operators: `segment_id` Example: Only show a feature to people who are not in the premium/paid tier. ![Not In Segment](https://docs.statsig.com/images/conditions/not-in-segment.png) ### Environment Tier Usage: The condition passes if the evaluation is happening in the given environment tier (development/staging/production). Refer to the [environments guide](https://docs.statsig.com/guides/using-environments) for more information on environments. Supported Operators: `development/staging/production/(other)` Example: Only show a feature on development builds ![Development Environment Condition](https://docs.statsig.com/images/conditions/development-environment-condition.png) ### Custom Field Usage: Specify the key in the custom object to fetch the value used on the left-hand side of a comparison. Supported Operators: - string: `any of, none of, contains any of, contains none of` - number: `any of, none of, less than, greater than` - version: `any of, none of, less than, greater than, less than or equal to, greater than or equal to` - date: `before, after` Example: Only show a feature to users who have turned on dark mode, as marked by the custom object having "darkmode": true. ![Custom Field](https://docs.statsig.com/images/conditions/custom-field.png) ### Unit ID Usage: Select custom ids to explicitly target or exclude from a gate. Supported Operators: `any of, none of, is null, is not null, contains any of, contains none of, regex` Example: Add yourself (or a small group like your team) when you start building a new feature. ![Unit ID example](https://docs.statsig.com/images/conditions/unit-id-example.png) ### Time Usage: Evaluate a gate relative to the current time Supported Operators: `after time, before time` Value: time (Console displays and accepts this in your browser's local time, then converts it to a unix timestamp for evaluation) Example: Show the labor day sale banner on labor day ![Time condition](https://docs.statsig.com/images/conditions/time-condition.png) ### Private attributes Usage: Any user field or custom field condition can be used through a private attribute. To target an email without logging it, create an email condition and put `"email": "xyz@email.com"` in the `privateAttributes` dictionary. For custom fields, create a custom field condition and put the key/value pair in `privateAttributes` instead. Statsig uses `privateAttributes` for evaluation only and doesn't store or include them in log events. Supported Operators: dependent on the condition Example: Only show a feature to 20 somethings, as marked by the privateAttributes object having "age": "20-29". ![Private attributes](https://docs.statsig.com/images/conditions/private-attributes.png) ## FAQs #### Could users switch between control (fail) and test (pass) groups? After Statsig exposes a user, it includes them in the analysis going forward. They saw the new feature, and it affected them. If you modify the feature gate rules, or the user's attributes change so that the user no longer qualifies, they stop receiving the new feature. However, Statsig continues to count them for analysis. After you roll out the feature, all users see the new feature; if you turn off the feature gate, all users see the control (feature disabled). In either case, Statsig performs no further analysis. #### How do overrides work? Are users included in overrides also included in the analysis? When you add user IDs in the **Pass** or **Fail** lists of your feature gate, these users see the appropriate treatment but Statsig doesn't include them in the analysis. ================================================================================ # Feature Gate overrides URL: https://docs.statsig.com/feature-flags/overrides ================================================================================ # Feature Gate overrides ## Override results of a feature gate Overrides force specific user IDs to pass or fail a feature gate, regardless of the rules you configure. Use them during development to state explicitly which users see a feature. Overrides use user IDs, and you can set them to pass or fail for a given user ID. When Statsig evaluates a gate, if the user ID has an override, Statsig returns the overridden result immediately before evaluating any rules. ### Adding an override - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate where you want to add an Override - Click the **Add Override** button ![Feature gate page with Add Override button highlighted](https://docs.statsig.com/images/feature-flags/overrides/148461864-4a5efd47-2e40-478f-81e5-49edfc5ea2e9.png) - Select either 'Pass List' or 'Fail List' from the tabs in the dialog ![Manage overrides dialog showing pass and fail lists](https://docs.statsig.com/images/feature-flags/overrides/148462020-417c007f-d492-46f7-8d25-d7a5178b4fe2.png) - For users you want to pass the gate, add them to the 'Pass List' - For users you want to fail the gate, add them to the 'Fail List' > **Info:** > > A user can only exist on one of these lists at a time. - After you've added the user IDs, select **Save** ### Deleting an override If you add an override but later decide you don't need it, you can remove it so Statsig evaluates the rules normally. - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate where you want to add an Override - Click the **Edit Overrides** button ![Edit overrides button within feature gate settings](https://docs.statsig.com/images/feature-flags/overrides/148469394-9f86db83-26f6-4a5b-809f-8a53f0b4f1fa.png) - Select the trashcan icon next to the user ID you want to remove from a list. ![Override list with trash icon to remove user ID](https://docs.statsig.com/images/feature-flags/overrides/148463292-6740a09f-337f-441a-9cfa-a547a5dc6183.png) - After you've updated the lists, select **Save** ### Testing an override After you add your override, you can test it in the **Test Gate** window by adding `userID` as a property of the user object. ![Test gate console showing user object with override result](https://docs.statsig.com/images/feature-flags/overrides/148462648-e7da94bb-a681-4b0a-ad53-1254c6abe623.png) Users that pass see "PASS (User ID Override)" ![Test gate output indicating PASS due to user ID override](https://docs.statsig.com/images/feature-flags/overrides/148462641-57b544c1-bbdb-48cf-bb7f-967b0b20fc63.png) Users that fail see "FAIL (User ID Override)" ![Test gate output indicating FAIL due to user ID override](https://docs.statsig.com/images/feature-flags/overrides/148462634-de69b838-f7b1-431c-9119-64ce123ad218.png) ================================================================================ # Test your Feature Gate URL: https://docs.statsig.com/feature-flags/test-gate ================================================================================ # Test your Feature Gate There are three ways to test your feature gate and validate that it's working as expected with the rules you have created: 1. Using the built-in **Test Gate** tool in the Statsig console 2. Using the prototype Javascript **Test App** available in the Statsig console 3. Using the **Diagnostics** tab in the Statsig console ## Option 1: Use the Test Gate tool To validate your feature gate using the built-in Test Gate tool: - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate that you want to validate - At the bottom of the page, the **Test Gate** window lists all properties available in the rules you have created, as shown below: ![Test Gate interface showing property fields](https://docs.statsig.com/images/feature-flags/test-gate/129104501-9e7349ae-31fe-47ea-97da-0520fd3d7e1b.png) - Click in the window and edit the value of the Email property to include the users you want to target. For example, type jdoe@example.com as shown below. When the email domain matches "@example.com", the feature gate check succeeds and the window shows PASS. Otherwise, the gate fails and the window shows FAIL. ![Test Gate showing PASS result for email validation](https://docs.statsig.com/images/feature-flags/test-gate/129104434-0f09087d-80da-4a62-84ac-c51e607e72a1.png) ## Option 2: Use the Statsig Test App To validate your feature gate using the Test App: - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate that you want to validate - At the bottom of the page, select **Check Gate in Test App** at the top right of the Test Gate window (shown by the red arrow). This opens a new browser window with a prototype JavaScript client that initializes and calls the Statsig `checkGate` API. ![Check Gate in Test App button location](https://docs.statsig.com/images/feature-flags/test-gate/138148684-581bb8d5-86ba-4aef-b24d-44e540fa91f1.png) ## Option 3: Use the Diagnostics tab To validate your feature gate using a live log stream: - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate that you want to validate - Click on the **Diagnostics** tab (next to the Setup tab) - Scroll down to the **Exposure Stream** panel, where you can see a live stream of gate check events as they happen: ![Exposure Stream panel showing live gate check events](https://docs.statsig.com/images/feature-flags/test-gate/138149819-5082d7e5-f7ee-42e8-b1ac-f57d9732e68f.png) - In the **Event Count by Group** panel, you can also validate that your application records events as expected for users you expose to the new feature (or not). If you have started recording a new event type to test a new feature's impact, validate that these events appear as you expose more users to the feature. ![Event Count by Group panel showing feature exposure metrics](https://docs.statsig.com/images/feature-flags/test-gate/141017409-f750c1c6-4c54-4140-bc4d-a3b83f1568fc.png) ================================================================================ # Viewing Feature Gate exposures URL: https://docs.statsig.com/feature-flags/view-exposures ================================================================================ # Viewing Feature Gate exposures > **Info:** > > By default, Statsig doesn't record exposure analytics for gate rules set to 0% or 100% rollout. To record them: > > 1. A project admin goes to _Settings > Project Configuration > Feature Management_ and turns on **Enable exposure tracking for 0/100% rolled out Gates**. > 2. On each gate that needs these exposures, turn on **Store 0/100 Exposures**. > > Statsig bills these exposures as analytic events. For Warehouse Native forwarding requirements, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). The gate settings above don't enable forwarding for experiment groups at 0% or 100%. If you need those experiment exposures, contact Statsig Support. ## Gate exposures To see the number of users exposed to a feature gate: - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Feature Gates** - Select the feature gate that you want to test - Click on the **Pulse Results** tab - The **Cumulative Exposures** panel shows total exposures of a feature gate, broken down into three groups: 1. Units that passed the feature gate and that Statsig used for analysis. 2. Units that didn't pass the feature gate and that Statsig used for analysis vs. the "Pass" group. 3. Units that didn't pass the feature gate and that Statsig did not use for analysis vs. the "Pass" group. ![Feature gate cumulative exposures view](https://docs.statsig.com/images/feature-flags/view-exposures/9b115b7b-026c-4364-aac9-24a2e0007b5d.png) ## Balanced gates Statsig balances gates and holdouts by default in Cloud, and as an opt-in option for Warehouse Native holdouts (on the Setup page). Balancing reduces false positives at the cost of some sample size. Balanced analysis is a best practice. Go to section 7 of [AB Testing Intuition Busters](https://drive.google.com/file/d/1oK2HpKKXeQLX6gQeQpfEaCGZtNr2kR76/view) for more discussion. Statsig achieves this sampling during analysis by downsampling the larger arm proportionally to match the smaller group. For example, Statsig applies a `(100 - large_group_pct)/(large_group_pct)` sampling rate to the larger group using an unbiased hashing approach, keeping the user pool consistent. Statsig rotates the hash salt across different gates and holdouts. ## Metric lifts The **Metrics Lifts** panel shows how your feature is performing based on lifts in any business metrics added to the list of **Monitoring Metrics** for your gate. Statsig uses an equal variant comparison (for example, 10% vs 10%) for calculating metric lifts for gate rollouts. Read more about the advantages of this methodology in ["A/B Testing Intuition Busters: Common Misunderstandings in Online Controlled Experiments"](https://www.researchgate.net/publication/361226478_AB_Testing_Intuition_Busters_Common_Misunderstandings_in_Online_Controlled_Experiments) by Ron Kohavi, Alex Deng, & Lukas Vermeer. In the example below, the rises in _product view count_ and _purchase event count_ are statistically significant. These rises suggest the feature positively impacts the number of product views but may negatively impact conversions to purchases. ![Metric lifts showing feature performance](https://docs.statsig.com/images/feature-flags/view-exposures/01207199-5a5a-4505-a0af-7e6354b4590d.png) ## Bots & filtering > **Info:** > > Statsig moved information on Bots & Filtering to its [own page](https://docs.statsig.com/experiments/monitoring/bots) ================================================================================ # Pre-Post Results URL: https://docs.statsig.com/feature-flags/pre-post-results ================================================================================ # Pre-Post Results Pre-Post Results is an analysis mode for Feature Gates that estimates a feature's impact when you can't run a traditional A/B test. It compares your key metrics in the period before a rollout against the period after, so you can gauge the directional impact of a feature you shipped to everyone at once. Use Pre-Post Results when you roll a gate straight from 0% to 100% and have no control group to compare against. > **Info:** > > **Cloud only feature** Statsig offers this feature only on Statsig Cloud. As Statsig works on a WHN solution, contact Statsig if you're interested in being an early customer. ## How Pre-Post Results work in Statsig By comparing key metrics before and after you roll out a feature gate from 0% to 100% of users, you can identify the directional impact of your features in production. ![Pre-Post Results Interface](https://docs.statsig.com/images/pre-post-results.png) Pre-Post is particularly valuable for: - **Emergency rollouts**: Features that need to ship immediately without time for a slow rollout - **Infrastructure changes**: Backend improvements or technical features that affect all units/pods/users and that you can't partially roll out - **Retroactive analysis**: Understanding the rough impact of features you already rolled out without experiments - **Regulatory or ethical features**: Changes you can't withhold from a control group ## Pre-Post Results aren't experiments Pre-Post analysis measures the change in a metric around a specific point in time, among a specific set of exposed units. It doesn't meet the requirements of a proper A/B test or feature gate partial rollout. Think of Pre-Post analyses as snapshot measurements around the time you launched your feature. Because many other factors can occur at the same time, there's no guarantee that your results are due to your feature launch. Correlation doesn't equal causation. Experiments remain the standard for measuring feature impact. Run launches as an Experiment or partial Feature Gate rollout when accuracy, validity, and extensibility are important. ## When does Statsig calculate Pre-Post Results? Statsig calculates Pre-Post Results for targeting rules that meet specific rollout conditions: 1. The targeting rule started at 100% pass rate, or you rolled it out from 0% to 100% in a single step 2. The rollout happened in the last 30 days When you select a qualifying rule in the Metrics Impact tab, Statsig automatically switches to Pre-Post Results mode and displays a banner indicating you're viewing Pre-Post analysis. ## How Pre-Post Results calculates feature impact Pre-Post Results uses the following approach to estimate feature impact: 1. **Identify the participating units**: Find all users you exposed to the feature after the 100% rollout 2. **Collect pre/post-rollout data**: Gather metric values for these users from the periods before and after the rule change 3. **Bucket metric data into discrete periods**: Statsig automatically groups metric data into buckets of a consistent duration. 4. **Calculate the difference**: Compute the mean metric values for both pre and post periods, treating each bucket as a unique observation, then calculate the delta (difference) between them This method ensures Statsig compares the same users before and after the feature rollout. ## Supported metric types | Metric type | Supported | | --- | --- | | Event Count | ✅ Yes | | Event Count Custom | ✅ Yes | | Event User | ✅ Yes | | Sum | ✅ Yes | | Mean | ✅ Yes | | Funnel | ❌ No | | Ratio | ❌ No | | Participation Rate | ❌ No | ## Best practices When using Pre-Post Results, follow these guidelines: - Focus on metrics that are directly related to your feature's intended impact and have sufficient volume. The more directly a metric responds to the feature launch, the easier it is to detect a sudden change. - Correlation doesn't equal causation. Consider other changes, seasonal effects, or external events that might influence your metrics during the analysis period. - Use Pre-Post Results as one data point alongside qualitative feedback, user research, and business context to make informed decisions. - If you can partially roll out a feature to less than 100% of users, do so. A partial rollout lets you measure the metric impact for users who see the feature against users who don't. That comparison establishes true causation. ## Known limitations - **30-day window**: Statsig supports only rollouts from the last 30 days - **No control group**: Results show correlation, not definitive causation - **External factors**: Other changes during the analysis period can influence results - **Metric type restrictions**: Statsig doesn't yet support some advanced metric types. ================================================================================ # Measuring multiple rollout stages URL: https://docs.statsig.com/feature-flags/multiple-rollout-stages ================================================================================ # Measuring multiple rollout stages ## Continuous analysis For gate rules that roll out with a pass percentage ≤ 50% and without any rollback, Statsig consolidates data collected at earlier and later stages of the rollout into one analysis. Consolidating this data produces a more complete analysis. Valid continuous analysis rollouts include: 10% → 20% 10% → 20% → 50% Invalid continuous analysis rollouts include: 10% → 5% (rollback) 10% → 70% (exceeds 50%) When a rollout is no longer valid for continuous analysis, Statsig analyzes the new rollout step separately from previous steps. ## Compatibility with other gate features ### Balanced gates Statsig also [balances](https://docs.statsig.com/feature-flags/view-exposures#balanced-gates) gate rules that have multiple rollout stages using downsampling. In cases where pass percentage ≤ 50%, Statsig uses the same hashing as the pass/fail and takes an equal percentage of the other group. When pass percentage > 50%, Statsig uses an orthogonal random hashing to sample the larger group at a rate of $\frac{1-p}{p}$ where p is the fraction of users in the larger group. For a gradual rollout, this sampling prevents bias based on enrollment time period. ### CUPED/CURE You can use CUPED/CURE only when there have been no rollbacks and when the rollout percentage hasn't exceeded 50% within a gate rule. Analysis is no longer continuous after a rollback or after the rollout exceeds 50%, because earlier treatments bias the pre-exposure data of a given unit. ================================================================================ # Scheduled Rollouts URL: https://docs.statsig.com/feature-flags/scheduled-rollouts ================================================================================ # Scheduled Rollouts Scheduled Rollouts add a time-based scheduling layer to Feature Gates. You pre-set a rollout schedule, and Statsig runs each phase automatically at the times you choose. This helps when a feature launch happens in another timezone or when your team follows a standard ramp-up schedule for every release. Scheduled rollouts apply at the Feature Gate rule level for maximum flexibility. Not all rules in your Gate need to include a scheduled rollout. Set it up only for the rules that need it. ## Set up a Scheduled Rollout To set up a Scheduled Rollout on a rule in your Feature Gate, tap the "…" in the upper right-hand corner of the rule you want to schedule a rollout for. ![Feature Gate rule menu options](https://docs.statsig.com/images/feature-flags/scheduled-rollouts/199850775-42528d6c-b8f1-4e5d-9774-bc1b576c2916.png) Select **Edit Rule or Rollout**, and then select **Schedule Automated Rollout**. ![Schedule Automated Rollout selection](https://docs.statsig.com/images/feature-flags/scheduled-rollouts/199851487-2e2aba51-30d5-4fef-933f-b31c0e78dd57.png) From here, configure each phase of your Scheduled Rollout. The upper right-hand corner shows your current pass percentage. This value reflects the baseline pass percentage you entered for your rule, and you can change it using **Edit Rule**. To add phases to your rollout, select **Add Phase** and configure as many phases as you need. Each scheduled rollout phase includes: - Rollout date - Rollout time\* - Pass percentage > **Note:** > > You can set rollout times in 15 minute increments. Additionally, each configured phase represents a discrete increase to the next rollout percentage, not a gradual rollout amortized over the entire phase. ![Scheduled rollout configuration interface](https://docs.statsig.com/images/feature-flags/scheduled-rollouts/199851781-60606e6b-d653-408a-a3ba-399e32d582b0.png) As you build your Scheduled Rollout, a preview of the phases appears below the configuration wizard. Viewers of your Feature Gate can also see this preview when they hover over a rule. ![Scheduled rollout phases preview](https://docs.statsig.com/images/feature-flags/scheduled-rollouts/199851974-c95ea9d2-6d04-4c3e-b9e5-f5d5ea3d85b3.png) ![Rollout phases hover preview](https://docs.statsig.com/images/feature-flags/scheduled-rollouts/199851640-007d63d5-7b9e-4002-93af-132af24416a1.png) ## Execute a Scheduled Rollout After configuration, each phase of a Scheduled Rollout executes automatically on the specified schedule. Statsig sends Scheduled Rollout notifications to the Feature Gate creator, any editors, and anyone following the Feature Gate. Statsig sends notifications through: - Email - Console - (Optional) Slack: to configure Slack notifications, go to _Account Settings > Notifications_. ================================================================================ # Safeguards URL: https://docs.statsig.com/feature-flags/safeguards-overview ================================================================================ # Safeguards Safeguards continuously monitor critical metrics and automatically intervene in your Feature Gate rollouts when your metrics exceed risk thresholds. This automatic monitoring ensures faster recovery from issues, eliminates the need for constant manual checks, and protects your users from unintended impact. > **Info:** > > Statsig offers Safeguards on the Pro and Enterprise billing tiers. ## When to use Safeguards Use Safeguards when you want to: - Limit the impact of a feature on critical business or performance metrics - Automate rollout progression to more users based on how your metrics are performing - Maintain system stability by automatically responding to API errors, latency spikes, or infrastructure issues ## How Safeguards work Safeguards listen to alert types that you have created in your project, such as Rollout Alerts and Topline Alerts. When any alert fires due to metric regressions, Safeguards automatically pause your rollout, roll it back, or finish a rollout based on your settings. **Pre-requisite:** You must create at least one Rollout Alert or Topline Alert before configuring a Safeguard on a Feature Gate. Go to the [Alerts](https://docs.statsig.com/product-analytics/alerts-overview) documentation for setup instructions. ## Two types of safeguards A Safeguard can use two types of alerts to take an action on your Feature Gate: | Alert type | Definition | Use case | | --- | --- | --- | | Rollout Alert | Monitors the regression of metric delta between users who pass and fail your Feature Gate | Use when you want to ensure your Feature Gate isn't causing negative drift for users receiving the new flag variation. Works only on partially rolled out rules (pass rate between 0% and 100%). | | Topline Alert | Monitors absolute metric values regardless of Feature Gate assignment | Use when you want to take action on your Feature Gate when system metrics breach thresholds, regardless of confirming causation. Works on fully rolled out (0% or 100%) and partially rolled out rules. | ## Get started with Safeguards Follow these tutorials to start using Safeguards: - [Create a new Safeguard](https://docs.statsig.com/feature-flags/safeguards-create) - [Manage an existing Safeguard](https://docs.statsig.com/feature-flags/safeguards-manage) ================================================================================ # Create a Safeguard URL: https://docs.statsig.com/feature-flags/safeguards-create ================================================================================ # Create a Safeguard A Safeguard monitors a Feature Gate's targeting rule for regressions and automatically takes an action, such as rolling back to 0%, when an alert fires. To create one on a rule, follow these steps: 1. Go to a Feature Gate's **Setup** tab 2. Pick a targeting rule for which you want to monitor regressions 3. Click the three-dot (...) menu and choose **'Safeguard Rule'** ![Create Safeguard on a rule](https://docs.statsig.com/images/safeguards/create-safeguard.png) 4. Choose the action to take when alerts fire: - **Rollback to 0%**: Assigns default value to all users. - **Roll out to 100%**: Assigns Pass value to all users. - **Pause Rollout**: Stops scheduled rollout progression (only available with an active Scheduled Rollout policy). ![Select an action](https://docs.statsig.com/images/safeguards/choose-safeguard-action.png) 5. (Optional) Set how long to monitor alerts for safeguarding the rule: | Alert type | Evaluation period | Evaluation start time | | --- | --- | --- | | Topline alert | Choose your own | Starts when you create the safeguard | | Rollout alert | Fixed (90 days) | Starts whenever targeting rule's pass % changes | ![Set evaluation period](https://docs.statsig.com/images/safeguards/evaluation-period.png) > **Tip:** > > **Recommended:** Monitor topline alerts for crashes, errors, latency, and similar issues _for a few days_ after a Feature Gate rollout to confirm stability. A 14-day evaluation period is a good starting point. 6. Select one or more alerts to monitor: - Rollout alerts - For feature-specific regression detection - Topline alerts - For system-wide health monitoring ![Add alerts for your Safeguard](https://docs.statsig.com/images/safeguards/add-alerts.png) 7. Click **Save** ================================================================================ # Manage a Safeguard URL: https://docs.statsig.com/feature-flags/safeguards-manage ================================================================================ # Manage a Safeguard ## View a Safeguard To view an existing Safeguard, tap the blue pill on your Feature Gate's targeting rule. You can see how you defined your Safeguard and make changes. You can add or remove alerts, change the action, or adjust the evaluation period. ![View an existing Safeguard](https://docs.statsig.com/images/safeguards/view-safeguard.png) ## When a Safeguard triggers When an alert triggers a safeguard: - The configured action executes automatically (rollback/pause/complete). - A banner appears on the targeting rule with the action taken, timestamp, and diagnostic link. - Statsig blocks further rule modifications until you resolve the alert. - Statsig sends notifications according to your alert configuration. ![Safeguard is triggered on a rule](https://docs.statsig.com/images/safeguards/safeguard-rule-banner.png) ================================================================================ # Managing Feature Gate lifecycles URL: https://docs.statsig.com/feature-flags/feature-flags-lifecycle ================================================================================ # Managing Feature Gate lifecycles A feature can go through different phases throughout its lifecycle. A few users may test it, you may have recently rolled it out to everyone, or it may be stable enough that you no longer need the toggle. A feature gate should clearly reflect the phase the feature is in, for a few important reasons: - **Prevent incidents**: Avoid scenarios where old code for a deprecated feature is accidentally touched or repurposed. These incidents have had real business consequences, as in [how Knight Capital lost half a billion dollars](https://www.statsig.com/blog/lose-half-a-billion-dollars-with-bad-feature-flags-knight-capital). - **Maintain a healthy codebase**: Dead references to flags increase the volume of code your team navigates daily and can slow down new developer onboarding. - **Reduce mental load**: The feature gate catalog shows the status of every feature, so you can quickly see what next steps are needed (for example, launch or end a feature) without tracking everything manually. ## Managing feature gate lifecycles Statsig makes it easy for your feature gates to reflect the phase your feature is in by using status. A gate can be in one of four statuses: ![A feature gate starts In Progress while it's being tested or rolled out. From there it becomes either Launched, once it's rolled out to everyone, or Disabled, once it's rolled back from everyone. After you remove the gate reference from your codebase, the gate becomes Archived.](https://docs.statsig.com/images/diagrams/feature-gate-statuses.svg) ![A feature gate starts In Progress while it's being tested or rolled out. From there it becomes either Launched, once it's rolled out to everyone, or Disabled, once it's rolled back from everyone. After you remove the gate reference from your codebase, the gate becomes Archived.](https://docs.statsig.com/images/diagrams/feature-gate-statuses.dark.svg) | Status | What it represents | Implication | | --- | --- | --- | | In Progress | You're rolling out and testing this feature. | Default status when you create a gate. | | Launched | You've rolled out this feature to everyone. | The gate always returns **TRUE** and stops generating billable exposure events, so you stop incurring costs. The gate reference is likely safe to clean up from the codebase. | | Disabled | You've rolled back this feature from everyone. | The gate always returns **FALSE** and stops generating billable exposure events, so you stop incurring costs. The gate reference is likely safe to clean up from the codebase. | | Archived | Your code no longer references or checks this feature; Statsig preserves the gate's history. | The gate has received 0 checks for the last 7 days and receives no more checks. | ## When to update feature gate lifecycles There are 3 points throughout the gate's lifecycle when you should take action, either in the console or in your codebase: ![The same status flow, marked with the three points where you take action. At point 1 you launch or disable an In Progress gate. At point 2 you remove the gate reference from your codebase. At point 3 the gate becomes Archived.](https://docs.statsig.com/images/diagrams/feature-gate-lifecycle.svg) ![The same status flow, marked with the three points where you take action. At point 1 you launch or disable an In Progress gate. At point 2 you remove the gate reference from your codebase. At point 3 the gate becomes Archived.](https://docs.statsig.com/images/diagrams/feature-gate-lifecycle.dark.svg) **1) You've fully rolled out or rolled back the gate, and you're ready to skip rule evaluation and assign a default value** - Go to the feature gate page and click the "..." menu in the upper right corner to select **Launch** or **Disable**: - **In Progress → Launch**: when you've rolled out the gate to 100% for a period of time (recommended: more than 30 days) and you're comfortable with the gate always returning TRUE. - **In Progress → Disable**: when you've rolled back the gate to 0% for a period of time (recommended: more than 30 days) and you're comfortable with the gate always returning FALSE. - To find all gates that are good candidates to be **Launched** or **Disabled** (rolled out to 100% or rolled back to 0% more than 30 days ago): - Go to Feature Gates catalog - Click on filter icon: - Status = In Progress - Pass Rate = 100% AND 0% - In the search bar: "Modified: ` **Note:** > > Confirm that no active Holdouts include these gates before removing reference. - To find all gates that are good candidates to remove from your codebase (Launched or Disabled more than 60 days ago): - Go to Feature Gates catalog - Click on filter icon: Status = **Launched** AND **Disabled** - In search bar: "Modified: ` **Info:** > > Statsig only enforces schemas when editing dynamic configs through the console or API, and doesn't use them at code runtime. For example, if you have a dynamic config that returns settings for a site banner, you might have a schema of: ```plaintext { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", "properties": { "title": { "type": "string", }, "description": { "type": "string", }, "cta": { "type": "string", } }, "required": ["title", "description", "cta"], } ``` Now, each of your rules must return an object including title, description, and CTA. ## Infer schema from current values You can also infer schema based on the current values in your targeting rule variations. Inferring schema is useful as a quick starting point for validations or for documenting the expected shape of your config. ![Infer schema from current values](https://docs.statsig.com/images/infer-schema.png) _JSON5 output_ Statsig emits the inferred schema in JSON5 (a superset of JSON). JSON5 allows unquoted object keys and trailing commas. These features may cause failures in other standard JSON Schema validators and typical unit-test tooling. Statsig accepts JSON5 in the console and API, but convert the output to strict JSON if you need to use it with validators or tests. ================================================================================ # Create a dynamic config URL: https://docs.statsig.com/dynamic-config/create-new ================================================================================ # Create a dynamic config A dynamic config defines JSON values your application reads from Statsig instead of hard-coding them. To create a dynamic config, - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Dynamic Configs** - Click the **Create New** button - Enter a name and description, and click **Create** ![Dynamic config creation interface](https://docs.statsig.com/images/dynamic-config/create-new/f44b281f-be49-46ce-b60d-e68a647274ab.png) ================================================================================ # Adding Rules URL: https://docs.statsig.com/dynamic-config/add-rule ================================================================================ # Adding Rules ## Add a rule to a dynamic config Targeting rules control which users receive a specific configuration from a dynamic config. To add new user targeting rules to a dynamic config, - Log into the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Dynamic Configs** - Select the dynamic config where you want to add a rule - Click the **Add Targeting** button - Click the **Add New Rule** button - Select the criteria for identifying the users you want to target: - You can target users based on common attributes such as their operating system as shown below. ![Operating system targeting rule configuration](https://docs.statsig.com/images/dynamic-config/add-rule/129112226-51978083-d007-4697-88b5-f3a080eabf48.png) - You can target users in a defined [segment](https://docs.statsig.com/segments/overview) as shown below. ![User segment targeting rule configuration](https://docs.statsig.com/images/dynamic-config/add-rule/129112427-27351aaf-074e-4997-91d8-6e1e7941b991.png) - You can target users who are eligible for a specific feature gate. Targeting by feature gate ensures Statsig activates the dynamic config only for users exposed to the target feature gate. ![Feature gate targeting rule configuration](https://docs.statsig.com/images/dynamic-config/add-rule/129112612-d881981c-4fc6-4e95-a9c5-18319c02d6f2.png) - To complete the dynamic config, select the **Edit** link to open the JSON configuration editor. Type the configuration parameters and values that your application should receive, then select **Confirm**. ![JSON configuration editor interface](https://docs.statsig.com/images/dynamic-config/add-rule/129113189-30e7e7da-7559-4d3a-8bd3-74a6ccb7afe2.png) ================================================================================ # Scheduled Rollout URL: https://docs.statsig.com/dynamic-config/scheduled-rollout ================================================================================ # Scheduled Rollout Scheduled rollouts automatically change Dynamic Config values at configured dates and times. Use them to increase a rule’s rollout percentage over time or switch between variants during specific date ranges. Configure a schedule on a rule, then publish the rule so Statsig applies each phase automatically. Scheduled rollouts apply at the rule level and follow the rule's targeting conditions. Rollout percentages apply to users who match the rule. ## Rollout types Dynamic Configs support two rollout types, depending on how you want to change the values users receive: - **Gradual**: Increases the percentage of users matching the rule who receive its configured values in discrete scheduled steps. Use it to roll out values to more users over time. Gradual rollouts are unavailable for rules with multiple variants. - **Switch**: Serves a selected variant or the config's Default values to 100% of matching users during scheduled date ranges. Use it to schedule which values users receive during specific time periods. The Default split applies outside those ranges, and Switch requires at least one variant. ## Gradual rollout 1. Open your Dynamic Config. 2. Open the contextual menu of the rule you want to schedule. Select **Apply rollout**. ![Rule menu with the Apply rollout option highlighted](https://docs.statsig.com/images/dynamic-config/scheduled-rollout/dynamic-config-scheduled-rollout-menu.png) 3. Select **Gradual** from the **Rollout type** dropdown menu in the rollout modal. 4. Configure each scheduled phase with a rollout date, rollout time, and percentage of matching users who receive the rule's configured values. 5. Select **Add Phase** to add another scheduled change. 6. Review the schedule preview, then select **Save** to apply the schedule to your local rule draft. Each phase changes the percentage in a discrete step. The percentage stays at that level until the next scheduled phase; it doesn't increase continuously between phases. For example, start a rule at 10% and increase its percentage every seven days: ![Gradual rollout example showing three phases with 10%, 50%, and 100% rollout over time](https://docs.statsig.com/images/dynamic-config/scheduled-rollout/dynamic-config-scheduled-rollout-gradual-type.png) ## Switch rollout > **Info:** > > Switch rollout is in Early Access. Functionality may change, and this documentation may not always be up to date. Contact [Statsig Support](https://docs.statsig.com/support-options) to request access. Before configuring a Switch rollout, add at least one variant to your rule. 1. Open your Dynamic Config and click the menu of the rule you want to schedule. 2. Select **Apply rollout**. 3. Select **Switch** from the **Rollout type** dropdown menu. 4. For each date range, configure a start date and time, an optional end date and time, and the variant or **Default** values to serve at 100%. 5. Select **Add another range** to schedule additional changes. 6. Configure the **Default split** to define the percentage of users who receive each variant or Default outside scheduled ranges. 7. Review the schedule preview, then select **Save** to apply the schedule to your local rule draft. Default means the Dynamic Config's default values. The default split defines how Statsig distributes users across variants and Default when no scheduled range is active. Ranges can't overlap. Only the final range can omit an end time. ![Switch rollout example showing date ranges with different variants and a default split configuration](https://docs.statsig.com/images/dynamic-config/scheduled-rollout/dynamic-config-scheduled-rollout-switch-type.png) ## Publish your scheduled rollout Saving in the rollout editor updates your local rule draft. It doesn't publish the rule or activate the schedule. 1. After saving the rollout editor, return to the Dynamic Config page. 2. Submit the config changes. If your changes don't require review, select **Save** to publish the rule and its schedule. If your changes require review, select **Submit for Review**, then complete the review process and publish the approved changes. A pending review doesn't activate the schedule. Publish the rule and its schedule before scheduled changes can take effect. After you publish the rule, each scheduled phase or date range takes effect automatically at its configured time. ![Publishing interface showing the Save and Submit for Review options](https://docs.statsig.com/images/dynamic-config/scheduled-rollout/dynamic-config-scheduled-rollout-publish.png) ================================================================================ # Guided Tutorial URL: https://docs.statsig.com/guides/first-dynamic-config ================================================================================ # Guided Tutorial Dynamic Config stores configuration values, such as text, colors, or ranking parameters, that you update without shipping new code. It works for server-side rendered UI, rate limiting, ranking systems, algorithms, and more. This tutorial builds a flexible homepage banner and shows how to change what different users see directly from the Statsig console. > **Info:** > > This guide focuses on a client-side example, as it's easier to illustrate how Dynamic Configs work and how to use them. You can and still should use Dynamic Config on the server side as well. This guide builds a front-page banner, the kind that appears on an ecommerce site to advertise an upcoming sale. The example applies it to a stripped-down version of the Statsig homepage. The result looks like this green banner: ![UI for mac users](https://docs.statsig.com/images/guides/first-dynamic-config/b82e808a-99b5-4922-90f7-727d9e5d942a.png) > **Info:** > > **Codepen Example** > > Find this example in [a codepen](https://codepen.io/tore-statsig/pen/mdWEajo) where you can see the actual code, or fork it to quickly test your own Dynamic Configs. ### Step 1 - Create a new Dynamic Config Create a new Dynamic Config. Dynamic Configs live under the "Feature Management" tab in the Statsig Console. Choose a name related to the set of variables this config holds. For a homepage banner, name it "Banner Config": ![Create Dynamic Config](https://docs.statsig.com/images/guides/first-dynamic-config/c0564d86-a83c-45c7-a3c3-62397ae00448.png) The new Dynamic Config is empty. It returns the default value (an empty JSON object) when you evaluate it. The next steps add options to populate a homepage banner. The goal is to show a targeted banner to two groups of developers: those likely to use a .NET SDK, and those likely to use a Swift SDK. The targeting is simple: promote the .NET SDK to users browsing on Windows, and the Swift SDK to users browsing on macOS. ### Step 2 - Create targeting rule(s) and conditions First, add the Windows rule. Select "Add Targeting", and then "Add new Rule": ![Add Rule](https://docs.statsig.com/images/guides/first-dynamic-config/9011708a-24e0-43c9-8e4d-468d57476413.png) Feature Gates and Dynamic Config share the same user segmentation and targeting tools, but differ in what they return. Feature Gates are lightweight and return only a boolean indicating whether the user matched a rule. Dynamic Configs return a different JSON object for each rule. ### Step 3 - Update the return value for users matching each rule This is the rough schema to return: ```js { text, backgroundColor, color, fontSize, isCloseable, } ``` Edit the return value for the Windows rule. Under "Return" on the right-hand side, select "edit" and paste the following: ```js { text: 'New! Introducing the Statsig .NET SDK', backgroundColor: '#194b7d', color: 'white', fontSize: 14, isCloseable: false, } ``` ![Return Value](https://docs.statsig.com/images/guides/first-dynamic-config/a2dc7b2a-98f4-4570-86db-34b390d80a89.png) Select "Save" in the bottom right. ![Config with one rule](https://docs.statsig.com/images/guides/first-dynamic-config/b6e0eb73-c623-4a05-b605-ad9eb2c42792.png) Repeat this process for users on macOS. Add the same OS rule, but this time select "Mac OS X". Then update the return value: ```js { text: 'New! Introducing the Statsig Swift SDK', backgroundColor: '#197d4b', color: 'white', fontSize: 16, } ``` Click "Save" to apply these rules to your config. The Dynamic Config should now look like this: ![Dynamic Config with two rules](https://docs.statsig.com/images/guides/first-dynamic-config/a04575a8-6afb-4380-8cb6-77052a2d5943.png) ### Step 4 - Call getDynamicConfig in your app This is a specific guide for creating a Dynamic Config using the Statsig JavaScript SDK. For other SDKs, go to the Statsig SDK [quickstart guides](https://docs.statsig.com/sdks/quickstart) and select the SDK you're using. You can also find the code snippet for a particular dynamic config by selecting the code snippet button on the dynamic config page and choosing the target SDK. ![dynamic config code snippet button](https://docs.statsig.com/images/guides/first-dynamic-config/8211d6ea-db5f-448b-9589-e112de3ac4b2.png) Use this Dynamic Config to create a different landing page experience for different groups of developers. Follow along with this [codepen](https://codepen.io/tore-statsig/pen/mdWEajo). If you fork the code and add the API Key from your Statsig project, you can see the banner for your platform. After adding the SDK to the webpage using the [jsdelivr cdn](https://www.jsdelivr.com/package/npm/@statsig/js-client), initialize the SDK: ```js const client = new window.Statsig.StatsigClient("", {}); ``` Now, fetch the config and construct the banner: ```js const bannerConfig = client.getDynamicConfig("banner_config"); const text = bannerConfig.get("text", null); const backgroundColor = bannerConfig.get("backgroundColor", "black"); const color = bannerConfig.get("color", "white"); const fontSize = bannerConfig.get("fontSize", 14); if (text == null) { return; } const banner = document.getElementById("homepageBanner"); const bannerText = document.createElement("p"); banner.style.display = "block"; bannerText.innerHTML = text; banner.style.color = color; banner.style.fontSize = fontSize + "px"; banner.style.backgroundColor = backgroundColor; banner.appendChild(bannerText); ``` This JavaScript relies on the HTML page having a homepageBanner div: ```html
``` With a small amount of JavaScript, this example integrates with the Statsig SDK and uses the Dynamic Config. You can now add a new rule to the Dynamic Config and return a different banner to a different group of users without updating the website. Here is an example of the result when viewing the webpage in Chrome on a Mac: ![UI for mac users](https://docs.statsig.com/images/guides/first-dynamic-config/b82e808a-99b5-4922-90f7-727d9e5d942a.png) This example shows one approach to using Dynamic Config with your app, website, or backend service. ================================================================================ # Segments URL: https://docs.statsig.com/segments/overview ================================================================================ # Segments ## What is a segment? A segment defines a reusable set of users. You can define a segment based on common user attributes such as location, client device, browser, client application version, or user IDs. ## When to use segments Segments are ideal for targeting a commonly identified set of users across features or dynamic configs. For example, you can create a segment representing your team members or company employees to test a new feature before launching to external users. You can also create different segments for English-speaking and Spanish-speaking countries to deliver a localized experience to each segment. To get started, go to the Statsig guide to [create your first segment](https://docs.statsig.com/guides/first-segment). The following tutorials show how to perform common tasks with segments. - [Create a segment](https://docs.statsig.com/segments/create-new) - [Create rules for a segment](https://docs.statsig.com/segments/add-rule) - [Use a segment](https://docs.statsig.com/segments/implement) ================================================================================ # Create a segment URL: https://docs.statsig.com/segments/create-new ================================================================================ # Create a segment To create a segment: - Log in to the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Segments** - Click the **Create** button - Enter a name and description for your segment - Select the type of segment you want to create: **Conditional** or **ID List**, and click **Create** (Conditional is the default) ![Segment creation interface](https://docs.statsig.com/images/segments/create-new/e2dd3e0e-a003-4772-8426-cb02738f4017.png) For **Conditional Segments**, you can **[Add Rules](https://docs.statsig.com/segments/add-rule)** to complete the segment's definition. For **ID List Segments**, you can **[Add an ID List](https://docs.statsig.com/segments/add-id-list)** to complete the segment's definition. ================================================================================ # Adding Rules URL: https://docs.statsig.com/segments/add-rule ================================================================================ # Adding Rules ## Create a rule for a segment A rule defines the criteria for which users a segment includes. To add a rule to a segment: - Log in to the Statsig console at https://console.statsig.com - On the left-hand navigation panel, select **Segments** - Select the segment where you want to add a rule - Click the **Add New Rule** button - Select the criteria to target a set of users. For example, select **Email** with the **Contains any of** operator, then enter your company's email domain to target only internal employees. ![Segment rule configuration interface](https://docs.statsig.com/images/segments/add-rule/129094975-a78b8caf-ac0d-4b14-96f7-adba2fe73f1f.png) - Click the **Add Rule** button - Click the **Save Changes** button at the top right of the **Rules** section ================================================================================ # Adding ID Lists URL: https://docs.statsig.com/segments/add-id-list ================================================================================ # Adding ID Lists ## Adding ID lists ### What is an ID list An ID List defines a reusable audience segment from user identifiers like `userID`, `stableID`, or `organizationID`. Use it to target a specific set of known users across gates, experiments, and dynamic configs. For audiences of hundreds of thousands or more, set an attribute on the User object instead of maintaining a large ID List. You can manage ID Lists by manually adding or removing IDs, uploading CSVs, or replacing the entire list. ### Creating an ID list segment 1. Navigate to the **Segments** section in the [Statsig Console](https://console.statsig.com). 2. Click **Create New Segment**. 3. Toggle the segment type from **Conditional** to **ID List**. ![Create New Segment](https://docs.statsig.com/images/segments/add-id-list/af7c5cb3-adc2-4e88-a411-b5844a541e49.png) 4. Select the **ID type** you want to build from. ![Create New Segment](https://docs.statsig.com/images/segments/add-id-list/958b7545-7f23-4559-8a66-99af01d39952.png) ### Managing IDs After you open your ID List segment, you have several options: - **Manual Entry**: Enter IDs directly into the input box. ![Create New Segment](https://docs.statsig.com/images/segments/add-id-list/ee94e6bc-475b-47a0-96a7-5ddba398d58c.png) - **Upload CSV**: Import a list of IDs from a CSV. - **Bulk Actions**: Choose how your input affects the existing list: - **Add**: Add IDs to the list. - **Remove**: Remove matching IDs from the list. - **Replace**: Clear all IDs and replace with a new list. You can also sync an ID list segment from sources such as [Amplitude Cohorts](https://amplitude.com/docs/analytics/behavioral-cohorts), [Segment Audiences](https://docs.statsig.com/integrations/data-connectors/segment#syncing-statsig-segment-id-lists-with-segment-personas-audiences), or a custom source using the [Console API](https://docs.statsig.com/console-api/introduction). There's a hard limit of 10 million IDs across all ID Lists in your project. ### Keep ID lists small Statsig synchronizes ID Lists with fewer than 1,000 IDs in the same process as feature gates, experiments, and conditional segments, providing high consistency and reliability. ID Lists over 1,000 IDs use a separate synchronization process for scalability. As a result, Statsig doesn't include them in the main initialization path (for server SDKs or the local evaluation version of client SDKs), and change propagation takes longer. > **Warning:** > > Support for ID Lists over 1,000 IDs varies by SDK. Check your SDK's documentation for any setup required before using a list of that size. If an SDK doesn't download or support large lists, users in that list evaluate as not in the segment, with no error returned. Keep each ID List to no more than 1,000 IDs unless the longer propagation time is acceptable. To target hundreds of thousands or millions of users, the more performant approach is to set an attribute on the User object passed to the Statsig SDK. For example, pass `user_type:Paid` or `user_type:Trial` in the User object instead of maintaining large ID Lists. This approach requires your app to have the attribute available when calling the Statsig SDK. ================================================================================ # Using a segment URL: https://docs.statsig.com/segments/implement ================================================================================ # Using a segment You can use a segment to target a set of users in a feature gate or a dynamic config: - Select the feature gate or dynamic config where you want to target users - Click the **Add New Rule** button - In the criteria, select the **User in Segment** option - Select the segment that you want to use and enter a name ![Segment targeting configuration interface](https://docs.statsig.com/images/segments/implement/129115596-fbaeb686-8adb-4ebe-9dcb-6dfecf0cf043.png) - Click the **Add Rule** button - Click the **Save Changes** button at the top right of the **Rules** section ================================================================================ # Release Pipeline Overview URL: https://docs.statsig.com/release-pipeline/overview ================================================================================ # Release Pipeline Overview Release Pipelines roll out feature gate and dynamic config changes in stages across your environments and infrastructure segments. Each phase targets a specific release segment, and you control when a rollout advances with time intervals or manual approvals. Use them to deploy progressively (for example, dev → staging → prod) and monitor each stage before the next begins. ## When to use Release Pipelines Consider using Release Pipelines when you need to: - Implement infrastructure-aware deployment strategies beyond what traditional feature flags offer - Safely roll out changes in complex, distributed systems with minimal risk - Deploy progressively across environments (dev → staging → prod) - Target specific infrastructure segments with precision (e.g., prod-us-west → prod-us-east → prod-eu) - Control progression between stages with time intervals or manual approvals - Monitor each deployment stage before proceeding to the next - Enable instant rollbacks if issues arise during any phase ### Especially valuable for - Platform engineering teams managing multi-environment, multi-region infrastructure - DevOps practitioners implementing progressive delivery strategies - SREs responsible for maintaining system reliability across complex deployments - Organizations with mission-critical services that can't afford downtime ## Key concepts | Concept | Description | | --- | --- | | **Release Pipeline** | Defines the complete release strategy for a feature gate or dynamic config change | | **Phase** | A distinct stage in the pipeline with specific conditions targeting designated release segments | | **Trigger** | An event that starts when a feature gate or dynamic config begins using a Release Pipeline | | **Action** | Controls you can apply to an active Trigger to manage the release process | ## Get started with release pipelines > **Note:** > > Statsig currently supports Release Pipeline only in its [Server Core SDKs](https://www.statsig.com/blog/introducing-statsig-server-core-v0-1-0). Legacy SDKs continue to work but don't get the full features of release pipelines. Follow these tutorials to begin implementing Release Pipelines: - [Create and Manage Release Pipelines](https://docs.statsig.com/release-pipeline/create-and-manage) - [Trigger a Release Pipeline](https://docs.statsig.com/release-pipeline/trigger) - [Manage an Ongoing Release Pipeline](https://docs.statsig.com/release-pipeline/actions) ## Current limitations - Release pipeline doesn't support experiments - Resalt/Disable/Delete/Archive/Launch actions don't trigger a release pipeline - [Scheduled rollouts](https://docs.statsig.com/feature-flags/scheduled-rollouts) don't work with release pipeline ================================================================================ # Create and Manage Release Pipelines URL: https://docs.statsig.com/release-pipeline/create-and-manage ================================================================================ # Create and Manage Release Pipelines ## Creating a new pipeline To create a new Release Pipeline: 1. Log into the [Statsig console](https://console.statsig.com) 2. Navigate to **Settings** > **Feature Management** 3. Under Release Pipelines, click the **Create** button 4. Enter a descriptive name for your pipeline 5. Click **Create** to proceed to the configuration page ![Create release pipeline interface](https://docs.statsig.com/images/release-pipeline/create.png) ## Configuring phases Each pipeline consists of one or more phases, with each phase representing a distinct release target. ### Adding phases For each phase in your pipeline: 1. Add one or more release rules 2. Select a required **Environment** for the rule 3. Optionally add custom field conditions for more precise targeting ![Phase configuration](https://docs.statsig.com/images/release-pipeline/phases.png) ### Setting phase transitions Control how your phases progress with these transition options: | Transition Type | Description | | --- | --- | | **Require Review** | Requires manual approval from an authorized user before starting the phase | | **Time Interval** | Automatically proceeds to the next phase after a specified duration (in minutes) | :::note You can combine both options in a single phase. When you use both, the time interval only begins counting down after someone gives the required approval. ::: ![Phase transition conditions](https://docs.statsig.com/images/release-pipeline/condition.png) ## Managing existing pipelines ### Updating a pipeline To modify an existing pipeline: 1. Click on the pipeline name from the list 2. Make your edits to any section 3. Click **Save** to apply your changes **Important:** You can't modify pipelines with active rollouts in progress until those rollouts complete or you stop them. ### Viewing pipeline references There are two ways to see which feature gates and dynamic configs are currently using a pipeline: 1. Project Settings - Navigate to Project Settings - Click on the Feature Management menu in the left-rail - Navigate to Release Pipelines section - Click on the **References** column against each Release Pipeline - This shows all feature gates and dynamic configs currently attached to a specific pipeline ![Reference](https://docs.statsig.com/images/release-pipeline/reference.png) 2. Feature Gates / Dynamic Configs Page - Navigate to Feature Gates / Dynamic Config list view - Filter by 'Release Pipeline' current status - This shows all feature gates and dynamic configs with an ongoing release pipeline ![Feature gates and dynamic configs with release pipeline status](https://docs.statsig.com/images/release-pipeline/create-and-manage/23a3199f-4710-40ed-9bd3-14d2ae5edb49.png) ## Opting out environments from Release Pipelines By default, all environments trigger Release Pipelines when you make changes. You can configure specific environments to be exempt from this behavior. When you opt an environment out from Release Pipelines: - Changes you make exclusively to that environment don't trigger a Release Pipeline. - Opting an environment out allows quick environment-specific adjustments without starting the full release process. ### How to opt out an environment To exclude an environment from triggering Release Pipelines: 1. Navigate to **Settings** in the Statsig console 2. Under **Keys & Environments**, select **Environments** 3. Click on the environment you want to opt out 4. Unselect the **Pipeline-required Environment** option 5. Click **Save** to apply your changes ![Environment opt-out setting](https://docs.statsig.com/images/release-pipeline/environment-opt-out.png) ================================================================================ # Trigger a Release Pipeline URL: https://docs.statsig.com/release-pipeline/trigger ================================================================================ # Trigger a Release Pipeline Statsig activates a Release Pipeline when you make changes to a feature gate or dynamic config that has a pipeline attached to it. ## Attaching a pipeline Before triggering a release, attach a pipeline to your feature gate or dynamic config. The Statsig console offers two methods for attaching a Release Pipeline. ### During feature creation You can select a Release Pipeline directly in the creation modal when setting up a new feature gate or dynamic config: ![Attaching a pipeline during creation](https://docs.statsig.com/images/release-pipeline/modal-attach.png) ### To an existing feature For an existing feature gate or dynamic config, you can attach a Release Pipeline through the sidebar settings: ![Attaching a pipeline via sidebar](https://docs.statsig.com/images/release-pipeline/sidebar-attach.png) :::note You must have at least one Release Pipeline created before it appears in the dropdown menu. Refer to [Create and Manage Pipelines](https://docs.statsig.com/release-pipeline/create-and-manage) for instructions on creating pipelines. ::: ## Starting a rollout After you attach a Release Pipeline, making changes to your feature gate or dynamic config automatically starts the pipeline process: 1. Make your changes to the feature gate or dynamic config 2. Click **Save** to commit the changes 3. A confirmation dialog appears, informing you that changes progress through the pipeline 4. Review the information and click **Confirm** to proceed The system then begins the rollout following the phases defined in the attached pipeline. ![Confirmation dialog when triggering a pipeline](https://docs.statsig.com/images/release-pipeline/trigger.png) ## Viewing release status After you trigger a Release Pipeline, you can monitor its progress: 1. At the top of the feature gate or dynamic config page, a status banner appears 2. This banner displays the current phase and overall progress through the pipeline ![Status banner showing release progress](https://docs.statsig.com/images/release-pipeline/view-status.png) For information about controlling an ongoing release, including approvals and cancellations, refer to [Managing Release Actions](https://docs.statsig.com/release-pipeline/actions). ## Frequently asked questions **Q: Can I attach different Release Pipelines to different feature gates?** A: Yes, each feature gate or dynamic config can use a different pipeline based on its specific rollout needs. However, a single feature gate or dynamic config can only have one Release Pipeline attached at a time. **Q: What happens if I need to cancel a release in progress?** A: You can stop an ongoing release using the actions menu in the release details view. Refer to [Managing Release Actions](https://docs.statsig.com/release-pipeline/actions) for complete instructions. ================================================================================ # Manage an Ongoing Release Pipeline URL: https://docs.statsig.com/release-pipeline/actions ================================================================================ # Manage an Ongoing Release Pipeline ## Managing release actions After you trigger a Release Pipeline, you can control its progression using the following actions. These controls let you safely test, pause, fast-track, or halt propagation of feature gate and config changes across pipeline phases. ![Release pipeline management actions](https://docs.statsig.com/images/release-pipeline/actions/519ecada-cce9-4b70-9492-62d21190a85a.png) ### Approve #### What it does Start a phase that requires manual approval before rollout begins. Use this when your workflow requires human verification before changes proceed. #### How to use it 1. The pipeline automatically pauses at the last completed phase awaiting approval 2. You receive a notification prompting you to take action 3. Go to the Release Pipeline status page 4. Click the ⋯ menu and select 'Approve' 5. Confirm the action. The next phase begins rolling out. ### Pause #### What it does Stops the bake timer between two phases. Useful if you want to delay rolling out the next phase to investigate the current phase. :::note Pause doesn't stop the current phase. It stops only the timer to move to the next phase. ::: #### How to use it 1. Go to the Release Pipeline status page 2. Click the ⋯ menu and select 'Pause' 3. Confirm to pause the bake timer ### Unpause #### What it does Resumes a previously paused bake timer, allowing the pipeline to move to the next phase after the remaining wait time. #### How to use it 1. Go to the Release Pipeline status page 2. Click the ⋯ menu and select 'Unpause' 3. Confirm to resume the bake timer ### Skip #### What it does Immediately skips the current phase and moves rollout to the next defined phase. Useful for fast-tracking safe changes. #### How to use it 1. Go to the Release Pipeline status page 2. Click the ⋯ menu and select 'Skip' 3. Confirm to resume the bake timer ### Abort #### What it does Halts the release process. The feature gate or dynamic config reverts to its pre-release state, and no further changes propagate. **Important:** Aborting a release is irreversible. After aborting, you must trigger a new release to restart the process with any modifications. #### How to use it 1. Go to the Release Pipeline status page 2. Click the ⋯ menu and select 'Abort' 3. Confirm to resume the bake timer ### Full roll out #### What it does Skips all intermediate phases and releases the latest version across all environments and custom attributes once. #### How to use it 1. Go to the Release Pipeline status page 2. Click the ⋯ menu and select 'Full Roll Out' 3. Confirm to resume the bake timer ================================================================================ # Smart Gate URL: https://docs.statsig.com/smart-gate/overview ================================================================================ # Smart Gate Smart Gate is an AI agent that reviews pull requests in your connected GitHub repositories and flags changes risky enough to ship behind a feature gate. When the PR author opts in, Smart Gate opens a second pull request that wraps the change in a new Statsig feature gate. After the code deploys, Statsig ramps the gate on a schedule, reverts it to 0% if a safeguard alert fires, and opens a cleanup PR once the gate has been at 100% long enough. Use Smart Gate when you want risky changes to ship behind a gate without hand-writing gate checks, picking metrics, or babysitting a rollout. Create a gate yourself with [Create a feature gate](https://docs.statsig.com/feature-flags/create) when you need custom targeting, a permanent gate, or an experiment. If you already manage gate rollouts with [Release Pipelines](https://docs.statsig.com/release-pipeline/overview), Smart Gate leaves those gates alone and doesn't ramp them. > **Info:** Availability > > Smart Gate is in early access. Statsig enables it per organization. To request access, contact your Statsig account team or [Statsig support](https://docs.statsig.com/support-options). ## How Smart Gate works Nothing in your code changes until someone opts in on the pull request. | Stage | What happens | | --- | --- | | Review | When a PR opens, Smart Gate assesses how risky the change is. | | Suggest | For a risky change, Smart Gate comments on the PR with what could break and how to opt in. Otherwise, it marks the PR **No gate needed**. | | Opt in | The PR author or a collaborator comments `@statsig gate this`. | | Wrap | Smart Gate creates the gate and opens a wrap PR that puts the change behind it. With the gate off, your app behaves as it does today. | | Merge | You merge the wrap PR into your branch, then merge your PR as usual. | | Ramp | After the code deploys, Statsig ramps the gate on your rollout schedule. | | Revert | If a safeguard alert fires, Statsig turns the gate back off and notifies the PR author. | | Clean up | After the gate has been fully launched for a while, Smart Gate opens a PR that removes it from your code. | Smart Gate understands how your codebase already uses Statsig, so the gate it adds reads like code your team wrote: same SDK, same patterns, same style. Smart Gate keeps the PR author updated in a comment on the PR, and optionally in Slack. For what PR authors see and do, go to [Work with Smart Gate on a pull request](https://docs.statsig.com/smart-gate/pull-requests). ## The gates Smart Gate creates - **Off in production, on in development and staging**: you can test the new behavior before any user gets it. - **Monitored**: each gate gets metrics and safeguard alerts from the project settings you choose. - **Editable**: you can change a gate's rules, metrics, and alerts from the console like any other gate. ## What Smart Gate doesn't do - **Change code without consent**: Smart Gate only opens a wrap PR after someone on your team opts in. - **Block your merge**: Smart Gate's check on the PR never fails. ## How Smart Gate handles your code Smart Gate works on your code in an isolated, short-lived environment, and Statsig and its LLM sub-processors don't use your data to train models. For details, go to [AI governance, security, and privacy](https://docs.statsig.com/compliance/ai_governance_security_privacy). ## Get started To connect GitHub and turn on Smart Gate, go to [Set up Smart Gate](https://docs.statsig.com/smart-gate/set-up). ================================================================================ # Set up Smart Gate URL: https://docs.statsig.com/smart-gate/set-up ================================================================================ # Set up Smart Gate Smart Gate settings belong to your Statsig organization, not to a single project. Organization admins can change them from any project. Statsig has enabled Smart Gate for your organization. Smart Gate is in early access; contact your Statsig account team to request it. You're an organization admin in Statsig. If your project doesn't belong to an organization, you need the project Admin role with integrations access. You can install GitHub Apps in your GitHub organization, or someone who can is available to approve the install. ## Connect the Statsig GitHub App Smart Gate uses the Statsig GitHub App, which appears as **Statsig Code** on GitHub. If you already connected it for code references or the [GitHub AI integration](https://docs.statsig.com/integrations/github-ai-integration), skip to the next step. 1. In the Statsig console, go to _Settings > Integrations_. 2. Select the **Statsig GitHub App** card, then select **Enable Connection**. 3. On GitHub, choose your organization and the repositories to grant access to, then approve the requested permissions. Other Statsig projects inherit the connection from the same card. Inherit it in each project that should receive gates. If your GitHub organization restricts access by IP address, allowlist the [Statsig IP ranges](https://docs.statsig.com/infrastructure/statsig_ip_ranges). ## Open the Smart Gate settings 1. In the Statsig console, go to _Settings > Integrations_ and select the **Statsig GitHub App** card. 2. On the **Smart Gate** card, select **Set up Smart Gate**. After setup, this button reads **Manage Smart Gate**. You can also search for **Smart Gate Settings** from the console search bar. The settings page has three tabs: **Repositories**, **Projects**, and **Rollout & cleanup**. Changes don't take effect until you select **Save changes**. ## Choose the repositories to review Smart Gate only reviews pull requests in repositories you add on the **Repositories** tab, even if the GitHub App can access more. 1. Select **Add a repository** and pick a repository from the list. 2. Under **Suggest gates for**, choose how many suggestions Smart Gate makes: - **High-risk changes** (default): the fewest suggestions, only for changes likely to break users. - **Medium and high-risk changes**: more suggestions, including moderate behavior changes. 3. Under **Review new pull requests automatically**, choose when Smart Gate reviews a PR: - **On** (default): Smart Gate reviews every PR when it opens or someone marks it ready for review. - **Off**: Smart Gate only reviews a PR when someone comments `@statsig gate this` or adds the `smart-gate` label. 4. Under **Folders**, choose where gates go. The root row sets the Statsig project for the whole repository. To send gates for part of a monorepo to a different project, select **Add folder rule**, pick the folder, and choose a project under **Gates created in**. If a single PR changes folders mapped to different projects, Smart Gate doesn't wrap it. > **Note:** > > Smart Gate doesn't create the `smart-gate` label. To let people opt in with the label, create a label named `smart-gate` in the GitHub repository. ## Configure each project that receives gates The **Projects** tab lists the projects that receive gates for the folders you mapped. Monitoring and safeguards use each project's own metrics, teams, and alerts. Select a project to edit these settings, which apply to every gate Smart Gate creates in that project: - **Metrics to attach**: the metrics Smart Gate adds to each new gate. - **Core metrics** (default): the project's metrics tagged Core. This option works with no setup. - **Owning team's gate metrics**: the default gate metrics of the team you choose under **Owning team**. - **Core metrics + suggested**: Core metrics, plus metrics Smart Gate suggests for the change. - **Owning team**: the team that owns new gates. Required for **Owning team's gate metrics**, or if the project requires a team on new configs. - **Target apps**: the target apps for new gates. Leave empty for all apps. - **Safeguards**: the **Guardrail alerts** and **Topline alerts** to watch during the ramp. If one fires, Statsig turns the gate back off. Set at least one safeguard alert. Smart Gate doesn't ramp a gate without one. To create alerts, go to [Alerts](https://docs.statsig.com/product-analytics/alerts-overview). To learn how alerts protect a rollout, go to [Safeguards](https://docs.statsig.com/feature-flags/safeguards-overview). ## Configure rollout and cleanup The **Rollout & cleanup** tab controls what happens after a wrapped PR merges. - **Rollout schedule**: the phases each gate ramps through after its PR deploys. Without a custom schedule, Statsig uses its default of 5%, 25%, then 100%, with 24 hours per phase. To change it, select **Customize**. The last phase must reach 100%. - **Wait for deploy up to**: how long Smart Gate waits for the merged code to reach production before it gives up. The default is 120 hours. - **Clean up launched gates after**: how many days a gate stays at 100% before Smart Gate opens a PR to remove it from the code. The default is 10 days. - **Open at most**: the daily limit on cleanup PRs. The default is 10. - **Archive the gate when its cleanup PR merges**: off by default. - **Fix failing checks on Smart Gate PRs**: when on, Smart Gate tries to fix CI failures on its own wrap PRs. Off by default. - **Send Slack notifications**: on by default. Choose which events to send: **Rollout started**, **Launched to 100%**, **Rolled back**, **Cleanup PR opened**, **CI repair gave up**, and **Deploy wait timed out**. Notifications go to the Slack channel of the project that owns each gate. That project needs [Slack connected](https://docs.statsig.com/integrations/slack) with **Smart Gate lifecycle** turned on in its event filtering. ## Turn on Smart Gate 1. At the top of the settings page, set the Smart Gate switch to **On**. 2. Select **Save changes**. Smart Gate starts reviewing pull requests opened after you turn it on. To review a PR that was already open, comment `@statsig gate this` on it. To stop Smart Gate, set the switch to **Off** and save. Smart Gate stops reviewing new pull requests. ================================================================================ # Configure sandbox profiles URL: https://docs.statsig.com/smart-gate/sandbox-profiles ================================================================================ # Configure sandbox profiles A sandbox profile defines how Smart Gate prepares a repository or folder for coding and verification. A profile build saves the repository, installed dependencies, and tools in a reusable filesystem snapshot. Customize a profile when your repository needs setup steps that automatic setup doesn't discover. ## Open a sandbox profile You need permission to edit Smart Gate settings and a repository connected through the Statsig GitHub App. If you haven't connected the repository, follow [Set up Smart Gate](https://docs.statsig.com/smart-gate/set-up). 1. Open the Smart Gate settings from _Settings > Integrations > Statsig GitHub App_. 2. On the _Repositories_ tab, expand the repository and find the folder row you want to configure. 3. In the _Sandbox profile_ column, select **Customize** to create a profile or **Configure** to edit an existing profile. 4. Select **Configuration** in the profile drawer. A folder without its own profile can inherit a parent folder's profile. Select **Save and build** to give that folder its own profile. If the settings page says **Save to customize**, save your repository settings first. If profile controls aren't available, contact your Statsig account team. ## Configure setup and startup scripts Use the _Setup script_ setting for toolchain installation, dependency installation, and required build or code-generation steps. The setup script runs during a snapshot build. | Setup option | When to use it | | --- | --- | | Automatic | Let Smart Gate work out the installation steps from repository setup instructions and configuration. Start here unless your repository needs custom steps. | | Script in the repository | Use a checked-in setup script, such as `scripts/sandbox-setup.sh`. | | Inline script | Enter shell commands directly in the profile. | Use the _Startup script_ setting for work that each new sandbox needs after checkout, such as starting required services. Choose **None**, **Script in the repository**, or **Inline script**. Keep dependency installation in the setup script so Smart Gate can reuse the installed files from the snapshot. Write scripts that work in the default Linux sandbox image. Make scripts safe to run again, and keep verification focused on the repository or folder the profile serves. Never put tokens, passwords, or other secrets in scripts or setup learnings. Organization members can read these values. ## Build a snapshot Select **Save and build** to save the profile configuration and start a snapshot build. The build uses the default sandbox image, checks out the repository, prepares the toolchain, verifies the setup, and captures the filesystem for later runs. Setup verification checks whether tools can execute commands such as lint, typecheck, and focused tests. Existing source-code errors can still appear in those checks. A usable toolchain doesn't mean every check passes on every pull request. To try configuration changes without changing the artifact Smart Gate uses, select **Test build**. Test builds retain their build details and logs, but Smart Gate doesn't use their artifacts for pull requests or save their new setup learnings. Select **Save and build** when you're ready to publish a reusable snapshot. ## Inspect build results Open the _Builds_ tab in the profile drawer and select a build to inspect its details. - **Status and duration**: Check the build status and how long the build takes. - **Usable until**: Check the snapshot's expiration date. Rebuild the profile when its snapshot approaches expiration. - **Logs**: Inspect setup, installation, verification, and capture output to diagnose a failed build. - **Source commit and scripts**: Confirm which repository revision and setup configuration the build used. - **Snapshot details**: Inspect the snapshot ID, size, and base image when you need to identify an artifact. - **Setup learnings**: Read observations from the build. Successful saved builds can update the profile's read-only learnings for future builds. Check the profile's active build indicator to confirm which snapshot Smart Gate selects. A newer build in the history doesn't necessarily replace the active snapshot. ## How Smart Gate uses snapshots Smart Gate restores a usable snapshot for the profile, checks out the pull request's code, and verifies the environment before coding. It can attempt repairs for requirements that differ from the saved snapshot. A successful saved build can become the profile's active snapshot. Smart Gate checks that the snapshot matches the repository and folder and has enough usable lifetime remaining. It excludes expired snapshots and test-build artifacts. If the active snapshot is unavailable, Smart Gate looks for another compatible, usable snapshot. If toolchain setup fails and the profile has no usable prepared snapshot, Smart Gate can retain a snapshot containing only the repository checkout. This reduces repeated cloning, but it doesn't provide verified lint, typecheck, or test tools. Smart Gate prefers a prepared snapshot when one is available. A failed build doesn't displace a usable prepared snapshot. ================================================================================ # Work with Smart Gate on a pull request URL: https://docs.statsig.com/smart-gate/pull-requests ================================================================================ # Work with Smart Gate on a pull request This page is for engineers whose pull requests Smart Gate reviews. Your Statsig organization admin must [set up Smart Gate](https://docs.statsig.com/smart-gate/set-up) for the repository first. ## Commands | Action | Effect | | --- | --- | | Comment `@statsig gate this` | Opts the PR in and starts the wrap. Also re-wraps the PR after you push new commits. | | Add the `smart-gate` label | Same as `@statsig gate this`, if the repository has a label with that name. | | Comment `@statsig feedback ` | Sends feedback about the suggestion to Statsig. | Smart Gate accepts commands from your team's members and collaborators. ## When Smart Gate reviews a pull request If the repository reviews pull requests automatically, Smart Gate reviews your PR when you open it or mark it ready for review. Otherwise, it reviews a PR only when someone comments `@statsig gate this`. Smart Gate doesn't review drafts, or PRs from forks or bots. If the change doesn't need a gate, Smart Gate marks the PR **No gate needed**. Its check never fails, so it never blocks your merge. If you disagree, comment `@statsig gate this` and Smart Gate wraps the PR anyway. If the change is risky, Smart Gate comments with what could break and the gate it plans to create. To accept, reply `@statsig gate this`. If you don't want a gate, ignore the comment. ## Review and merge the wrap PR After you opt in, Smart Gate creates the gate, off in production and on in development and staging, and opens a wrap PR into your branch. The wrap PR follows your codebase's conventions for Statsig. If the changed code runs in a service that doesn't use a Statsig SDK yet, Smart Gate sets one up in the wrap PR where it can. To ship the change: 1. Review the wrap PR. You can push changes to its branch like any other PR. 2. Merge the wrap PR into your branch. 3. Merge your original PR as usual. > **Warning:** > > If you merge your original PR without the wrap PR, Smart Gate removes the gate and nothing ramps. If you push more commits to your PR after opting in, the wrap PR doesn't cover them. Reply `@statsig gate this` again to rebuild the wrap. If CI fails on the wrap PR, push a fix to the wrap branch. If your organization turned on CI repair, Smart Gate tries to fix it first. ## Ramp, revert, and launch After the code deploys, Statsig ramps the gate on your organization's rollout schedule. Smart Gate's comment on your PR shows the current percentage. If a safeguard alert fires, Statsig turns the gate back off and Smart Gate mentions you on the PR. Investigate the alert, then ramp the gate from its page in the console when you're ready. If Smart Gate pauses the ramp, for example because the gate has no safeguard alerts, its comment on the PR says why and what to do. ## Cleanup After the gate has been fully launched for a while, Smart Gate opens a PR that removes the gate from your code. Review and merge it like any other PR. To remove a launched gate sooner, select **Remove from Code** on the gate's page in the Statsig console. ## Stop Smart Gate on a pull request Smart Gate doesn't change anything until someone opts in. After that, close the wrap PR to stop it from gating your PR. ================================================================================ # Troubleshoot Smart Gate URL: https://docs.statsig.com/smart-gate/troubleshooting ================================================================================ # Troubleshoot Smart Gate Use this page when Smart Gate doesn't review a pull request, can't wrap one, or doesn't ramp a gate. Most problems show up as a Smart Gate comment on the pull request, and the comment says what to do next. ## Smart Gate doesn't review a pull request - **Smart Gate is off, or the repository isn't added**: an organization admin turns Smart Gate on and adds repositories in its settings. Go to [Set up Smart Gate](https://docs.statsig.com/smart-gate/set-up). - **Automatic review is off, or the PR opened before Smart Gate was on**: comment `@statsig gate this` on the PR. - **The PR is a draft, or comes from a fork or a bot**: Smart Gate skips these. ## Common messages | Message | What to do | | --- | --- | | Smart Gate isn't turned on for this GitHub installation. | Ask a Statsig organization admin to turn on Smart Gate, then reply `@statsig gate this` again. | | Smart Gate isn't enabled for this repo. | Ask a Statsig organization admin to add the repository in the Smart Gate settings, then reply again. | | Smart Gate couldn't build the wrap PR. | Nothing in your code changed. Reply `@statsig gate this` to retry. If it keeps failing, contact [Statsig support](https://docs.statsig.com/support-options). | | Smart Gate didn't add a gate. | Smart Gate couldn't make this change safe to switch off. Follow the guidance in the comment, or [create a gate yourself](https://docs.statsig.com/feature-flags/create). | | New commits aren't gated. | Reply `@statsig gate this` to rebuild the wrap with your latest commits. | | Ramp paused | Follow the comment. The most common fix is adding a safeguard alert on the gate page. | ## Problems in the Smart Gate settings - **Smart Gate settings aren't available here**: connect or inherit the Statsig GitHub App in the project. If that doesn't help, contact your Statsig account team. - **The settings are view only**: only organization admins can change Smart Gate settings. - **You can't pick a project for a folder**: inherit the GitHub connection in that project from _Settings > Integrations > Statsig GitHub App_. ================================================================================ # Product Analytics Overview URL: https://docs.statsig.com/product-analytics/overview ================================================================================ # Product Analytics Overview ## Metrics Explorer Metrics Explorer is where you analyze your product data to understand how users interact with your product and to uncover ideas for new features. After you implement these features, you can release and measure their impact using Statsig feature gates, A/B tests, or experiments to understand how the features affect core metrics. ### Charts in Metrics Explorer In Metrics Explorer, charts are the primary means of analysis, providing a detailed look at your data. You can switch between chart types from the top-left section of the interface while maintaining context on the selected events. Switching chart types lets you focus on a particular metric or event while exploring it from different angles. Statsig offers the following chart types: - [Metric Drilldown](https://docs.statsig.com/product-analytics/drilldown) - [Funnels](https://docs.statsig.com/product-analytics/funnels) - [Retention](https://docs.statsig.com/product-analytics/retention) - [Distribution](https://docs.statsig.com/product-analytics/distribution) - [User Journeys](https://docs.statsig.com/product-analytics/user-journeys) - [Lifecycle](https://docs.statsig.com/product-analytics/lifecycle) Get started with Metrics Explorer charts by navigating to the **Analytics** section of the Statsig console navigation menu and selecting [Metrics Explorer](https://console.statsig.com/metrics/explore). ## Dashboards [Dashboards](https://docs.statsig.com/product-analytics/dashboards) let you share insights and information with your team. You can save any chart you build to a dashboard. You can also save a snapshot of Feature Gates, A/B tests, and experiments to dashboards. Experiment and feature gate snapshots sync automatically to a dashboard, keeping your team up to date with relevant launches as they emerge. Statsig auto-populates these dashboards with any entity matching the tags you specify. ### Charts in Dashboards You can add any chart supported in Metrics Drilldown to dashboards. Dashboard charts aren't static. After expanding a chart using the \[ \] icon, you can modify it for further exploration without saving the change to the dashboard. To save changes, click the edit icon or button and save. To get started, navigate to **Dashboards** in the Statsig left navigation. ================================================================================ # Metric Drilldown Charts URL: https://docs.statsig.com/product-analytics/drilldown ================================================================================ # Metric Drilldown Charts The Metric Drilldown chart in Metrics Explorer is a tool for understanding customer behavior and trends within your product. Use it to analyze key metrics and user behavior over time. You can also filter to specific properties or cohorts and use Group-By to compare behaviors between groups. ## Use cases - **Trend Analysis Over Time**: Track how specific metrics evolve over time. Visualizing product data in Metrics Explorer lets you compare key performance indicators and user behavior, and understand long-term trends and short-term fluctuations. - **Identify Cohorts**: Define and explore cohorts by filtering to users who performed certain events at frequencies you define. - **Understand Feature and Experiment Impact**: Split any metric by Experiment Group or Feature Gate Group to compare metric performance across groups. Use automatically generated chart annotations for feature launches and experiment starts to correlate decisions with changing trends. - **Segmentation and Comparison**: Analyze how different user segments or product features perform to identify areas providing value or areas that need improvement. - **Filtering**: Focus on specific segments or cohorts for more targeted analysis. - **Statistical Understanding**: Understand how the average, median, or other percentile value (for example, p99, p95) of a metric changes over time. - **Dynamic Metric Creation with Formulas**: Create new metrics dynamically using custom formulas to derive ad-hoc insights. - **Flexible Visualization Options**: Choose from line charts, bar charts, horizontal bar charts, stacked bar charts, and other formats to best represent your data. - **Event Samples for Debugging**: Access a metric's underlying sample events and the user-level information attached to each event. Useful for troubleshooting trends or anomalies. - **Detailed Data Control**: Adjust data granularity from high-level overviews to detailed breakdowns. Use rolling averages to smooth data for trend analysis. - **Debug Experiments**: Break down your experiment's first exposures to understand how properties or groups (feature gates, experiments, holdouts) affect the experiment. - **View Sample Ratio Mismatch (SRM)**: See the SRM of your experiments over time and drill down into event and user metadata to understand how properties (country, browser) or groups affect experiment SRM. - **Debug Feature Gates**: Break down feature gate first exposures per rule to understand how properties or groups affect the gate. - **Analyze Dimensions Across Metrics**: Identify top or bottom performers across multiple metrics by viewing data in a table and sorting by any metric-column combination. ## Using the metric drilldown chart ## Selecting metrics and events In Metrics Explorer you can choose events, custom-metrics, auto-generated metrics, or experiment exposures to explore. You can add several metrics and events or exposures to plot on a single chart. ### Events When selecting an event, the chart plots the total number of times the event occurred (Count) for a given data point (hour, day, etc.) by default. You can also choose different aggregation methods: - **Count**: Plot the number of times the event occurred within the given time range per data point. - **Unique**: Plot the number of unique ids (generally UserIDs) that performed the event in the given time range per data point. ![Event aggregation options interface](https://docs.statsig.com/images/product-analytics/drilldown/7e4740c5-88e6-4d1c-a49c-dd29dca30714.png) - When viewing data on uniques (for example, unique users) at daily granularity, you can set the value of each daily data point to represent the number of unique weekly users (unique users over the previous 7 days). This shows how weekly usage is changing day over day. ![Weekly unique users configuration option](https://docs.statsig.com/images/product-analytics/drilldown/2cec3257-b8a5-4efc-9bcd-be4d7f871c7a.png) - **Average**: Plot the average of a selected event property value per data point. This works only for properties with numerical values. ![Average event property aggregation interface](https://docs.statsig.com/images/product-analytics/drilldown/f7ea5919-5288-42f0-8949-d711e17ffec7.png) - **Sum**: Plot the sum of a selected event property value per data point. This works only for properties with numerical values. ![Sum event property aggregation interface](https://docs.statsig.com/images/product-analytics/drilldown/20ed372c-e1cb-4c2e-bdac-ed6dd2ba7c4e.png) - **Percentiles**: Plot the value of a selected event property at the selected percentile per data point. ![Percentiles aggregation configuration interface](https://docs.statsig.com/images/product-analytics/drilldown/112d74ec-7a52-4621-8969-af79e8599714.png) - **Unique Values**: Plot the count of distinct values for any property across events or users within the given time range per data point. This aggregation helps answer questions like "How many different referrers drove traffic last week?" or "How many SKUs were added to carts today?" by counting unique property values rather than event occurrences. - **Count per User**: Plot the frequency distribution of how often users perform a specific event. The chart shows statistics like average, median, or percentile values per user within the given time range per data point. This aggregation helps analyze user engagement patterns by measuring how many times each user performed an event, then applying summary statistics across those users. ### Exposures When you select an experiment or gate exposure, the chart plots its first exposures over your selected date range. First exposures are the first time Statsig exposed a unique id (set on the experiment or gate) to each of your experiment groups or each of your gate's rules. ### Understanding first exposures in feature gates When you check a gate for a user, Statsig creates an exposure for the rule whose conditions the user met. If Statsig exposes a user to multiple rules at different times, it keeps the first exposure from each rule. Group by rule to see each rule's exposures separately. ### Metrics Selecting a custom Metric or auto-generated Metric plots the value of that metric over your selected date-range. #### Viewing and modifying the metric definition The metric definition appears directly below the metric name. You can also make ad-hoc edits to the event-based definition to plot new metrics dynamically, based on existing metric definitions. ### Comparing multiple metrics, events, or exposures You can compare multiple metrics or events by plotting them on the same chart. To add a metric, click the **+** icon and select **Metric**, then select the metric. When you plot multiple metrics, click any metric's row in the table below the chart to scope to that metric. Click the row again to show all metrics. Use the checkboxes next to metric names in the table to scope to a custom set of metrics. ### Filtering Filters let you scope to events and metrics logged by users with specific properties. To add a filter to an event or metric, click the filter icon and select the event or user property to filter by. ### Adding formulas Formulas let you dynamically combine and transform plotted events and metrics using mathematical expressions to answer new questions. To add a formula, hover over the **+** icon in the Metrics section and select **Formula**. A free-form text field appears. Use the label of each plotted metric or event as a variable (each plotted metric is labeled with a letter). For example, if you have: - Metric A: number of unique purchasers - Metric B: total purchases You can plot purchases per purchaser as `B/A`. ## Drilling down In addition to plotting metrics, you can drill into your metrics to identify unique groups that reveal how people use your product. ### Group-By A Group-By disaggregates plotted metrics and events by a selected property or group, letting you compare how an action or user behavior correlates with a specific property. Adding a Group-By splits the plotted metrics into separate plots. By default, the chart shows the top ten groups by value. You can select up to 50 groups when you set the chart to daily granularity. You can group a metric by event properties, user profile properties, experiment group, or feature gate group. To adjust Group-By limits, add a group-by, go to the summary table below the charts, and click the **Top X series** dropdown. Select how many groups to display (up to 50). This feature is available for line charts, stacked-line charts, bar charts, and stacked-bar charts. ![Group-by top series selection dropdown](https://docs.statsig.com/images/product-analytics/drilldown/e61fedbe-2633-4469-8120-9959968c484a.png) When you have a Group-By applied, you can view the results as raw numbers, or as a percentage. #### Feature gate and experiment groups You can also select a Feature Gate or Experiment to split a metric by the different groups in the selected test. #### Adding a group-by To add a group-by, hover over the **+** icon in the _Drilldown_ section and select **Group By**. Then select the property or experiment group to split the metric by. #### Quickly hiding or isolating lines When using Group By, you can isolate lines to show data for specific groups. Click the row representing a group in the table view below the chart. Clicking an already-isolated group shows all groups again. Use the checkboxes in the table view to scope to a custom set of groups. ### Define and compare event-based cohorts Building a useful group of users to analyze often requires more precision than comparing by property values. For example, you may want to understand the behavior of power users and compare them against your general user base. To support this, you can define event-based cohorts. Select an event of interest, then define a frequency criterion for how often users in the cohort performed the event: - Performed the event _**at least**_ some number of times - Performed the event _**at most**_ some number of times - Performed the event _**exactly**_ some number of times You can also define the time window in which a user performed the event, and filter to a specific property for more granular cohort definitions. You can save cohorts to reuse them later. ## Exploring a metric drilldown chart ### Selecting chart granularity The Metric Drilldown chart supports daily, hourly, 30-minute, 5-minute, and 1-minute granularity. The granularity setting controls the interval between x-axis values. Granularities below hourly limit the analysis time window to 1 day. The default granularity is daily. To change it, select the **Daily** dropdown in the top right of the chart. When viewing data on uniques (for example, unique users) at daily granularity, you can set each daily data point to represent the number of unique weekly users (unique users over the previous 7 days). This shows how weekly usage is changing day over day. ### Setting the date range The default date range is 14 days. To change it, click the **Last 14 days** dropdown and select a quick date range or a custom range. ### Changing your unit type The default unit type is numbers. To view data as a percentage, time value, or measurement of space (bytes, bits, etc.), click the settings cog in the top right corner of the chart and select a format unit type. ### Smoothing out the data with rollups Metrics like daily usage often have seasonality effects that make longer-term trends harder to see. Rollups such as a 7-day rolling average help smooth this data. Statsig supports the following rollups to smooth out data, each of which you can roll up over 3, 7, 14, 28, 48, or 60 data points: - **Rolling average**: Replaces each data point with the average of the preceding selected number of data points. - **Rolling sum**: Replaces each data point with the sum of the preceding selected number of data points. - **Cumulative Sum**: Replaces each data point with the sum of all preceding data points, including itself. The result is a continuously increasing total where each value represents the accumulated sum. ### Selecting the chart visualization Metrics Drilldown offers many ways to visualize your data, including: - **Line**: Useful when plotting one or more metrics over time. - **Stacked Line**: Useful when comparing groups to understand the relative proportion a certain group has of a metric or event. - **Bar**: Useful when comparing the total value of two metrics over the entire date range. - **Horizontal Bar**: Ideal for grouped data comparisons, especially when you have longer label names. Makes it easy to identify top and bottom performers across any business dimension like user types, locations, or platforms. - **Donut**: Useful for visualizing the proportional breakdown of a whole into distinct categories at a single point in time. Perfect for showing how different segments (like countries, user types, or feature groups) contribute to your total metric value. Apply a Group-By to any metric to see the breakdown as a donut chart. - **World Map**: Visualize your metrics geographically by country when using a country-based Group-By. This view makes it easy to spot geographic trends and understand how your product performs across different regions. - **Single Value**: Display key metrics at a glance for quick summaries. Perfect when you need to highlight a single important number or KPI without the complexity of a full chart. - **Data Table**: Compare multiple metrics across groups in a structured table format. Ideal for detailed analysis when you need to examine exact values and perform side-by-side comparisons of different segments. Both donut charts and world maps work with any metric when you apply a Group-By. Select your metric, add a Group-By for the property you want to analyze (such as country for geographic analysis), and choose your preferred visualization from the chart type selector. ### Zooming in To zoom in on a portion of the date range, click at one end of the range, hold the mouse button down, and drag to the other end. Release the mouse button to zoom in. To reset the zoom, click **Reset Zoom** in the top right of the chart. ### Sharing your insights When you want to share an insight, you have several options: - **Share by URL**: Copy the URL. This shares the query as currently defined. - **Create a share link**: Click the **…** button in the top right of the chart and select **Share Link**. This copies a shortened URL to the clipboard. - **Share to Dashboard**: Click the **…** button and select **Export to Dashboard** to save the chart to an existing dashboard or create a new one. Sharing a chart through a URL or shortened link captures a snapshot of the chart as defined when you copied the link. The share link doesn't capture subsequent changes. ================================================================================ # Funnel Charts URL: https://docs.statsig.com/product-analytics/funnels ================================================================================ # Funnel Charts ## How funnel charts work Funnel Charts in Metrics Explorer show what portion of users complete each step of a journey you define through your product or service. These charts are useful for understanding user behavior, identifying bottlenecks, and developing insight-driven product changes that help users convert more successfully. ### Example use cases - **Conversion Analysis**: Monitor the progression of users through stages like sign-up, adding to cart, and purchase completion. - **Identifying Drop-off Points**: Pinpoint where users drop off, so you can target improvements at those steps. - **Comparing User Segments**: Observe how different user segments move through the funnel, highlighting variations in behavior based on demographics, user types, or other criteria. - **Product Optimization**: Determine which features or steps effectively move users to the next stage, and which require improvements. - **Experiment Analysis**: Understand the conversion rates before and after first exposure to an experiment. ## Defining a user funnel ### Step 1: Add steps to your funnel To define a funnel, select a series of events that represent different parts of a product flow you want to understand. To do so: 1. Go to **Metrics Explorer** under **Analytics** in the Navigation Bar, and switch over to the Funnel Charts view. 2. Add steps to your funnel using the **+** icon. Optionally add filters to funnel steps to target specific event or user properties. For WHN, add steps directly from your **Metric Source**. For Statsig Cloud, use events or metrics for the steps. #### Combining multiple events into one step You can combine multiple events into a single step. This is useful when more than one qualifying event represents a single meaningful portion of your funnel. Combined events use OR logic. To do this: 1. On the step, click the **…** button and select **Combine Events**. 2. Select an additional event to add. 3. Add any filters to each event in the funnel step. Repeat as needed. You can combine up to 5 events per step. ![Funnel step configuration interface](https://docs.statsig.com/images/product-analytics/funnels/2e0d34ba-cff9-4a19-9fe5-ea6ef19b1cfb.png) #### Filtering to the first time a user performed an event Filtering to the first-time experience is useful because first-time behavior can affect long-term retention and may differ significantly from general product flows. You can filter funnel events to the first time a user (or other unit ID) ever performed an event: 1. Click **…** next to the event. 2. Select **Filter to First Time**. ![Filter to first time event option](https://docs.statsig.com/images/product-analytics/funnels/aa72701f-b9c2-47ae-81e8-514a1c1d971b.png) #### Renaming steps When sharing a Funnel Chart (for example, by saving it to a dashboard), logged event names may not be easily readable. You can rename funnel steps for legibility: 1. Click **…** next to the event name. 2. Click **Rename Funnel Step**. 3. Enter a readable name for the step. Renaming a step doesn't change the underlying event name. The rename applies only to the funnel being configured. ### Step 2: Select a graph type Statsig supports three graph types for understanding conversion funnels: - **Conversion Rate**: A standard funnel view showing a step-by-step breakdown of where users drop off and how many convert through each step. - **Conversion Rate Over Time**: Shows how the overall conversion rate has changed over time. Useful for understanding how features and product changes affected the funnel conversion rate. - **Time to Convert**: Shows the distribution of time it takes users to complete the funnel. ### Step 3: Choose an ID type In general, construct funnels using a userID to understand the rate at which individual users complete each step. Some funnels may involve multiple people in an organization. For example, you may want to understand end-to-end company onboarding where different people handle purchasing, deploying, and using the service. Statsig supports individual or group analytics, letting you analyze funnel success at the user level or for whole groups such as organizations or companies. You can choose any ID type defined in your Statsig project when creating a funnel. If you select an experiment exposure, make sure the ID type matches that of the experiment. > **Info:** > > Group analytics isn't a paid add-on at Statsig, and comes at no extra cost for all tiers. ### Step 4: Define the conversion window After you define your funnel, you can limit the analysis to users (or other unit IDs) who converted within a specified time frame. Statsig counts users who start the funnel but don't convert within this time frame as dropped off. ### Step 5: Drilldown To understand how conversion varies between user groups, use the **Group By** feature to split funnels by properties, experiment groups, or feature flag groups. Click **+** to the right of **Group By** and select the property, experiment, or feature flag to split the funnel conversion analysis by. ## Advanced funnel analysis ### Ordered or unordered funnels Ordered funnels are the default and the most common scenario. They require a user to complete the selected events in the specified order to count as converted. The user may perform other events between the specified events and still count as converted. For example, for an ordered funnel with events A, B, C, and D, the sequence A→B→B→A→C→D counts as converted. To check only whether a user completed all events regardless of order, toggle **Ordered** off in the advanced settings. Unordered funnels require only that the user completes the specified events within the given time range. ### Unique users (or unit ID) vs total conversions You can define funnel analysis by the total number of conversions or the number of unique users who convert. The default is Unique Users. ### Daily aggregation When enabled, this setting calculates funnel conversions per calendar day. Statsig counts a unit with funnel conversions on multiple days as multiple conversions. This setting is on by default. ## Interpreting your user funnel ### Conversion rate vs. number of conversions At the top right of the funnel chart, the **Conversion Rate vs. Conversions** selector lets you switch the y-axis between conversion rate and number of conversions. When used with a Group By, toggling between the two views shows both relative and absolute conversion scales across different user groups. ### Conversion summary and table Under each funnel step, a summary shows: - The percentage and number of units that converted, relative to the first step - The percentage and number of units that dropped off, relative to the first step - The average time for each user to convert The conversion table shows the percentage and number of units that converted relative to both the first step and the previous step. This is useful when grouping by a property to compare conversions between user groups. ![Funnel conversion summary table](https://docs.statsig.com/images/product-analytics/funnels/073f9f20-f26f-4af4-a4e9-65d65474b97f.png) ### User exploration By clicking any bar in the funnel, you can download all users in that segment who dropped off or converted as a CSV file. You can also view session streams to get an event-by-event understanding of a user's experience before and after that point in the funnel. ![User exploration options interface](https://docs.statsig.com/images/product-analytics/funnels/2c140de9-bce8-4813-91b1-8f2d8d1e9a66.png) ## Conversion Drivers Conversion Drivers identify statistically significant factors that correlate with funnel conversion or drop-off at each step. The analysis surfaces event properties, user properties, and intermediary events that influence user progression through the funnel. ![Conversion Drivers Interface](https://docs.statsig.com/images/conversion-drivers-funnels.png) To access Conversion Drivers: 1. Click on any funnel step 2. Select **"View Drop-Off & Conversion Drivers"** 3. Configure the analysis scope using the dropdown filters ![Conversion Drivers Entry Point](https://docs.statsig.com/images/conversion-drivers-context-menu.png) ### Analysis configuration You can configure which data types to include in the analysis: - **Event Properties**: Attributes attached to events (e.g., platform, plan\_type, referral\_code) - **User Properties**: User-level attributes (e.g., country, account\_age, signup\_method) - **Intermediary Events**: Events that occurred between the selected funnel steps ### Driver metrics Each identified driver displays: - **Conversion Likelihood**: A multiplier of the funnel's conversion rate (e.g., users with platform::Android are 1.2x as likely to convert) - **Conversion Rate**: Percentage of users with this factor who converted - **Participant Share**: Percentage of total funnel participants who had this factor ### Detailed analysis Click on any driver to access the drilldown view, which provides: - **Conversion Matrix**: Side-by-side comparison of conversion outcomes for users with and without the factor - **Correlation Coefficient**: Statistical measure of the factor's association with funnel completion (also known as the [phi coefficient](https://en.wikipedia.org/wiki/Phi_coefficient)) You can group the funnel by any identified driver by clicking the group by option. This reconfigures the funnel chart to show conversion performance segmented by the selected property. ### Use cases Conversion Drivers are useful for: - Exploratory analysis when investigating funnel performance without predefined hypotheses - Root cause analysis of conversions and drop-offs - Validating assumptions about user segment behavior - Monitoring funnel performance changes over time > **Note:** > > Conversion Drivers require a Pro plan subscription or Enterprise plan with the Advanced Analytics package. ================================================================================ # Retention Chart URL: https://docs.statsig.com/product-analytics/retention ================================================================================ # Retention Chart ## How Retention charts work Retention charts in Metrics Explorer help you understand how effectively your product or service maintains user interest and engagement over time. Retention charts are useful for measuring product-market fit and are critical for overall product growth. By analyzing retention patterns, you can identify whether your product or certain features resonate with your audience, and which areas need improvement. ![Retention chart interface showing user engagement over time](https://docs.statsig.com/images/product-analytics/retention/13a46b84-f1cc-4226-9876-5b314641927b.png) ### Use cases - **Long-term user engagement tracking**: Monitor retention over days, weeks, or months to understand how long users stay engaged after their initial interaction or a specific trigger event. - **Stickiness of specific features**: Identify which product features users return for. - **Sub-population analysis**: Filter your retention analysis to specific groups to compare engagement across different user segments. ## Creating a retention chart You define a retention chart with a start event, a return event, and a return window. A retention chart lets you answer the question: "For users who performed the starting event, what percentage performed the return event within the given conversion window, over successive days or weeks?" ### Step 1: Define a start event The start event (or trigger event) indicates that a user has started using the product or service. Depending on the question you want to answer, the start event is often a top-of-funnel event such as sign-up or any active event. The start event can also be an event that represents use of the feature whose retention you want to understand. To analyze the retention of a specific group of users, optionally add a filter to scope your analysis. ### Step 2: Define a return event The return event indicates that the user is getting value from your service. Depending on the question you want to answer, the return event can be returning to your product (another active event) or use of a specific feature. You can also add a filter to the selected event based on user or event properties. ### Step 3: Choose an ID type Statsig supports individual and group analytics. This lets you analyze the retention of individual users or of whole groups such as organizations or companies. ### Step 4: Choose a return time window Choose whether to measure daily or weekly retention. When you don't expect users to engage daily to count as "active", a weekly return window is more useful. A weekly window answers: "For users who perform the start event, how many perform the return event within 1 week?" Daily retention defines each cohort as users who performed the start event on a given calendar day. The chart then shows, over your selected time range (for example, 30 days), what percent of users in the cohort returned on each day. Weekly retention defines each cohort as users who performed the start event within a calendar week. Each cohort spans successive weeks. The chart then shows, over your selected time range, what percent of users in the cohort returned during each week. ### Step 5 (Optional): Choose a chart granularity for weekly retention charts When you select weekly retention, you can optionally change the chart granularity by selecting "Daily" from the granularity dropdown in the top left of the chart. Granularity is distinct from the Return Time Window. When you create a weekly retention chart with daily granularity, the chart shows, on a given day, what percent of the cohort performed the return event within the last week. For example, day 12 indicates what percent of the cohort performed the return event during the 7 days spanning day 6 through day 12, inclusive. ## Understanding a retention chart [Retention charts](https://www.youtube.com/watch?v=mqlHpYimik8) in Statsig include two main sections: the **retention graph (j-curve)** and the **retention table (triangle chart)**. ### Retention table (triangle chart) A retention table, or triangle chart, shows how well you retain users after their first interaction with your product or service. The retention table tracks cohorts of users based on their first engagement date (defined by your start event). The table shows the percentage of those users returning (defined by your return event) over subsequent days or weeks. The leftmost column identifies each cohort. Across the top are time intervals (days or weeks) after the initial engagement. Each cell shows the proportion of users from a cohort who were active at a specific time interval. A vertical analysis (looking down a column) lets you compare retention rates of different cohorts at the same lifecycle stage. A horizontal analysis (reading across a row) shows how a single cohort's retention evolves over time. High numbers in the first few columns suggest strong initial engagement; consistent percentages over longer intervals indicate successful long-term retention. Columns start at day/week 0, the earliest day/week in the time range. The rightmost column shows retention for the most recent day/week. Column behavior depends on the selected granularity: - **Daily retention**: Each column shows the percentage of the cohort that performed the return event on that calendar day. - **Weekly retention with weekly granularity**: Each column shows the percentage that performed the return event within that week. - **Weekly retention with daily granularity**: Each column shows the percentage that performed the return event on that calendar day or within the 6 days prior. ### Retention graph A retention graph plots the percentage of retained users against time. The X-axis represents time, segmented into daily or weekly intervals since the users' first interaction with the product. The Y-axis shows the percentage of the original users who remain active (performed the return event). #### Reading the graph The retention graph illustrates the rate at which users disengage over time. - A **declining curve** followed by a flattening is common. This pattern indicates a drop in user interest after the first interaction, followed by stabilization among a core user group. The higher the percentage at which the curve flattens, the better the retention health of the product. - A **smiling curve** shows an initial decline in retention followed by an upward trend at later stages. This pattern often results from successful re-engagement strategies or product improvements that bring back previously inactive users. - A **continuously declining curve** indicates a consistent loss of users over time, often pointing to issues in user satisfaction or engagement. Key aspects to observe: 1. **Initial Drop-off Rate**: The steepness of the initial decline indicates how many users stop using the service after their first experience. 2. **Long-term Engagement**: The slope in the later stages of the graph shows the long-term user engagement. A flatter slope at this stage means better user retention. 3. **Trends Over Time**: Comparing multiple graphs over different time periods can reveal the impact of product changes or external factors on retention. ## Scoping to specific cohorts By default, Statsig plots only the "All cohorts" retention curve. To scope to a single cohort, click anywhere on that cohort's row in the table. To compare multiple cohorts, use the checkboxes on the leftmost portion of the table to select the cohorts whose retention curves you want to compare. ================================================================================ # Distribution URL: https://docs.statsig.com/product-analytics/distribution ================================================================================ # Distribution ## How distribution charts work Distribution charts in Metric Explorer help you visualize the range of user experiences across your product. These charts are useful for understanding central tendencies, evaluating product health, and identifying outlying behavior. ![Distribution chart interface in Metrics Explorer](https://docs.statsig.com/images/product-analytics/distribution/b3b1507a-4a30-4a74-bc5c-8b3d08a1e64f.png) ### Use cases - **Analyze the spectrum of experiences**: Study the distribution of event values to identify any trends. - **Measure feature engagement**: Visualize how often each user is interacting with a critical event. - **Monitor product performance**: Ensure that your product isn't experiencing performance issues like unusual latency times. ## Creating a distribution chart ### Step 1: Choose a metric or event First, decide whether to use a metric or an event. The distribution of a metric shows the aggregated property value per unit ID. For example, if the metric aggregation is by count, the chart displays the number of times each user triggered the event. The distribution of an event shows the range of data stored under the **Value** property for each logged event. Statsig displays the event distribution only when the data under **Value** is numeric. ### Step 2: Refine your bucket size By default, the bucket size is 1, with a minimum value of 0 and a maximum value of 10. Buckets are always lower-inclusive and upper-exclusive. If the range exceeds the maximum bucket value, the chart shows the data as "10+". You can adjust bucket sizes, minimums, and maximums to find the best view of your data. ## Interpreting your distribution chart ### Distribution of a metric For the distribution of a metric, the chart always represents metric values per unit ID. The X-axis represents the metric value, which can be a count of events or the sum or average of a property value, depending on the metric configuration. The Y-axis represents the unit ID, which can be users, stable IDs, or a custom ID. ### Distribution of an event The distribution of an event always displays the range of data under the **Value** property. The X-axis shows the **Value** and the Y-axis shows the number of events. ================================================================================ # User Journeys URL: https://docs.statsig.com/product-analytics/user-journeys ================================================================================ # User Journeys ## How User Journeys works The User Journeys chart shows the many paths users are taking through your product so you can better understand the end-user experience. ![User journeys sankey diagram visualization](https://docs.statsig.com/images/product-analytics/user-journeys/51e0c508-45cf-4839-93a0-3bf63e4e961d.png) ### Use cases - **Event pathways**: Follow the most common paths users take through your product. - **Identifying drop-off points**: Pinpoint where users drop off within key product flows. - **Discovering unexpected behavior**: Uncover surprising usages and iterate on your product. ## Creating a user journeys chart ### Step 1: Choose a starting or ending event Choose whether to explore a journey that starts or ends with a specific event. Starting events are often top-of-funnel events such as sign-up or log-in, but can also be an event trigger for any new feature you introduce into your product. Ending events let you understand where users came from before reaching a specific point. You can optionally add filters to scope your analysis to a specific group. ### Step 2: Choose an ID type Statsig supports individual and group analytics. This lets you analyze the paths of registered users with User IDs, Stable IDs, or your own custom IDs. ### Step 3: Define your measurement criteria Under the "Measured as" section, choose between total conversions or unique conversions. Under total conversions, users can re-enter the flow each time they trigger the start event. Under unique conversions, each user appears in the path only once. You can also specify the observation duration. The observation duration defaults to 1 hour, but you can change the length of time users have to convert to the next event. Adjusting this value helps validate whether users are passing through flows at the pace you expect. To add more context, break the User Journey out by an event property. Select a specific event property to view the user journey expanded by its different property values (similar to a group-by). For example, you can view user journeys split by operating system. You can also filter out user paths that include a specified event. After editing the measurement criteria, click **Run Query** to apply your selections. ### Step 4: Adjust your chart visualization At the top bar of the chart, you can edit the conversion percent threshold, hide events, and expand your time window. The conversion percent threshold sets the minimum percentage of conversions needed to count as relevant. Statsig consolidates events below the threshold under "Others". The **Hide Events** selector lets you filter out events you don't want to see. The time selector lets you view user journeys during the time window you care about most. ## Using User Journeys After selecting your start event, a sankey diagram shows all the next steps users took. Click any node to display the next events users triggered. Each event shows the total number of events counted and the percentage of users who triggered it. Continue clicking nodes to explore user flows through your product. ================================================================================ # Lifecycle URL: https://docs.statsig.com/product-analytics/lifecycle ================================================================================ # Lifecycle ## How Lifecycle charts work Lifecycle charts in Metrics Explorer help you understand how usage changes over time. These charts classify your unique units (for example, user\_id) within each time interval based on whether the units used an event recently, returned after a gap, continued to use the event, or churned. ![Life Cycle chart interface in Metrics Explorer](https://docs.statsig.com/images/product-analytics/lifecycle/lifecycle_demo_v4.png) ### Use cases - **Track new-user ramp after a launch**: See whether adoption is growing week over week after shipping a new feature. - **Monitor churn and reactivation**: Understand whether users are falling off and whether they return. - **Compare retention health across releases**: Spot changes in retention and reactivation patterns over time. ## Creating a lifecycle chart ### Step 1: Choose an event (or a compatible metric) Decide whether to use a metric or an event. Lifecycle works with a single underlying event and count-style metrics composed of a single count-type event. ### Step 2: Choose your unit (unique units) Select what you want to count uniquely (for example user\_id, stable\_id, or another unit). The chart reports how many unique units fall into each category for each time interval. ### Step 3: Choose your interval (granularity) Pick an interval unit (day / week / month) and a number of intervals per bucket (1–48). Each bar on the chart represents one interval bucket, and the chart shows one data point per bucket across the selected date range (max 1 year). ![Life Cycle chart interface in Metrics Explorer](https://docs.statsig.com/images/product-analytics/lifecycle/lifecycle_interval_selector.png) ### Step 4: (Optional) Add filters Apply filters to focus on a specific segment (for example platform, country, app version, or a feature-related property). ## Interpreting your lifecycle chart Each interval bucket classifies unique units into four categories (mutually exclusive): **New**: Used during this interval and didn't use at any point earlier within the lookback window (up to 1 year before this interval). **Resurrected**: Used during this interval, didn't use in the immediately previous interval, and used earlier within the lookback window. **Recurring**: Used during this interval and the immediately previous interval. **Dormant**: Used in the immediately previous interval, but not during this interval (Statsig displays this below the axis to make churn visually apparent). ### Reading the chart **X-axis**: Time, grouped into your chosen interval buckets. **Y-axis**: Count of unique units. **Stacked bars**: Show how the composition of usage changes over time (new vs. resurrected vs. recurring), while the dormant component highlights drop-off between adjacent intervals. ================================================================================ # Dashboards URL: https://docs.statsig.com/product-analytics/dashboards ================================================================================ # Dashboards Dashboards bring the charts, metrics, experiments, and feature gates you care about into one view that your team can share, save, and revisit. Use a dashboard to track long-term product health, monitor a feature launch, or send stakeholders a recurring snapshot of the metrics that matter. You can start from a Statsig template or build one from scratch. ## Creating a dashboard There are two ways to create a dashboard: 1. Navigate to the _Dashboards_ tab and click **Create**. You can choose one of Statsig's [Dashboard Templates](#dashboard-templates) or create a custom dashboard. ![Dashboard creation interface](https://docs.statsig.com/images/product-analytics/dashboards/15696f0e-17b8-4413-a5fe-ab68f6c5c7c7.png) 2. You can also create a dashboard directly from Metrics Explorer. To do this, after you finish building a chart: 1. Click **Export to Dashboard** at the top right corner of the chart. 2. Name the chart. 3. Select **Create New Dashboard** from the Dashboard Destination selector. 4. Give your new dashboard a name. ![Export to dashboard from Metrics Explorer](https://docs.statsig.com/images/product-analytics/dashboards/012d7dc0-a09b-4424-af10-ab8a714040cb.png) ### Adding charts, feature gates, and experiments to a dashboard Dashboards help teams share and review product insights. You can add Metric Charts and track ongoing Pulse results from A/B tests and feature launches. There are several types of dashboard widgets you can add or create including: - **Charts**: Create a new chart directly from a dashboard or export a chart created in Metrics Explorer to a dashboard. Supported charts include: - Drilldown Charts - Funnel Charts - Retention Charts - Distribution Charts - User Journey Charts - **Text**: Annotate dashboards with context or create section headers for better readability. - **Single Value**: Highlight a hero metric with clarity by adding a single value to the dashboard. - **Experiment, Feature Flag**: Get a quick snapshot of an experiment or feature flag. - **Funnel Metrics**: Visualize custom funnel metrics. ### To add a widget to a dashboard 1. Click **Add Widget**. 2. Select the type of widget you want to add. 3. Configure the widget, for example select a chart type and then select events and metrics you want to track. 4. Save the widget to the dashboard. ## Exploring your dashboard ### Edit date ranges By default, Statsig syncs charts and widgets on a dashboard with the date range set for the entire dashboard. To update this default date range, click the pencil icon in the top right corner. In the settings panel, you can modify the dashboard's title, description, and **Default Date Lookback Range**. Statsig applies this range automatically each time you open the dashboard. If you choose **Chart Default**, each chart uses the date range originally set when you first added the chart to the dashboard. ![Dashboard settings and date range configuration](https://docs.statsig.com/images/product-analytics/dashboards/a89fc3b7-48f6-40b2-a226-11c925553f14.png) You can also change the date range dynamically by modifying the date picker at the top right of the dashboard. Changes to this selector synchronize all charts and widgets on the dashboard. Statsig doesn't save these changes when you reopen the dashboard. ![Dashboard date picker interface](https://docs.statsig.com/images/product-analytics/dashboards/1c038930-f9bd-4d94-9bb4-4ba84a417dda.png) ### Exporting your dashboard To share a static version, print, or save your dashboard, click the settings dropdown (**...**) in the top right corner and select **Export as PDF**. Statsig generates a PDF of the dashboard and downloads it automatically within a few seconds. ![Export dashboard menu](https://docs.statsig.com/images/product-analytics/dashboards/37e8b00d-981e-4bc2-a375-a975b6d4d302.png) ### Cloning your dashboard To duplicate a dashboard, open it, click the settings dropdown (**...**) in the top right corner, and select **Clone**. A dialog appears to confirm the clone. After cloning, Statsig takes you to the new dashboard. ![Dashboard clone dialog](https://docs.statsig.com/images/product-analytics/dashboards/abf7b681-5859-4a0e-b63e-d6fe16ea6e77.png) ### Filtering your dashboard Select the filters button below the dashboard name to add a global filter. The filter applies across all eligible widgets, so you can view updated results without filtering each widget individually. You can also use free-form text to apply generic filters, such as filtering emails that contain `@gmail.com`. When you expand a dashboard widget that has a dashboard filter applied, the filter appears as an **Inherited Dashboard filter**. Any changes you make at the widget level are temporary and Statsig doesn't save them. ![Dashboard global filter interface](https://docs.statsig.com/images/product-analytics/dashboards/397d0197-632d-4f25-a8be-a5413575173f.png) #### Default dashboard filters Default dashboard filters let you pin commonly used filters directly to your dashboards. These filters appear at the top of the dashboard and apply across all eligible widgets, enabling quick comparisons across dimensions like company, region, or platform, without rebuilding filters from scratch. To configure default dashboard filters: 1. Navigate to your dashboard and click the settings cog ⚙️ 2. Scroll to **Default Filters** and configure the filters you want to pin to the dashboard. 3. Click **Save**. After configuration, the pinned filters appear at the top of the dashboard. You can swap filter values to see how different users, cohorts, or properties affect the same set of charts. When you change a filter value, all charts update automatically. Dynamic filtering lets you reuse the same dashboard instead of duplicating dashboards or manually editing each widget's filters. ### Refreshing your dashboard widgets To ensure your dashboard data is up to date, you can refresh dashboard widgets in several ways: **Manual Refresh**: Click the refresh button shown below to refresh all dashboard widgets at once. ![Dashboard refresh button](https://docs.statsig.com/images/product-analytics/dashboards/2799df0e-2a71-454b-8fee-df0420cdf68b.png) **Automatic dashboard refreshes**: Statsig can automatically refresh dashboards on a schedule. Statsig caches results for faster loading. You can configure a refresh frequency for each dashboard (for example, hourly or daily). Queries for that dashboard run on the specified schedule and store the results. When someone opens the dashboard, the most recent cached data appears immediately without triggering fresh queries. To configure automatic dashboard refreshes: 1. Navigate to your dashboard and click the settings cog. 2. Scroll to **Schedule Dashboard Refresh** and set the interval. 3. Click **Save**. This feature is useful for shared dashboards or recurring check-ins where fresh data should be ready without manual effort. ### Dashboard subscriptions Dashboard subscriptions send a scheduled snapshot of a dashboard to your team so stakeholders can stay up to date without opening Statsig. #### What gets delivered A subscription delivers a snapshot of the dashboard at send time, including: - Dashboard title and link - All widgets currently on the dashboard - The dashboard’s default date range (and any pinned default dashboard filters, if configured) Depending on your workspace setup, Statsig can deliver subscriptions by email and/or Slack. #### Creating a subscription 1. Open the dashboard you want to subscribe to. 2. Click the settings menu (**...**) in the top right corner. 3. Select **Add/Manage Dashboard Subscription**. 4. Configure your delivery channel (email, Slack), recipients (emails or Slack channel), and schedule (for example, daily or weekly). 5. Click **Save**. ### Organize your dashboard A well-organized dashboard conveys what information is most important and shows the relationship between items. You can move and resize dashboard widgets in place. Each dashboard uses a grid layout. To move a widget, click and hold empty space on the widget and drag it to the target position. To resize a widget, click and hold the bottom right edge and drag to the target size. ### View and edit a chart in a dashboard You can add any chart supported in Metrics Explorer to a dashboard. Dashboard charts are interactive, not static. To explore a chart on the dashboard, click the **\[ \]** icon. When expanded, you have access to the full Metrics Explorer and can modify the query, date range, and chart title. These changes are for exploration only and don't permanently alter the chart on the dashboard. To save changes, configure the chart and click **Save** to update the existing chart, or **Save As** to create a new chart on the dashboard. ![Chart editing interface in dashboard](https://docs.statsig.com/images/product-analytics/dashboards/aa563da7-eab1-4578-a081-1ad1f343cc5c.png) ## Tips ### Dashboard templates Dashboard templates reduce time to insights. Statsig compiles industry-standard metrics so your data visualization focuses on critical success indicators. You can start with a template and add additional charts as needed. Statsig offers the following templates: - Product Growth - Use Statsig's built-in metrics like DAU, WAU, Stickiness, etc. to track long-term product health - Feature Success - Input a feature usage event, like form\_submit or purchase\_completed, to evaluate the success of your feature rollout with usage and retention metrics - Optionally, you can add a feature adoption event or related feature flag to broaden the scope of your tracking - B2B SaaS Topline Metrics - Input a key feature event and user subscription events to monitor product usage, user retention and subscription conversion rates over time - Web Analytics - Available with Autocapture, track essential web metrics like page views, clicks, and sessions duration. Go to the [Autocapture guide](https://docs.statsig.com/guides/sidecar-experiments/measuring-experiments#using-autocapture) for more information. - Create from Gate or Experiment - Input your Gate or Experiment of interest to generate a focused dashboard with related monitoring metrics - Create from Tag - Utilize Statsig's project tagging to create and easily maintain a dashboard with the metrics, experiments, and feature flags you care about ### Finding dashboards After you create a dashboard, the _Dashboards_ tab offers several ways to find it: 1. In the _Dashboards_ tab, click the search box and select **My dashboards** to find dashboards you created. 2. In the _Dashboards_ tab, click the filter icon to scope to dashboards with specific tags or created by specific team members. 3. In the _Dashboards_ tab, search for the dashboard name. 4. Anywhere in Statsig, open global search with **cmd+k** and type the dashboard name. ================================================================================ # Users Tab URL: https://docs.statsig.com/product-analytics/users-tab ================================================================================ # Users Tab ## How the Users Tab works The Users section of Statsig gives you an event-by-event level understanding of how users (and other Unit IDs) use your product. This granular view lets you diagnose issues and understand user behavior using event logs, session streams, and session replays. The Users section is also a central place to manage feature rollout and experiment overrides. ## Exploring the Users Tab When you open the Users tab, enter a specific ID and select the matching Unit ID type. There are also many context-specific entry points to the Users Tab within Statsig. A Users Tab query surfaces the following information: - **Properties**: Additional context for this ID, including email, country, OS, and browser. Customers with user profiles can see all user profile properties for a given ID. - **Log History & Event Details**: History of events and exposures for this ID, limited to 5000 rows. You can view these as an event log stream or a session stream. - **Overrides**: The ability to manually override an ID into a given feature gate or experiment variant. - **Session Replays**: A sample of session replays the user has triggered. ## Events ### Log Streams Under the Events tab, you can view the events and exposures this user triggered in their event log stream. From here, you can diagnose which features this user was most interested in or which experiment group they were in. ![Event log stream interface](https://docs.statsig.com/images/product-analytics/users-tab/1ff4af6a-c467-4dc1-8b9e-fb58818cb67b.png) ### Session Streams Switch from **Log Stream** to **Session Stream** to get a session-centric view of all events the user triggered during each session. You can refine either view by changing the time window, hiding events, and filtering to show only events or experiment/gate exposures. ![Session stream interface showing user events grouped by session](https://docs.statsig.com/images/product-analytics/users-tab/7ac4a9f8-a3d4-485b-9a8a-8ce972ba6cda.png) ## Overrides Under the Overrides tab, you can override an ID into a given experiment variant or feature gate rollout. If there's already an active override for an ID on a particular entity, it appears in this section and you can modify it inline. Overrides set in the Users Tab sync to the "Overrides" section of the relevant entity, and you can edit or remove them from either interface. ## Session Replays Under Session Replays, you can navigate to a sample of session replays the user has triggered for additional insight into their behavior. For more information, refer to [Session Replays](https://docs.statsig.com/session-replay/overview). ================================================================================ # Infra Analytics Overview URL: https://docs.statsig.com/infra-analytics/overview ================================================================================ # Infra Analytics Overview [Infra Analytics](https://statsig.com/infra-analytics) pulls in logs, metrics, and alerts so you get system-level observability in the same place you analyze product outcomes. - Collect metrics and traces through OpenTelemetry (OTEL) - Search and analyze logs to investigate issues - Create alerts tied to service health - Connect infrastructure signals to product analytics for a unified understanding of impact ## Key features - **Logs Explorer**: Debug incidents with search, filters, and visualizations - **Topline Alerts**: Catch regressions and anomalies with log/metric-based triggers - **Metrics Explorer**: Inspect infrastructure metrics alongside product metrics --- ## Set up Infra Analytics - [Set up OTEL ingestion](https://docs.statsig.com/infra-analytics/getting-started) to start sending logs and metrics - Traces are in limited preview: contact Statsig in Slack to request access ================================================================================ # Getting Started with OTEL + Statsig URL: https://docs.statsig.com/infra-analytics/getting-started ================================================================================ # Getting Started with OTEL + Statsig Send OpenTelemetry (OTel) telemetry to Statsig so you can use Infra Analytics: Logs Explorer, Metrics Explorer, and Alerts. There are two common paths: - Kubernetes/OpenTelemetry Collector: scrape logs and metrics from your cluster and export to Statsig. Go to [Open Telemetry Logs and Metrics](https://docs.statsig.com/server/concepts/open_telemetry) for a more complete guide. - Applications: export traces, metrics, and logs to your OpenTelemetry Collector (or traces directly from TypeScript/Node). Go to the quick starts below. > **Info:** > > **Endpoint & Auth** > > - Endpoint: `https://api.statsig.com/otlp` > - Auth header: `statsig-api-key: ` > **Info:** > > Statsig supports direct trace export to its OTLP endpoint only for TypeScript/Node. For all other languages, send traces to your OpenTelemetry Collector and forward from the Collector to Statsig over OTLP/HTTP. > **Info:** > > Need a deeper setup guide? Go to [Open Telemetry Logs and Metrics](https://docs.statsig.com/server/concepts/open_telemetry) for collector installation and configuration, and the [Traces Explorer quick start](https://docs.statsig.com/infra-analytics/send-traces) for language-specific trace examples. --- ## Application telemetry quick starts #### Node.js Install dependencies: ```bash npm install --save \ @opentelemetry/sdk-node \ @opentelemetry/auto-instrumentations-node \ @opentelemetry/exporter-trace-otlp-http \ @opentelemetry/exporter-metrics-otlp-http \ @opentelemetry/api-logs \ @opentelemetry/sdk-logs \ @opentelemetry/exporter-logs-otlp-http \ @opentelemetry/resources \ @opentelemetry/semantic-conventions ``` Initialize OpenTelemetry (e.g., `instrumentation.js`): ```js // instrumentation.js const { NodeSDK } = require('@opentelemetry/sdk-node'); const { resourceFromAttributes } = require('@opentelemetry/resources'); const { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } = require('@opentelemetry/semantic-conventions'); // import if you want to enable traces const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http'); const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http'); const { PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics'); const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node'); // For troubleshooting, set the log level to DiagLogLevel.DEBUG // const { diag, DiagConsoleLogger, DiagLogLevel } = require('@opentelemetry/api'); // diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG); const statsigKey = process.env.STATSIG_SERVER_SDK_SECRET; const headers = { 'statsig-api-key': statsigKey ?? '' }; const sdk = new NodeSDK({ resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'statsig-node-service', [ATTR_SERVICE_VERSION]: process.env.VERSION || '1', env: process.env.NODE_ENV || 'development', }), traceExporter: new OTLPTraceExporter({ url: 'https://api.statsig.com/otlp/v1/traces', // or // url: /v1/traces headers, }), metricReader: new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter({ url: 'https://api.statsig.com/otlp/v1/metrics', // or // url: /v1/metrics headers, }), exportIntervalMillis: 60000, }), instrumentations: [getNodeAutoInstrumentations()], }); sdk.start(); ``` To set up application logs with OTel, use the pino or winston bridges. The example below uses [pino](https://getpino.io/#/) with [pino auto instrumentation](https://www.npmjs.com/package/@opentelemetry/instrumentation-pino). Install the pino instrumentation: ```bash npm i pino @opentelemetry/instrumentation-pino ``` ```js // instrumentation.js (continued) const { BatchLogRecordProcessor } = require('@opentelemetry/sdk-logs'); const statsigKey = process.env.STATSIG_SERVER_SDK_SECRET; const headers = { 'statsig-api-key': statsigKey ?? '' }; const sdk = new NodeSDK({ // ... other config ... logRecordProcessors: [ new BatchLogRecordProcessor( new OTLPLogExporter({ url: 'https://api.statsig.com/otlp/v1/logs', // or // url: /v1/logs headers }) ), ], instrumentations: [getNodeAutoInstrumentations(), new PinoInstrumentation()], }); // in your application code, e.g., app.js const pino = require('pino'); const logger = pino(); logger.info('OTel logs initialized'); ``` The Statsig SDK also supports forwarding logs to Log Explorer. Go to the alternative logging example below. ```js // Requires: npm i @statsig/statsig-node-core const { Statsig, StatsigUser } = require('@statsig/statsig-node-core'); const s = new Statsig(process.env.STATSIG_SERVER_SDK_SECRET); await s.initialize(); const user = new StatsigUser({ userID: 'a-user', custom: { service: process.env.OTEL_SERVICE_NAME || 'my-node-service' }, }); // levels: trace, debug, info, log, warn, error s.forwardLogLineEvent(user, 'info', 'service started', { version: process.env.npm_package_version }); try { // your app code } catch (err) { s.forwardLogLineEvent(user, 'error', 'unhandled error', { message: String(err?.message || err), stack: err?.stack, }); } ``` Run your service: Require or import `instrumentation.js` before any other application code to ensure instrumentation sets up correctly. ```bash STATSIG_SERVER_SDK_SECRET=YOUR_SECRET \ OTEL_SERVICE_NAME=my-node-service \ node -r ./instrumentation.js app.js ``` Tip: you can configure exporters through environment variables instead of code: - `OTEL_EXPORTER_OTLP_ENDPOINT=https://api.statsig.com/otlp` - `OTEL_EXPORTER_OTLP_HEADERS=statsig-api-key=${STATSIG_SERVER_SDK_SECRET}` - `OTEL_EXPORTER_OTLP_PROTOCOL=http/json` #### Next.js Go to the official Next.js OpenTelemetry instructions for [pages router](https://nextjs.org/docs/pages/guides/open-telemetry) and for [app router](https://nextjs.org/docs/app/guides/open-telemetry). Install dependencies: ```bash npm install @opentelemetry/sdk-node @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/sdk-trace-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/auto-instrumentations-node ``` Add `instrumentation.ts` at the app root (Next 13+): ```ts // instrumentation.ts import { NodeSDK } from '@opentelemetry/sdk-node'; import { resourceFromAttributes } from '@opentelemetry/resources'; import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'; // For troubleshooting, set the log level to DiagLogLevel.DEBUG // const { diag, DiagConsoleLogger, DiagLogLevel } = require('@opentelemetry/api'); // diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG); export async function register() { const headers = { 'statsig-api-key': process.env.STATSIG_SERVER_SDK_SECRET ?? '' }; const sdk = new NodeSDK({ resource: new Resource({ [ATTR_SERVICE_NAME]: process.env.OTEL_SERVICE_NAME || 'statsig-node-service', [ATTR_SERVICE_VERSION]: process.env.VERSION || '1', env: process.env.NODE_ENV || 'development', }), traceExporter: new OTLPTraceExporter({ url: 'https://api.statsig.com/otlp/v1/traces', // or // url: /v1/traces headers, }), metricReader: new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter({ url: 'https://api.statsig.com/otlp/v1/metrics', // or // url: /v1/metrics headers, }), exportIntervalMillis: 60000, }), instrumentations: [getNodeAutoInstrumentations()], }); sdk.start(); } ``` To set up application logs with OTel, use the pino or winston bridges. The example below uses [Pino](https://getpino.io/#/) with [Pino auto instrumentation](https://www.npmjs.com/package/@opentelemetry/instrumentation-pino). Install the pino instrumentation: ```bash npm i pino @opentelemetry/instrumentation-pino ``` ```js // instrumentation.ts (continued) import { BatchLogRecordProcessor } from '@opentelemetry/sdk-logs'; const statsigKey = process.env.STATSIG_SERVER_SDK_SECRET; const headers = { 'statsig-api-key': statsigKey ?? '' }; const sdk = new NodeSDK({ // ... other config ... logRecordProcessors: [ new BatchLogRecordProcessor( new OTLPLogExporter({ url: 'https://api.statsig.com/otlp/v1/logs', // or // url: /v1/logs headers }) ), ], instrumentations: [getNodeAutoInstrumentations(), new PinoInstrumentation()], }); // in your application code, e.g., app.ts import pino from 'pino'; const logger = pino(); logger.info('OTel logs initialized'); ``` The Statsig SDK also supports forwarding logs to Log Explorer. Go to the alternative logging example below. ```js // Requires: npm i @statsig/statsig-node-core import { Statsig, StatsigUser } from '@statsig/statsig-node-core'; const s = new Statsig(process.env.STATSIG_SERVER_SDK_SECRET); await s.initialize(); const user = new StatsigUser({ userID: 'a-user', custom: { service: process.env.OTEL_SERVICE_NAME || 'my-node-service' }, }); // levels: trace, debug, info, log, warn, error s.forwardLogLineEvent(user, 'info', 'service started', { version: process.env.npm_package_version }); try { // your app code } catch (err) { s.forwardLogLineEvent(user, 'error', 'unhandled error', { message: String(err?.message || err), stack: err?.stack, }); } ``` > **Note:** > > In Next.js, mark '@statsig/statsig-node-core' as a server external package in `next.config.js` to avoid bundling. ### Using the Statsig + Vercel integration If you deploy to Vercel, use the [Statsig + Vercel integration](https://docs.statsig.com/integrations/vercel/) to forward logs to Statsig automatically. > **Note:** > > - Keep `STATSIG_SERVER_SDK_SECRET` out of client bundles (do not use `NEXT_PUBLIC_`). > - Client/browser tracing requires separate web tracer setup; do not send secrets client-side. Consider routing through a Collector. #### Other Languages/Frameworks Statsig supports sending OTLP data directly (without a collector) only for Node.js applications. For other languages and frameworks, send OTLP data to a collector and configure the collector to forward data to Statsig. Go to the [Collector quick starts](#collector-quick-starts) below for example configurations. For installation and configuration instructions for other languages and frameworks, go to the [OpenTelemetry Language APIs & SDKs documentation](https://opentelemetry.io/docs/languages/). --- ## Collector quick starts Running a Collector is optional, but Statsig recommends it for production workloads. Use the OpenTelemetry Collector as a gateway to receive OTLP from your applications and forward to Statsig. A Collector gateway is useful for centralizing telemetry collection, adding advanced sampling methods like tail-based sampling, or scraping logs and metrics from hosts or Kubernetes. #### Kubernetes (Helm) Create a minimal `values.yaml` for the OpenTelemetry Collector that forwards all signals (traces, metrics, logs) to Statsig: ```yaml config: receivers: otlp: protocols: http: grpc: processors: batch: {} exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} service: pipelines: traces: receivers: [otlp] processors: [batch] exporters: [otlphttp] metrics: receivers: [otlp] processors: [batch] exporters: [otlphttp] logs: receivers: [otlp] processors: [batch] exporters: [otlphttp] ``` Install the Collector with Helm: ```bash helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts helm repo update helm install otel-gateway open-telemetry/opentelemetry-collector \ -n otel --create-namespace \ -f values.yaml ``` Provide the Statsig key as an environment variable to the Collector pods (for example, through a Secret and envFrom). Your applications then send OTLP to the in-cluster Collector endpoint (for example `http://otel-gateway-collector.otel.svc.cluster.local:4318`). For a production setup that also scrapes Kubernetes logs and metrics, go to the full guide: [Open Telemetry Logs and Metrics](https://docs.statsig.com/server/concepts/open_telemetry). > **Note:** > > **Version requirement** > > The `encoding: json` option in the OTLP HTTP exporter requires Collector v0.95.0 or newer. If you pin the image through Helm values, set `image.tag: "0.95.0"` (or newer). #### Docker (Compose) Use Docker Compose to run a Collector gateway that accepts OTLP and forwards to Statsig. ```yaml services: otel-collector: image: otel/opentelemetry-collector-contrib:latest command: ["--config=/etc/otel-collector-config.yaml"] environment: - STATSIG_SERVER_SDK_SECRET=${STATSIG_SERVER_SDK_SECRET} volumes: - ./otel-collector-config.yaml:/etc/otelcol-contrib/config.yaml ports: - "4317:4317" # OTLP gRPC - "4318:4318" # OTLP HTTP ``` Create the Collector config referenced above: ```yaml receivers: otlp: protocols: http: grpc: processors: batch: {} exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} service: pipelines: traces: receivers: [otlp] processors: [batch] exporters: [otlphttp] metrics: receivers: [otlp] processors: [batch] exporters: [otlphttp] logs: receivers: [otlp] processors: [batch] exporters: [otlphttp] ``` Start the Collector: ```bash export STATSIG_SERVER_SDK_SECRET=YOUR_SECRET docker compose up -d ``` Point your applications at the Collector: `http://localhost:4318` (or `http://otel-collector:4318` from other compose services). The Collector forwards telemetry to Statsig using your key. #### Other You can run the Collector in other environments (VMs, bare metal) using the config below. Go to the [Collector documentation](https://opentelemetry.io/docs/collector/installation/) for other installation and deployment methods. ```yaml exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} ``` --- ## Common Collector configs (K8s & Docker) The following examples show popular receivers and processors you can enable in your Collector and still export to Statsig through the same `otlphttp` exporter. > **Note:** > > These components live in the contrib distribution. Use an image that includes them: > > - Docker: `otel/opentelemetry-collector-contrib` or newer > - Helm: set `image.repository: otel/opentelemetry-collector-contrib` (and a compatible `image.tag`) Helm values (contrib image): ```yaml image: repository: otel/opentelemetry-collector-contrib tag: "latest" pullPolicy: IfNotPresent ``` ### A. File logs (filelog receiver) Reads and parses logs from files on disk. The filelog receiver is useful for hosts, containers, or Kubernetes nodes. Minimal example: ```yaml receivers: filelog: include: [ /var/log/myservice/*.json ] start_at: beginning operators: - type: json_parser timestamp: parse_from: attributes.time layout: '%Y-%m-%dT%H:%M:%S%z' processors: batch: {} exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} service: pipelines: logs: receivers: [filelog] processors: [batch] exporters: [otlphttp] ``` Kubernetes tip: to tail container logs on nodes, mount host paths (for example, `/var/log/pods` and `/var/lib/docker/containers`) into the Collector DaemonSet and set `include` to those paths. ### B. EC2 resource detection (resourcedetection processor) Automatically adds AWS EC2 metadata (cloud provider, region/zone, instance ID) to your telemetry. ```yaml processors: resourcedetection/ec2: detectors: [env, ec2] timeout: 2s override: false service: pipelines: traces: receivers: [otlp] processors: [resourcedetection/ec2, batch] exporters: [otlphttp] metrics: receivers: [otlp] processors: [resourcedetection/ec2, batch] exporters: [otlphttp] logs: receivers: [otlp] processors: [resourcedetection/ec2, batch] exporters: [otlphttp] ``` The Collector must be able to reach the EC2 metadata service (IMDS). Ensure network access to `169.254.169.254` and IMDSv2 where required. ### C. Docker container metrics (docker\_stats receiver) Emits container CPU, memory, network, and block I/O metrics by querying the Docker daemon. ```yaml receivers: docker_stats: endpoint: unix:///var/run/docker.sock collection_interval: 15s processors: batch: {} exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} service: pipelines: metrics: receivers: [docker_stats] processors: [batch] exporters: [otlphttp] ``` Requirements: - Linux only (doesn't work on macOS or Windows). - Mount the Docker socket into the Collector container: `/var/run/docker.sock`. --- ## Related resources - OpenTelemetry Collector: https://opentelemetry.io/docs/collector/ - Kubernetes Collector components: https://opentelemetry.io/docs/platforms/kubernetes/collector/components/ - Helm chart: https://github.com/open-telemetry/opentelemetry-helm-charts - Collector configuration reference: https://opentelemetry.io/docs/collector/configuration - OTLP protocol specification: https://opentelemetry.io/docs/specs/otlp/ - Filelog receiver (contrib): https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/filelogreceiver - Resource detection processor (contrib): https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/processor/resourcedetectionprocessor - Docker stats receiver (contrib): https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/dockerstatsreceiver - Collector contrib distribution: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib ================================================================================ # Traces Explorer Quick Start URL: https://docs.statsig.com/infra-analytics/send-traces ================================================================================ # Traces Explorer Quick Start Send traces to Statsig's Traces Explorer by exporting your spans over OTLP/HTTP. TypeScript and Node apps can post directly to Statsig's API; for every other language, you route spans through an OpenTelemetry Collector and configure the Collector to forward the spans to Statsig. > **Info:** > > To set up Logs and Metrics as well, go to [Getting Started](https://docs.statsig.com/infra-analytics/getting-started) for more in-depth OpenTelemetry Collector setup instructions. Use the OTLP/HTTP traces endpoint to forward spans into Traces Explorer. Authenticate using your Server Secret key in the header: - Endpoint: `https://api.statsig.com/otlp/v1/traces` - Header: `statsig-api-key: ` > **Note:** > > Statsig supports direct to API for TypeScript/Node only. For all other languages, send traces to your OpenTelemetry Collector and configure it to forward to Statsig over OTLP/HTTP. For non-TypeScript apps, point your Collector (for example, `http://localhost:4318/v1/traces`) to Statsig by configuring the Collector to forward traffic to Statsig: ```yaml receivers: otlp: protocols: http: exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} service: pipelines: traces: receivers: [otlp] exporters: [otlphttp] ``` #### TypeScript/Node ```bash npm install @opentelemetry/sdk-node @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources @opentelemetry/semantic-conventions @opentelemetry/api ``` ```js // trace.js const { NodeSDK } = require('@opentelemetry/sdk-node'); const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http'); const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base'); const { Resource } = require('@opentelemetry/resources'); const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions'); const { trace } = require('@opentelemetry/api'); const sdk = new NodeSDK({ resource: new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: 'trace-sample-node', }), spanProcessor: new BatchSpanProcessor( new OTLPTraceExporter({ url: 'https://api.statsig.com/otlp/v1/traces', headers: { 'statsig-api-key': process.env.STATSIG_SERVER_SDK_SECRET || '' }, }), ), }); sdk.start().then(() => { const tracer = trace.getTracer('example'); const span = tracer.startSpan('do-work'); span.setAttribute('example', true); span.end(); setTimeout(() => sdk.shutdown(), 1000); }); ``` #### Python ```bash pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http ``` ```python # trace.py from opentelemetry import trace from opentelemetry.sdk.resources import Resource from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter trace.set_tracer_provider( TracerProvider(resource=Resource.create({"service.name": "trace-sample-python"})) ) exporter = OTLPSpanExporter( endpoint="http://localhost:4318/v1/traces", # your Collector ) trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(exporter)) tracer = trace.get_tracer(__name__) with tracer.start_as_current_span("do-work") as span: span.set_attribute("example", True) trace.get_tracer_provider().shutdown() ``` #### Go ```bash go get go.opentelemetry.io/otel/sdk go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp go.opentelemetry.io/otel/semconv/v1.26.0 ``` ```go // main.go package main import ( "context" "log" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp" "go.opentelemetry.io/otel/sdk/resource" sdktrace "go.opentelemetry.io/otel/sdk/trace" semconv "go.opentelemetry.io/otel/semconv/v1.26.0" ) func main() { ctx := context.Background() exporter, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpointURL("http://localhost:4318/v1/traces"), // your Collector ) if err != nil { log.Fatal(err) } tp := sdktrace.NewTracerProvider( sdktrace.WithBatcher(exporter), sdktrace.WithResource(resource.NewWithAttributes( semconv.SchemaURL, semconv.ServiceNameKey.String("trace-sample-go"), )), ) otel.SetTracerProvider(tp) tracer := otel.Tracer("example") ctx, span := tracer.Start(ctx, "do-work") span.SetAttributes(attribute.Bool("example", true)) span.End() _ = tp.Shutdown(ctx) } ``` > **Info:** > > For collector installation and configuration, go to [Open Telemetry Logs and Metrics](https://docs.statsig.com/server/concepts/open_telemetry). For full Logs and Metrics setup, go to [Getting Started](https://docs.statsig.com/infra-analytics/getting-started). ================================================================================ # Logs Explorer Overview URL: https://docs.statsig.com/infra-analytics/logs-explorer ================================================================================ # Logs Explorer Overview Logs Explorer lets you query logs, traces, and ingested events from a single interface. Use it the same way whether you’re debugging infrastructure issues or investigating product event streams. - **Search**: Slice logs down to only what's relevant (by service, host, status code, etc.) - **Group**: Aggregate logs by dimensions like region, status, or browser. - **Visualize**: Plot log groupings over time to spot spikes, regressions, or anomalies instantly. --- ### Getting started with Log Explorer To get started with Log Explorer, follow the [OTEL onboarding guide](https://docs.statsig.com/infra-analytics/getting-started) to set up log ingestion. After you configure log ingestion, navigate to _Infra Analytics > Log Explorer_ from the Statsig left menu. You can also use Logs Explorer in [Events Mode](https://docs.statsig.com/infra-analytics/events-mode-logs-explorer) to search and analyze your existing Statsig Events, with no additional instrumentation needed. You can switch between Logs and Events mode using the dropdown left of the search bar. ![Logs Explorer Switch Mode](https://docs.statsig.com/images/infra-analytics/lex-toggle.png) --- ### Searching in Logs Explorer - **Write custom queries**: Refer to the [syntax guide](https://docs.statsig.com/infra-analytics/logs-explorer-queries) to craft your search. - **Using the query builder**: Point-and-click to construct filters without syntax overhead. ![Logs Explorer Overview](https://docs.statsig.com/images/infra-analytics/logs-explorer-1.png) --- ### Download log results Export your query results to a file when you need to share findings or run them through a script. The **Download** button lives in the Logs Explorer toolbar, in the top-right corner next to the settings gear. Downloads work in both Logs and Events mode. To download results: 1. Run your query. 2. Open the **Download** menu from the toolbar. 3. Choose a format and row cap, then start the download. A progress indicator shows the export as it runs, and you can cancel mid-download. #### Formats - **CSV**: Columns match the visible table. The download excludes hidden columns, so the file reflects what you see on screen. - **JSONL**: Emits one full log object per line, which works well with tools like `grep` and `jq`. #### Row caps Choose a cap of 100, 1,000, or 10,000 rows. The default is 1,000; select 10,000 for heavier pulls. ================================================================================ # Events Overlays in Logs Explorer URL: https://docs.statsig.com/infra-analytics/logs-explorer-overlays ================================================================================ # Events Overlays in Logs Explorer Events Overlays add a marker layer to time-series charts in Logs Explorer, so you can line up log and event trends with the changes that drove them. Overlay a feature gate's rollout history to see exactly when a change shipped, or map raw JSON events onto the chart for ad hoc annotations. On-call responders and engineers use overlays to connect a spike or regression to the config change behind it. > **Info:** > > The feature gate overlay source is in early access, gated behind `logs_overlay_gate_source`. Statsig opts employees in by default. --- ## How overlays work The **Overlay events** control lives in the chart toolbar as a popover. Open it, pick an overlay source, configure which decorations render, and Logs Explorer draws the overlay on top of your query results. Overlays render only on marker-capable time-series charts: **Line**, **stacked line**, and **timeseries bar**. Other visualizations show an unsupported message and skip the overlay fetch entirely. Logs Explorer quantizes the chart window to the minute, so a live 15-second refresh doesn't re-run the gate snapshot walk on every tick. {% callout type="note+ %} The default time window in Logs Explorer is only 2 hours. Typically, gate changes take place over a week. Be sure to check your time window to ensure that the Logs Explorer time window and your window for gate changes overlap. > **Note:** > > --- ## Overlay sources Select a source from the **Overlay events** popover. Logs Explorer offers two sources. ### Feature gate The feature gate source walks a selected gate's config-change and snapshot history, then renders three decorations you can toggle independently: - **Changes**: markers at each point where the gate's configuration changed. - **Rollout %**: a dashed step line that tracks the gate's rollout percentage over time. - **Shade when off**: shaded regions across intervals where the gate was disabled. A follow-rule selector lets you track a specific rule instead of the gate as a whole. ### Raw JSON Paste your events, then map their fields in the field-mapping grid. A live parse preview shows how Statsig reads each field, so you can confirm the mapping before you apply it. --- ## Add an overlay 1. Open Logs Explorer and run a query that renders as a **Line**, **stacked line**, or **timeseries bar** chart. 2. In the chart toolbar, click **Overlay events**. 3. Select a source: **Feature gate** or **Raw JSON**. 4. For a feature gate, choose the gate, toggle the **Changes**, **Rollout %**, and **Shade when off** decorations you want, and set a follow rule if you need one. 5. For raw JSON, map the event fields in the grid and confirm the parse preview. 6. Apply the overlay to draw it on the chart. Logs Explorer saves your overlay configuration to local storage per project and surface, so it persists when you return to the same chart. --- ## Share an overlay Click **Copy link** to share an overlay. Statsig encodes the overlay configuration into an `overlay` URL parameter, which hydrates the overlay once on open and then strips the parameter from the address bar. You can use **Copy link** (or copy/paste the URL from the address bar) only when the encoded overlay fits within URL size limits. For a large field mapping, rebuild the overlay from the source configuration instead. --- ## Limitations > **Note:** > > Overlays render only on marker-capable time-series charts (**Line**, **stacked line**, and **timeseries bar**). The feature gate source is in early access behind `logs_overlay_gate_source`. **Copy link** works only when the overlay payload fits URL size limits. ================================================================================ # Query Syntax for Logs Explorer URL: https://docs.statsig.com/infra-analytics/logs-explorer-queries ================================================================================ # Query Syntax for Logs Explorer Logs Explorer query syntax filters, groups, and visualizes logs using property prefixes, logical operators, and wildcards. Use these operators in day-to-day investigations, and adapt the examples below to your own logs. > **Info:** > > Plain text searches match only against the **log message field**, not the entire log body. ## Basics ### Property prefixes | Prefix | Description | Example | | --- | --- | --- | | `@property` | Event or log properties | `@traceId:"1a3cg5"` | | `#property` | Reserved properties | `#custom_event:"shopping_cart_opened"` | | `$user` | User identifiers | `$stableID:"abcdef"` | | _none_ | User properties | `tier:prod` | ### Logical operators These are query-level connectors. They combine or negate multiple conditions. | Operator | Description | Example | | --- | --- | --- | | `AND` (case sensitive) | Match all conditions | `level:error AND service:api-gateway` | | `OR` (case sensitive) | Match any condition | `level:error OR level:warn` | | `!=` or `!:` | Exclude a condition | `status!:error OR service!:api-gateway` | ### Other operators These are field-level conditions. | Operator | Description | Example | | --- | --- | --- | | `:` or `=` | equals | `status_code:200` or `status_code=200` | | `!=` or `!:` | not equals | `level!:debug` or `level!=debug` | | `>` `<` | greater/less than | `latency_ms>500` or `latency_ms<1000` | | `>=` `<=` | greater/less or equal | `latency_ms>=500` or `latency_ms<=2000` | ### Wildcard search You can use the `*` character as a wildcard in queries. A wildcard matches zero or more characters inside a field value. > **Note:** > > Wildcards can impact query performance. Use them sparingly. ### Additional examples | Query | Description | Matches | | --- | --- | --- | | `@"log.file.path":"/logs/pods/*"` | Path begins with `/logs/pods/` | `/logs/pods/1234/stdout.log` | | `@"log.file.path":"*/logs/pods/"` | Path ends with `/logs/pods/` | `/mnt/storage/logs/pods/` | | `service:"api-*"` | Services with names starting with `api-` | `api-gateway`, `api-auth` | | `@route:"*products/*"` | Page routes containing the string `products/` | `shopify.com/products/tshirts`, `shopify.com/cart/products/view` | | `@message!:""` | Return logs where the message field is **not null** | any log that has a `message` field | ================================================================================ # Events Mode on Logs Explorer URL: https://docs.statsig.com/infra-analytics/events-mode-logs-explorer ================================================================================ # Events Mode on Logs Explorer Events Mode brings the searching and filtering abilities from [Log Explorer](https://docs.statsig.com/infra-analytics/logs-explorer) to your existing Statsig events data. No additional instrumentation required! - Debug user activity with more control - Trace the sequence of actions a user performed - Narrow in on specific events from metadata properties > **Info:** > > Statsig offers Events Mode to all **Statsig Cloud customers**. --- ### Get started with Events Mode 1. Open Logs Explorer from the left navigation. 2. Confirm you've switched from **Logs** mode to **Events** mode (the area next to the search bar should say **Events**). 3. Start searching across event names, properties, and time ranges. --- ### Construct a search You can search through events in two ways: 1. **Writing queries**: Use [syntax-based search](https://docs.statsig.com/infra-analytics/logs-explorer-queries) to target specific events and properties. 2. **Using the query builder**: Point-and-click to construct filters without syntax overhead. ![Events Explorer Overview](https://docs.statsig.com/images/infra-analytics/events-explorer-querying.png) --- ### Example workflows | Description | Query | | --- | --- | | Find all enterprise account signups from web browser devices | `event_name:signup_completed AND #plan:enterprise AND #platform:web` | | Find all checkout events where the item name contained "black" | `@#custom_event:checkout_event,add_to_cart AND @product:"*black*"` | | Find all events from users with a gmail account | `#user_object.email:"*gmail.com"` | ================================================================================ # Topline Alerts with Logs URL: https://docs.statsig.com/infra-analytics/topline-alerts-logs ================================================================================ # Topline Alerts with Logs By combining log filters with [Topline Alerts](https://docs.statsig.com/product-analytics/topline-alerts), you can detect failures immediately, without writing custom scripts or dashboards. ### When to use log-based alerts - **Monitoring success rates**: Catch regressions before they impact SLOs. - **Detecting error spikes**: Trigger when 5xx or other errors rise above baseline. - **Isolate by segment**: Identify failures concentrated in a region, client, or device type ## Create a log-based Topline Alert (Statsig Cloud) This example creates a monitor for the success rate of a GET request. 1. **Navigate to Topline Alerts** - Go to **Analytics → Topline Alerts** in the product menu. - Click **+Create**. - Enter a name for your alert. ![Alert setup step 1](https://docs.statsig.com/images/infra-analytics/loglinealert-1.png) 2. **Define Alert Criteria** - Select `statsig::log_line` as your event. - Apply filters to define what constitutes success and failure. If you're unsure which fields to filter on, open the [Logs Explorer](https://docs.statsig.com/infra-analytics/logs-explorer) and inspect the log body. ![Alert setup step 2](https://docs.statsig.com/images/infra-analytics/loglinealert-2.png) 3. **Set Up Evaluation Formula** - Define the formula for calculating your success rate. - (Optional) Add a group-by dimension. ![Alert setup step 3](https://docs.statsig.com/images/infra-analytics/loglinealert-3.png) 4. **Configure Alert Thresholds** - Set thresholds and the evaluation window. In this example, Statsig triggers a warning when success rate drops below 99.5% and an alert when success rate drops below 99.0%. ![Alert setup step 4](https://docs.statsig.com/images/infra-analytics/loglinealert-4.png) 5. **Configure Notifications** - Add the alert title and description for context. - Include diagnostic hints (e.g. "Check version X" or "Android requests timing out"). - Add subscribers. - Set priority. ![Alert setup step 5](https://docs.statsig.com/images/infra-analytics/loglinealert-5.png) 6. **Save the Alert** - Click **Save**. - After you save your alert, visit the **Diagnostics** tab to view a history of alert triggers. ![Alert setup step 6](https://docs.statsig.com/images/infra-analytics/loglinealert-6.png) --- ## Best practices - Set up [Slack notifications](https://docs.statsig.com/integrations/slack) for team visibility - Keep formulas simple (ratios & percentages are easiest to scan) - Add group-by dimensions (like country or app version) to pinpoint where issues occur - Write clear notification text that explains what the alert means ================================================================================ # Alerts Overview URL: https://docs.statsig.com/product-analytics/alerts-overview ================================================================================ # Alerts Overview ## Alerts Statsig offers two types of alerts on the platform: 1. **[Topline Metric Alerts](https://docs.statsig.com/product-analytics/topline-alerts)** - Monitor a metric’s overall performance, independent of experiments or gates. These alerts keep you informed about topline trends and highlight when key product or business metrics move in a concerning direction. 2. **[Rollout Alerts](https://docs.statsig.com/product-analytics/alerts-overview)** - Monitor how a metric behaves in the context of a feature gate or experiment rollout. These alerts help you confirm that no critical metrics regress when introducing a new change. ================================================================================ # Rollout Alerts URL: https://docs.statsig.com/metrics/rollout-alerts ================================================================================ # Rollout Alerts ## How rollout alerts work Rollout Alerts notify you when an experiment or feature gate moves a metric beyond a threshold you set, so you can catch regressions during a rollout. The console calls them **Guardrail Metric Alerts** on an experiment's _Diagnostics_ tab, and older material calls them metric alerts. All three names describe this feature. On Statsig Cloud, Statsig evaluates Rollout Alerts every 24 hours. Alerts trigger only if the cumulative metric delta is statistically significantly lower or higher than your threshold, which reduces alert noise. On Statsig Warehouse Native, Statsig evaluates Rollout Alerts every time you load Metric Results in a feature gate or experiment. Loading Results on the first day provides more real-time visibility during this window. Alerts only trigger if the metric delta is statistically significantly lower or higher than your threshold, which reduces alert noise. Statsig applies all stats methodologies you have enabled for your experiment or gate rollout (CUPED, Sequential Testing, and so on) to alert calculations. > **Note:** > > Rollout Alerts don't alert at the **topline metric value** level, but rather at **the experiment or feature gate level**. For example, if you allocate an experiment to 10% of your users and the metric change within that 10% breaches the threshold, Statsig alerts you. All alerts you receive are in the context of a specific experiment or feature gate. To debug or resolve the alert, Statsig directs you to the relevant experiment or gate. ## Setting up a rollout alert To set up a metric alert, go to the **Metrics** tab, then **Metrics Catalog**, and search for the metric you want. ![Metrics catalog entry showing alert configuration option](https://docs.statsig.com/images/metrics/rollout-alerts/205982663-f5eabaf6-733b-410f-bba1-63268f3af31a.png) After you open the Metric Detail View, go to the **Alerts** tab and tap **+ Create Alert**. Configure the following inputs: - **% Change**: The metric delta threshold that triggers an automated alert. This delta is measured in the context of the feature gate rollout or experiment, not as a top-line metric change across your entire user base. - **Minimum Participating Units**: The minimum number of unique units emitting the metric in each test group before triggering an alert. Statsig displays the 25th, 50th, and 75th percentiles of metric-emitting unit counts per group across your gates and experiments to help you choose a reasonable threshold. - **Direction**: Positive or negative, depending on whether you want an alert when the metric exceeds or drops below a target threshold. - **Subscribers**: By default, Statsig notifies all creators of a feature gate or experiment with a configured alert when the alert fires. You can also add global subscribers, whom Statsig notifies when any feature gate or experiment regresses the metric beyond the threshold. In a large project, adding yourself as a global subscriber of a metric can generate high alert volume. ![Metric alert creation panel specifying threshold, units, and subscribers](https://docs.statsig.com/images/metrics/rollout-alerts/205983421-a50e4373-29b7-4110-91de-a0246f87fe5d.png) After you configure a Rollout Alert for a metric, an alarm bell icon appears next to the metric in the Metrics Catalog. You can also filter for metrics with alerts using the standard metrics filter next to the search bar. ## Determining the right threshold To help you configure the right threshold, the Scorecard shows a preview of how much the metric has moved in the context of any feature gates or experiments containing that metric. ![Scorecard showing metric delta preview with alert threshold guidance](https://docs.statsig.com/images/metrics/rollout-alerts/2a0434fe-e708-497d-b5bd-53c7b609cd47.png) To see how a metric has trended over a longer period, hover over the metric delta for a feature gate or experiment. Then tap a data point to view more details. Tapping the data point opens the time-series for the metric, with a configurable date range picker. ![Metric trend hover showing detailed data point information](https://docs.statsig.com/images/metrics/rollout-alerts/a57599b6-044f-42b6-97fc-e6fb8bb3435c.png) ![Metric time-series chart with selectable date range](https://docs.statsig.com/images/metrics/rollout-alerts/f4b0e8a2-c5aa-4bb3-b57d-36930e906e5d.png) ## Alert notifications and resolution When a Rollout Alert triggers, all subscribers and the relevant gate or experiment creators receive a notification by email and in the Statsig Console. Users who have configured Slack notifications for their Statsig accounts also receive the notification through Slack. ![Alert notification card showing metric exceeding threshold](https://docs.statsig.com/images/metrics/rollout-alerts/205983664-14d2715d-924b-429e-b4a3-40365c4a26af.png) ![Slack notification preview for rollout alert](https://docs.statsig.com/images/metrics/rollout-alerts/205983817-6a569919-7e2b-4716-9862-aa406c9db843.png) Tapping **View Alert** takes you to the Diagnostics page of the offending feature gate or experiment that triggered the rollout alert. ![Diagnostics page showing call-to-action after alert triggers](https://docs.statsig.com/images/metrics/rollout-alerts/205983990-6ccbd888-acd4-47e3-96ef-8b3a513a26bf.png) In the Diagnostics section, scroll to the **Rollout Alerts** section and select the active alert. The metric delta trend appears with the threshold overlaid. To resolve the alert, tap **Resolve** inline. You can either resolve the alert and provide an explanation, or snooze the alert for a specified period. The alert status updates both in the **Rollout Alerts** section and at the top of the Pulse page for the gate or experiment. ![Rollout alerts section with resolve and snooze controls](https://docs.statsig.com/images/metrics/rollout-alerts/205984434-f60e7d21-8356-499d-95e8-0c551f82a74d.png) ## Viewing alert history To view alert history, go to the **Metrics** tab, then **Metrics Catalog**, and select the metric. Then go to **Alerts**, open the **…** menu in the **Experiment and Gate Alerts** section, and select **View Alert History**. The history shows all instances of the alert firing, being resolved, or being snoozed, along with the resolution reason, who resolved the alert, and when. ![Alert history table listing firing and resolution events](https://docs.statsig.com/images/metrics/rollout-alerts/205984564-216fdf30-185b-4b05-9047-b64769c844ec.png) ![Alert resolution dialog capturing notes and snooze options](https://docs.statsig.com/images/metrics/rollout-alerts/205984591-cf528cab-c6bd-43a5-8aa1-c80704d4e137.png) ================================================================================ # Topline Alerts URL: https://docs.statsig.com/product-analytics/topline-alerts ================================================================================ # Topline Alerts Topline Alerts watch an event or metric you choose and notify you when its value crosses a fixed threshold or changes beyond an amount you set. Use them to catch shifts in metrics like P90 latency or usage as they happen, and route notifications to email, the Statsig Console, Slack, and PagerDuty. > **Info:** > > Topline Alerts are available to customers on Pro and Enterprise plans. Topline Alerts are available in Statsig Cloud and Statsig Warehouse Native with support available for three types of Topline Alerts: | Alert Condition Type | When to Use | Example | | --- | --- | --- | | **Threshold** | Use when you want to stay above or below a fixed number. | “Alert me when P90 latency spikes above 15 seconds.” | | **Change** | Use when the absolute size of the change matters. | “Alert me when hourly P90 latency increases by 10 seconds.” | | **Change (%)** | Use when the relative size of the change matters more than raw numbers. | “Alert me when hourly P90 latency increases by 50%.” | ## Creating a topline alert 1. **Navigate to Topline Alerts** Go to **Analytics → Topline Alerts** in the product menu. 2. **Create a New Alert** Click **+Create** and give the new alert a name. 3. **Select the Event or Metric Source** Pick the data you want to monitor. - **On Statsig Warehouse Native**: Select a Metric Source, filter, and group by the dimensions you want. - **On Statsig Cloud**: Select the event, aggregation, filters, and group-by conditions for this alert. > **Info:** > > This example sets up an alert to monitor P90 latency for `mex_query` events, filtering out internal employee queries and grouping by the `hadGroupBy` dimension. ![Select events or metrics for a Topline Alert](https://docs.statsig.com/images/infra-analytics/topline-alerts-choose-events.png) 4. **Review the Alert Preview** The preview shows how your metric is trending with the current setup. Confirm values look correct, or open the metric in [Metrics Explorer](https://docs.statsig.com/product-analytics/drilldown) for deeper analysis. ![Topline Alert preview showing trending metric](https://docs.statsig.com/images/infra-analytics/topline-alerts-preview.png) 5. **Set Alert Conditions** The preview updates along with each change. Define the: - Condition type (threshold, change, change %) - Directionality - _Alert_ and _Warn_ values - Evaluation window > **Warning:** > > On Warehouse Native: Define the evaluation frequency, lookback, and max delay. These values directly influence warehouse compute costs. ![Configure alert conditions for a Topline Alert](https://docs.statsig.com/images/infra-analytics/topline-alerts-conditions.png) 6. **Add Notifications** Notifications go to email, the Statsig Console, Slack (if connected), and [PagerDuty](https://docs.statsig.com/integrations/pagerduty) (if configured). Project-wide defaults live in Settings. - Draft a clear, actionable message subscribers receive when the alert fires. - Add subscribers. - Select the PagerDuty services to page when the alert fires. - Set alert priority. - Configure re-notification rules if alerts should resend while conditions hold. 7. **Save and Monitor** After saving, triggered alerts appear at the top of the page. From here you can: - View samples of the event. - Open the trend in [Metrics Explorer](https://docs.statsig.com/product-analytics/drilldown). - Mute the alert temporarily if it's noisy or already under investigation. ![Topline Alerts table with active alerts](https://docs.statsig.com/images/product-analytics/topline-alerts-overview.png) ## Diagnostics Navigate to the **Diagnostics** tab to review alert history, inspect samples, open Metrics Explorer, or mute noisy alerts. ![Diagnostics tab showing alert history](https://docs.statsig.com/images/product-analytics/topline-alerts-diagnostics.png) --- ## Related resources - [Create a Topline Alert on log lines](https://docs.statsig.com/infra-analytics/topline-alerts-logs) - [Set up team Slack notifications](https://docs.statsig.com/integrations/slack/#team-notifications) ================================================================================ # Statsig Web Analytics Overview URL: https://docs.statsig.com/webanalytics/overview ================================================================================ # Statsig Web Analytics Overview ## Web analytics overview Statsig [Web Analytics](https://www.statsig.com/web-analytics) tracks key measures for your website, such as visitors, views, and sessions. It's simpler and more direct than product analytics, which makes it a good fit for marketers, site maintainers, or anyone familiar with tools like Google Analytics. With Web Analytics and Statsig Dashboards you can easily gather insights such as number of visitors, views, sessions, how long sessions last, error rates, usage journey, and more. After you add web analytics to your application, events appear in your metrics page: https://console.statsig.com/metrics/events ![Metrics events dashboard showing web analytics data](https://docs.statsig.com/images/web-analytics-dash-1.png) ## Getting started ### Option 1: HTML script installation Add a single script tag to your website: ```html ``` Get YOUR\_CLIENT\_KEY from _Project Settings > Keys & Environments_. Reveal the Client API Key, copy, and paste it over the \[YOUR\_CLIENT\_KEY\] in the snippet above. ![Project settings showing client API key configuration](https://docs.statsig.com/images/Client-api-key-web-analytics.png) ### Option 2: HTML script with advanced control For more control over initialization and configuration, you can manually initialize the Statsig client: ```html ``` ### Option 3: JavaScript client SDK (React bindings) If using the JavaScript client SDK or another framework, use the corresponding SDK with the autocapture plugin (JS, React, Angular, etc.): ```javascript import * as React from 'react'; import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; return ( Loading... } options={{ plugins: [ new StatsigAutoCapturePlugin() ] }}>
Hello
); ``` ## Autocaptured events Statsig Web Analytics automatically captures the following events without any additional code: ### Page navigation events - **`auto_capture::page_view`**: Statsig captures this event when a user navigates to a new page. It includes page URL, query parameters, referrer information, and metadata. - **`auto_capture::page_view_end`**: Statsig captures this event when a user leaves a page. It includes engagement metrics like scroll depth, time on page, and whether the exit was due to inactivity. ### User interaction events - **`auto_capture::click`**: Captures all click events with target element information, coordinates, and page context. - **`auto_capture::rage_click`**: Detects rapid repeated clicks in the same area, often indicating user frustration. - **`auto_capture::dead_click`**: Identifies clicks that don't result in any page changes or navigation, potentially indicating broken functionality. - **`auto_capture::form_submit`**: Captures form submission events with form metadata. - **`auto_capture::copy`**: Tracks when users copy text from your page, including the selected text content. ### Technical performance events - **`auto_capture::error`**: Automatically captures JavaScript errors with stack traces, error messages, and context. - **`auto_capture::web_vitals`**: Captures Core Web Vitals metrics (refer to the [Web vitals events](#web-vitals-events) section below). - **`auto_capture::performance`**: Collects page load performance metrics including load times, DOM interactive time, and network transfer data. (deprecated, use `auto_capture::web_vitals` instead) ### Session events - **`auto_capture::session_start`**: Marks the beginning of a new user session. ### Console logging (disabled by default) - **`statsig::log_line`**: Captures console log output. Statsig disables console log capture by default, so you must enable it in your configuration. For details on how to enable console log autocapture, refer to [Console Log Capture Configuration](#console-log-capture-configuration). ## Event filtering and console configuration ### Disabling events through the console You can disable specific autocapture events from the Statsig console under _Project Settings > Analytics & Session Replay_: ![Analytics event filtering configuration interface](https://docs.statsig.com/images/autocapture-settings.png) ### Programmatic event filtering For more granular control, you can filter events programmatically using a custom filter function: ```javascript const client = new StatsigClient( 'YOUR_CLIENT_KEY', { userID: 'optional' }, { plugins: [ new StatsigAutoCapturePlugin({ eventFilterFunc: (event) => { // Filter out events from admin pages if (event.metadata.pageUrl && event.metadata.pageUrl.includes('/admin/')) { return false; } return true; } }) ]} ); ``` ### Console log capture configuration Statsig disables console log capture by default, but you can enable it with the following configuration: ```javascript const client = new StatsigClient( 'YOUR_CLIENT_KEY', { userID: 'optional' }, { plugins: [ new StatsigAutoCapturePlugin({ consoleLogAutoCaptureSettings: { enabled: true, } }) ]} ); ``` The following optional settings are also available when capturing console logs: - **`logLevel`**: minimum level to capture (`debug` | `info` | `log` | `warn` | `error`) - **`sampleRate`**: fraction between 0 and 1 to sample captured logs - **`maxKeys`**: maximum number of keys to serialize from logged objects - **`maxDepth`**: maximum nesting depth when serializing objects - **`maxStringLength`**: maximum number of characters for stringified values ```javascript const client = new StatsigClient( 'YOUR_CLIENT_KEY', { userID: 'optional' }, { plugins: [ new StatsigAutoCapturePlugin({ consoleLogAutoCaptureSettings: { enabled: true, logLevel: 'warn', // capture warn and error sampleRate: 0.5, // capture 50% of matched logs maxKeys: 50, // limit number of keys per object maxDepth: 3, // limit nested object depth maxStringLength: 2000, // truncate long strings } }) ]} ); ``` ## Web vitals events Statsig automatically captures Core Web Vitals metrics that are essential for measuring user experience and SEO performance: ### Core Web Vitals metrics - **CLS (Cumulative Layout Shift)**: Measures visual stability by tracking unexpected layout shifts during page load. Lower scores indicate better user experience. - **FCP (First Contentful Paint)**: Measures loading performance by tracking when the browser paints the first text or image on the screen. Faster FCP times indicate better perceived performance. - **LCP (Largest Contentful Paint)**: Measures loading performance by tracking when the largest content element becomes visible. This metric correlates strongly with user-perceived load times. - **TTFB (Time to First Byte)**: Measures server response time by tracking how long it takes to receive the first byte of response from the server. This indicates server and network performance. - **INP (Interaction to Next Paint)**: Measures responsiveness by tracking the longest latency across user interactions. Lower values mean more consistent, responsive experiences. Statsig automatically collects and sends these metrics as `auto_capture::web_vitals` events, providing insights into your website's performance and user experience quality. ## Single page application (SPA) support Statsig Web Analytics automatically supports single page applications without any additional configuration. Statsig detects route changes through: ### Automatic route change detection - **Browser Navigation**: Listens for `popstate` events to detect when users use browser back/forward buttons - **Programmatic Navigation**: Automatically proxies `history.pushState` calls to detect when your application programmatically navigates to new routes - **Automatic Page Views**: Triggers new `auto_capture::page_view` events whenever Statsig detects route changes Modern SPA frameworks like React Router, Vue Router, and Angular Router work with Statsig Web Analytics without requiring manual page view tracking. ## Exploring events in Metrics explorer In [Metrics Explorer](https://console.statsig.com/metrics/explore), you can filter and group your events using complex filters and dimensions, then add the analysis to your dashboard. For more on Metrics Explorer features like Funnels and Retention, refer to the [Product Analytics overview](https://docs.statsig.com/product-analytics/overview). ![Metrics Explorer interface for analyzing web analytics data](https://docs.statsig.com/images/webanalytics/overview/f4ed6f2c-79ce-4e47-ba6d-8dbe69978cc0.png) For example autocapture event details, refer to [Autocapture Metrics](https://docs.statsig.com/webanalytics/autocapture). ## Autocapture settings The autocapture plugin or manual setup can take an optional `options` parameter to customize the autocapture settings. | Parameter | Type | Description | | --- | --- | --- | | `eventFilterFunc` | `Optional[Callable[[AutoCaptureEvent], bool]]` | A function to filter events based on their metadata. | | `consoleLogAutoCaptureSettings` | `Optional[ConsoleLogAutoCaptureSettings]` | An object to configure console log capture. | **consoleLogAutoCaptureSettings**: | Setting | Type | Description | | --- | --- | --- | | `enabled` | `Optional[bool]` | Enables or disables console log capture. | | `logLevel` | `Optional[str]` | Sets the minimum log level for console log capture. | | `sampleRate` | `Optional[float]` | Sets the sample rate for console log capture (0-1). | | `maxKeys` | `Optional[number]` | Maximum number of keys to serialize from logged objects. | | `maxDepth` | `Optional[number]` | Maximum nesting depth when serializing objects. | | `maxStringLength` | `Optional[number]` | Maximum number of characters for stringified values. | **eventFilterFunc**: | Field | Type | Description | | --- | --- | --- | | `event` | `AutoCaptureEvent` | The event object Statsig is capturing. | | `return` | `bool` | Return `true` to capture the event, or `false` to ignore it. | ================================================================================ # Autocapture Metrics URL: https://docs.statsig.com/webanalytics/autocapture ================================================================================ # Autocapture Metrics The JavaScript, React, and Angular SDKs support autocapture, which automatically captures events and their attributes without requiring you to manually instrument your code. ## Attributes captured ### Common metadata (on all events) Statsig automatically captures comprehensive metadata with each autocapture event to provide rich context for analysis: - To filter events, you can use the `eventFilterFunc` option when initializing the Statsig client. - To sanitize events and their metadata, listen for the `pre_logs_flushed` client event and modify the event object before Statsig sends it. (Refer to [Client Event Emitter](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) for more details.) #### Page and environment metadata | Property | Description | | --- | --- | | `metadata.title` | Page title from `` tag | | `metadata.current_url` | Full current URL | | `metadata.hostname` | Domain name of the current page | | `metadata.pathname` | Path portion of the URL | | `metadata.user_agent` | Browser user agent string (truncated to 200 chars) | | `metadata.locale` | Browser language setting | | `metadata.timezone` | User's timezone | | `metadata.timezone_offset` | Timezone offset in minutes | | `metadata.timestamp` | Event timestamp in milliseconds | #### Screen and viewport data | Property | Description | | --- | --- | | `metadata.screen_width` | Screen width in pixels | | `metadata.screen_height` | Screen height in pixels | | `metadata.viewport_width` | Browser viewport width in pixels | | `metadata.viewport_height` | Browser viewport height in pixels | #### Network information | Property | Description | | --- | --- | | `metadata.effective_connection_type` | Connection speed estimate | | `metadata.rtt_ms` | Round-trip time in milliseconds | | `metadata.downlink_mbps` | Download speed in Mbps | | `metadata.save_data` | Whether user has data saver enabled | #### Referrer and traffic source data | Property | Description | | --- | --- | | `metadata.referrer` | Full referrer URL | | `metadata.referrer_domain` | Domain of the referrer | | `metadata.referrer_path` | Path of the referrer URL | | `metadata.searchEngine` | Detected search engine | | `metadata.searchQuery` | Search query from referrer | #### Campaign and marketing attribution Statsig automatically captures 25+ marketing attribution parameters including: | Property | Description | | --- | --- | | `metadata.utm_source` | UTM source parameter | | `metadata.utm_medium` | UTM medium parameter | | `metadata.utm_campaign` | UTM campaign parameter | | `metadata.utm_term` | UTM term parameter | | `metadata.utm_content` | UTM content parameter | | `metadata.utm_id` | UTM ID parameter | | `metadata.gclid` | Google Click ID | | `metadata.fbclid` | Facebook Click ID | | `metadata.msclkid` | Microsoft Bing Click ID | | `metadata.ttclid` | TikTok Click ID | | `metadata.li_fat_id` | LinkedIn Click ID | | `metadata.epik` | Pinterest Click ID | Additional platform IDs captured: - `gclsrc`, `wbraid`, `gad_source` (Google) - `dclid` (DoubleClick) - `irclid` (Impact) - `igshid` (Instagram) - `_kx` (Klaviyo) - `mc_cid`, `mc_eid` (Mailchimp) - `qclid` (Quora) - `rdt_cid` (Reddit) - `sccid` (Snapchat) - `ttc`, `ttc_id` (TikTok) - `twclid` (Twitter) ### Action events (click, form submit, etc.) | Property | Description | | --- | --- | | `tagName` | The HTML tag of the clicked element | | `classList` | The list of CSS classes on the clicked element | | `class` | The class attribute of the clicked element | | `id` | The ID attribute of the clicked element | | `ariaLabel` | The aria-label attribute of the clicked element | | `selector` | A CSS selector that uniquely identifies the clicked element | Statsig may capture the following properties depending on the event element: - `action` - `method` - `formName` - `formId` - `href` - `content` - `inputName` - `textContent` - `selectedText` ...and more ### Page view events PageViewStart: | Property | Description | | --- | --- | | `last_page_view_url` | The URL of the last page view | PageViewEnd: | Property | Description | | --- | --- | | `page_view_length` | The length of the page view in milliseconds | | `lastScrollY` | The last scroll position in pixels | | `maxScrollY` | The maximum scroll position reached during the page view in pixels | | `lastScrollPercentage` | The last scroll percentage (0-100) of the page | | `maxScrollPercentage` | The maximum scroll percentage reached during the page view (0-100) | | `scrollDepth` | The scroll depth percentage (0-100) - deprecated, use maxScrollPercentage instead | | `dueToInactivity` | Whether the page view ended due to inactivity | ### Dead click events | Property | Description | | --- | --- | | `scrollTimeout` | Boolean indicating if a scroll timeout occurred | | `selectionChangeTimeout` | Boolean indicating if a selection change timeout occurred | | `mutationTimeout` | Boolean indicating if a mutation timeout occurred | | `absoluteTimeout` | Boolean indicating if an absolute timeout occurred | | `scrollDelayMs` | The number of milliseconds to wait before considering a scroll event as a dead click | | `selectionChangeDelayMs` | The number of milliseconds to wait before considering a selection change event as a dead click | | `mutationDelayMs` | The number of milliseconds to wait before considering a mutation event as a dead click | | `absoluteDelayMs` | The number of milliseconds to wait before considering an absolute timeout event as a dead click | ### Rage click events | Property | Description | | --- | --- | | `x` | The x-coordinate of the rage click | | `y` | The y-coordinate of the rage click | | `timestamp` | The timestamp of the rage click in milliseconds | ### Web vitals events | Property | Description | | --- | --- | | `name` | The name of the web vital ('CLS', 'FCP', 'LCP', 'TTFB') | | `value` | The current measurement value (e.g., milliseconds for LCP, FCP, etc.; a numeric score for CLS) | | `delta` | The change from the previously reported value, used to calculate cumulative values over time | | `id` | The ID of the web vital event | ### Console log events | Property | Description | | --- | --- | | `status` | The status of the console log ('debug', 'info', 'warn', 'error') | | `log_level` | The level of the console log ('debug', 'info', 'log', 'warn', 'error') | | `payload` | The payload of the console log (array of strings) | | `timestamp` | The timestamp of the console log in milliseconds (epoch time) | | `trace` | A stack trace (if available) showing where in the code the console log was triggered (array of strings) | | `source` | The source of the console log ('js-auto-capture') | #### Query parameters Statsig automatically captures all URL query parameters as individual metadata fields with their parameter names as keys. ================================================================================ # Agent Experimentation Overview URL: https://docs.statsig.com/ai-evals/overview ================================================================================ # Agent Experimentation Overview Statsig Agent Experimentation serves the prompts and models behind your AI app or agent, and grades their output before and after release. Each LLM task's model, prompt messages, and parameters live in an AI Config. Your app fetches the AI Config at runtime, so you can change a prompt or model without deploying code. Graders score output from 0 to 1, on test datasets before a release and on a sample of live traffic after it. Use Agent Experimentation to find out whether a new prompt or model gives better answers. To measure whether the change also moves product metrics, such as retention, create an experiment from the AI Config. For details, go to [Use AI Configs with gates, experiments, and analytics](#use-ai-configs-with-gates-experiments-and-analytics). The Statsig SDKs and the Console API still call AI Configs "prompts." For example, the Node AI SDK fetches an AI Config with `getPrompt`. ## Parts of Agent Experimentation Agent Experimentation has these parts: | Part | What it does | | --- | --- | | [AI Configs](https://docs.statsig.com/ai-evals/prompts) | Store the model, prompt messages, and parameters for one LLM task, in versions. Your app serves the Live version. | | [Playground](https://docs.statsig.com/ai-evals/playground) | Runs up to 10 prompts side by side on the same inputs. You can promote the prompts to a new AI Config. | | [Datasets](https://docs.statsig.com/ai-evals/datasets) | Hold test cases for evals to grade, such as user questions and expected answers. | | [Graders](https://docs.statsig.com/ai-evals/graders) | Score output from 0 to 1 with an LLM judge, Python code, a string comparison, or a text similarity function. Graders live in one catalog, so every AI Config and eval can reuse them. | | [Offline evals](https://docs.statsig.com/ai-evals/offline-evals) | Run AI Config versions on every dataset row and grade the outputs. Compare versions before you promote one to Live. | | [Evals](https://docs.statsig.com/ai-evals/evals) | Grade outputs that already exist in a dataset, such as answers from your own agent, and track scores across runs. | | [Online evals](https://docs.statsig.com/ai-evals/online-evals) | Grade a sample of production traffic about one minute after your app sends each span. | | [AI Traces](https://docs.statsig.com/ai-evals/ai-traces) | Lists the LLM spans your app sends, with their messages, model, tokens, cost, and grader scores. You can save spans to a dataset. | The [Node AI SDK](https://docs.statsig.com/ai-evals/node) and the [Python AI SDK](https://docs.statsig.com/ai-evals/python) connect your app to Agent Experimentation. They fetch AI Configs, send model calls to AI Traces as spans, and log grades that your own code computes. ### How the parts fit together A typical workflow uses the parts in this order: 1. Try prompts and models in the Playground, then promote the best prompts to an AI Config. 2. Add a dataset and graders to the AI Config. Run an offline eval of each version, then promote the best version to Live. 3. Fetch the AI Config in your app with a Statsig AI SDK, and trace its model calls. 4. Add online rules to your graders, and turn on online eval for the AI Config to grade production traffic. 5. Review spans in AI Traces. Add spans with poor answers to a dataset, so the next offline eval tests them. For a step-by-step walkthrough, go to [Set up Agent Experimentation](https://docs.statsig.com/ai-evals/setup). ### Offline and online grading Offline evals and runs on the _Evals_ page grade every row of a dataset, so a grader can compare the output with an expected answer from the dataset. Production traffic has no expected answer. Online evals therefore use graders that score each answer on its own, such as LLM judges and Python graders. Each grader's targeting rules decide where the grader runs. For details, go to [Choose where a grader runs](https://docs.statsig.com/ai-evals/graders#choose-where-a-grader-runs). ## Use AI Configs with gates, experiments, and analytics AI Configs work with the rest of Statsig: - **Feature gates**: To release an AI feature to some users first, check a [feature gate](https://docs.statsig.com/feature-flags/overview) in your code before you fetch the AI Config. To serve a different AI Config to users who match a rule, click **Edit Targeting Rules** in the AI Config's header. - **Experiments**: To measure how AI Config versions affect product metrics, click **Create Experiment** in the AI Config's header. You need at least two versions that are Live or Candidate. Statsig creates the experiment in the AI Config's layer, gives each version a group, and splits traffic evenly across the groups. Statsig also adds a primary metric for each grader on the AI Config. These grader metrics read only grades that your code logs with `logEvalGrade`. For the steps, go to [Create an experiment from an AI Config](https://docs.statsig.com/ai-evals/prompts#create-an-experiment-from-an-ai-config). - **Analytics**: Statsig logs online grades and `logEvalGrade` grades as `statsig::eval_result` events in your project. For the event's fields, go to [Grade events in your project](https://docs.statsig.com/ai-evals/online-evals#grade-events-in-your-project). ## LLM as a judge Some checks follow a fixed rule. For example, when an answer must be High, Medium, or Low, a String Comparison grader checks for an exact match. Other checks need judgment. "Your ticket has been escalated" and "This ticket has been escalated" mean the same thing, but an exact match scores them as different. An LLM as a Judge grader sends the output and your judge prompt to a model. The model returns a score from 0 to 1 with its reasoning. For example, the prompt can ask the model to score how close the answer is to an ideal answer. A judge can be wrong, but it applies the same prompt to every output and needs no human reviewers. Judges make it practical to compare versions across many outputs. A judge can use any provider and model in the grader's **Evaluation Model** list, such as OpenAI, Anthropic, or Google models. New graders use OpenAI `gpt-5-mini`. To choose a model and write a judge prompt, go to [Choose the evaluation model](https://docs.statsig.com/ai-evals/graders#choose-the-evaluation-model). ## Credits and API keys Agent Experimentation calls model providers to generate and grade output. Each Statsig organization gets $100 of Included Credits for these calls, shared by all of its projects. A project that isn't in an organization gets its own $100. Statsig charges each model call that runs on Statsig's provider keys against the credits, based on the model's token prices. Included Credits are for getting started. To keep using Agent Experimentation after they run out, add your own API keys for the model providers you use. Statsig doesn't meter calls that use your own keys. ### What Included Credits cover These activities use Included Credits when your project has no API key for the provider they call: | Activity | Model calls that use credits | | --- | --- | | Previews of AI Config output and grader scores | The model of the AI Config version or of the judge | | Offline evals from an AI Config, including scheduled runs | The version's model for each dataset row, and graders that call a provider | | Runs on the Evals page | Graders that call a provider | | Online evals | Graders that call a provider | | Playground runs | The model of each prompt | Two kinds of grader call a provider. LLM as a Judge graders call the provider in **Evaluation Model**. Text Similarity graders that use Cosine call OpenAI for `text-embedding-3-large` embeddings. String Comparison, Python, and the other Text Similarity functions run inside Statsig at no cost. AI Config versions with a custom workflow call your own endpoint, so they don't use credits. For a summary by grader type, go to [Grader costs](https://docs.statsig.com/ai-evals/graders#grader-costs). ### Track Included Credits The _Included Credits_ indicator next to the tabs on each AI Config page shows what percentage of the Included Credits your organization has used. Hover over the indicator to find the **Add API key** link. The indicator disappears when your project has an API key for every provider in _AI Provider API Keys_: OpenAI, Anthropic, Google, and Meta. When a model uses a provider that has no API key, a notice under the model also shows an **Add API key** link. The notice appears in the _Model_ section of an AI Config's _Setup_ tab and under **Evaluation Model** on a grader's _Setup_ tab. ### Add your own API keys API keys belong to a project, and only admins can add them. 1. Go to _Settings > Product Configuration > General_. Console messages call this page _Settings > Products_. 2. In the **AI Provider API Keys** row, click **Edit**. 3. In the _Edit AI Provider API Keys_ dialog, click **Add API Key**. 4. Choose a **Provider**, enter the key in **API Key**, and click **Add API Key**. Repeat for each provider that your AI Configs, graders, and playgrounds use. 5. Click **Save**. After you save, Statsig uses your key for every call to that provider. The provider bills your account for those calls. ### When Included Credits run out When your organization's Included Credits run out, Statsig stops making calls on its own provider keys. Work that doesn't need those keys keeps running: calls on your own API keys, AI Config versions with a custom workflow, and graders that call no provider. - **Offline work**: Statsig blocks previews, offline evals, Evals-page runs, and Playground runs that call a provider without an API key. The console shows "Included Credits have run out" and names the provider that needs a key. Statsig also skips scheduled runs that need credits. - **Online evals**: Statsig keeps running graders that use your own API keys and graders that call no provider, such as Python graders. Statsig skips the other graders, and the trace drawer explains that Statsig didn't grade the span. ### Judges that use other providers Statsig calls LLM as a Judge graders that use a provider other than OpenAI through Statsig's model gateway. If your project has an API key for that provider, the gateway call uses your key, and Statsig doesn't meter it. Without a key, the call uses Statsig's key and spends Included Credits. ## Data residency Statsig processes online-eval traces in the US only. Statsig plans to support EU data residency. ================================================================================ # Set up Agent Experimentation URL: https://docs.statsig.com/ai-evals/setup ================================================================================ # Set up Agent Experimentation This walkthrough sets up Statsig Agent Experimentation from start to finish. You create an AI Config and grade its first version against a dataset. Then you serve the AI Config from a Node.js app and grade the app's production traffic with online evals. Each step covers the minimum you need and links to the page with the full details. Use this walkthrough to release one LLM task with evals before and after it reaches users. To compare prompts side by side before you create an AI Config, use the [Playground](https://docs.statsig.com/ai-evals/playground) instead. The Statsig SDKs and the Console API still call AI Configs "prompts." For example, the Node AI SDK fetches an AI Config with `getPrompt()`. A [Server Secret Key](https://docs.statsig.com/access-management/api-keys#server-secret-keys) for the Statsig project, which your app uses to fetch AI Configs and send traces. Included Credits or your own model provider API keys. Statsig charges model calls from previews, eval runs, and LLM as a Judge graders to your organization's Included Credits. Calls on your project's own provider API keys don't use credits. An admin adds keys in _Settings > Product Configuration > General_, under **AI Provider API Keys**. For details, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). A project or org admin for the steps in [Grade production traffic](#grade-production-traffic). A Node.js server app that calls OpenAI, Anthropic, or Google Gemini. The code on this page uses the [Node AI SDK](https://docs.statsig.com/ai-evals/node). From another language, send traces with OpenTelemetry instead. For details, go to [Send traces to AI Traces](https://docs.statsig.com/ai-evals/ai-traces#send-traces-to-ai-traces). ## Create an AI Config An AI Config stores the model, prompt messages, and parameters for one LLM task, such as answering support questions. Your app fetches the AI Config at runtime, so you can change the model or the prompt without deploying code. 1. Go to _Agent Experimentation > AI Configs_ and click **Create**. 2. In the _Create New AI Config_ dialog, enter a name, such as `Support Bot`. Statsig shows the AI Config ID under the name, after `ai_config_name:`. For `Support Bot`, the ID is `support_bot`. Your code fetches the AI Config by this ID. 3. Click **Create**. Statsig opens the AI Config's _Setup_ tab. The AI Config starts with one Live version, named "Version 1." Your app serves the Live version, so saved changes to Version 1 reach your app right away. For the optional fields, such as team and tags, go to [Create an AI Config](https://docs.statsig.com/ai-evals/prompts#create-an-ai-config). ## Configure the version Configure Version 1 in the _Config Setup_ group of the AI Config's _Setup_ tab: 1. Under _Model_, choose a **Provider** and a **Model**. Statsig maintains the list of models for OpenAI, Anthropic, and Google. 2. Under _Prompt_, fill in the System message and the User message. For example: - System: `Answer customer support questions in two sentences or fewer.` - User: `{{input}}` 3. (Optional) Under _Parameters_, change **Temperature** or **Max tokens**. 4. Click **Save**. `{{input}}` is a variable. In offline evals, Statsig replaces the variable with each dataset row's value from the `input` column. Graders read the same column as their own `{{input}}` variable. In your app, you pass the variable's value to `getPromptMessages()`. For model limits, output formats, Prompt Advisor, and custom workflows, go to [Configure a version](https://docs.statsig.com/ai-evals/prompts#configure-a-version). ## Add a dataset and a grader An offline eval runs a version on every row of the AI Config's dataset, then scores each output with the AI Config's graders. Set the dataset and graders in the _Eval Setup_ group of the _Setup_ tab. They apply to every version of the AI Config. To add a dataset: 1. Create a CSV file with an `input` column and one test question in each row. For example: ```csv input How do I reset my password? Can I change the email address on my account? My order arrived damaged. What should I do? ``` 2. Under _Dataset_, click **Select a Dataset**, then click **Upload Dataset**. 3. In the _Upload Eval Dataset_ drawer, click **Upload CSV** and choose the file. Check the preview, then click **Upload**. 4. Click **Save**. An upload accepts one CSV file of up to 2 MB and 1,000 rows. To use a global dataset or generate rows instead, go to [Add a dataset to an AI Config](https://docs.statsig.com/ai-evals/datasets#add-a-dataset-to-an-ai-config). To add a grader: 1. Under _Graders_, click **Add grader**, then click **Create new grader**. 2. Choose **LLM as a Judge**. 3. In the _Create New Grader_ drawer, enter a **Name**, such as `Helpfulness`, and write the judge prompt. For example: ```text Score how well the answer resolves the request, from 0 to 1. <request> {{{input}}} </request> <answer> {{{output}}} </answer> ``` 4. Click **Add Grader**, then click **Save**. `{{output}}` holds the model's answer. Three braces pass a variable's text without HTML escaping. This grader reads only `{{input}}` and `{{output}}`, so it can also grade production traffic in [Grade production traffic](#grade-production-traffic). The first grader you add becomes the AI Config's primary grader, whose score is each run's overall score. Graders you create from an AI Config join your company's grader catalog. For grader types, templates, and evaluation models, go to [Graders](https://docs.statsig.com/ai-evals/graders). ## Run an offline eval 1. In the AI Config's header, click **Run Eval**. 2. In the _Start Evaluation_ dialog, keep Version 1 selected and click **Start Evaluation**. Statsig opens the _Evals_ tab on the new run. A run can take a few minutes. When it finishes, the tab shows these results: - **Model, Score, and Prompt cards**: The model and prompt messages the run used, and the run's overall score from 0 to 1. - **Offline graders chart**: Each grader's score for the run, which is the mean of its row scores. - **Results table**: One row for each dataset row, with the output and each grader's score. Click a row to open _Row Details_, which shows the judge's reasoning. If you can't click **Run Eval**, hover over the button to read the reason. For each reason and its fix, go to [Why Run Eval is disabled](https://docs.statsig.com/ai-evals/offline-evals#why-run-eval-is-disabled). To improve on Version 1, create a new version, run the eval on both versions, and click **Compare** on the _Evals_ tab. Promote the better version with **Promote to Live**. For details, go to [Manage versions](https://docs.statsig.com/ai-evals/prompts#manage-versions) and [Compare two versions](https://docs.statsig.com/ai-evals/offline-evals#compare-two-versions). ## Serve the AI Config from your app Your app fetches the AI Config with the [Node AI SDK](https://docs.statsig.com/ai-evals/node), then calls the model with the Live version's settings. Install the SDK and the OpenAI client: ```shell npm install @statsig/statsig-ai @statsig/statsig-node-core openai ``` For pnpm and Yarn commands, go to [Install the SDK](https://docs.statsig.com/ai-evals/node#install-the-sdk). Then fetch the AI Config and call the model inside `withLive()`. This code reads your Server Secret Key from the `STATSIG_SDK_KEY` environment variable. ```ts import OpenAI from "openai"; import { StatsigAI, StatsigUser } from "@statsig/statsig-ai"; const statsigAI = StatsigAI.newShared({ sdkKey: process.env.STATSIG_SDK_KEY! }); await statsigAI.initialize(); const openai = new OpenAI(); export async function answerQuestion(userID: string, question: string) { const user = new StatsigUser({ userID }); const prompt = statsigAI.getPrompt(user, "support_bot"); // withLive passes the Live version to your function return prompt.withLive(async (version) => { const response = await openai.chat.completions.create({ model: version.getModel({ fallback: "gpt-5-mini" }), messages: version.getPromptMessages({ input: question, }) as OpenAI.ChatCompletionMessageParam[], }); return response.choices[0].message.content; }); } ``` `getPromptMessages()` returns the version's messages with each variable replaced, so `{{input}}` becomes the user's question. In TypeScript, cast the messages to OpenAI's message type. `withLive()` also tags the traced model calls inside it with the AI Config and version, which online evals need. For the other version getters, go to [Get an AI Config](https://docs.statsig.com/ai-evals/node#getting-a-prompt). The Python AI SDK fetches AI Configs with `get_prompt()`. For details, go to [Python AI SDK](https://docs.statsig.com/ai-evals/python#getting-a-prompt). ## Trace model calls Online evals grade the spans that your app sends to Statsig. Each span needs its input and output messages, plus the AI Config and version that produced it. To send these spans, add tracing to the code in [Serve the AI Config from your app](#serve-the-ai-config-from-your-app): 1. Call `initializeTracing()` when your app starts. Call it before you wrap your model client. 2. Wrap the OpenAI client with `wrapOpenAI`, and turn on `captureOptions` for input and output messages. ```ts import OpenAI from "openai"; import { StatsigAI, StatsigUser, initializeTracing, wrapOpenAI, } from "@statsig/statsig-ai"; // Start tracing before you wrap the client. Reads the key from STATSIG_SDK_KEY. initializeTracing({ serviceName: "support-bot" }); const statsigAI = StatsigAI.newShared({ sdkKey: process.env.STATSIG_SDK_KEY! }); await statsigAI.initialize(); // Record the input and output messages that online graders read const openai = wrapOpenAI(new OpenAI(), { captureOptions: { capture_input_messages: true, capture_output_messages: true, }, }); // answerQuestion() stays the same ``` `answerQuestion()` already calls the model inside `withLive()`, so each span records the AI Config in `statsig.llm.prompt_name` and the version in `statsig.llm.prompt_version_id`. Note these points about tracing: - A client that you wrap before you call `initializeTracing()` doesn't send spans. The SDK logs `NoopOtelSingleton instance is being used` when you wrap it. - The SDK doesn't record message content unless you turn on `captureOptions`. Online evals skip spans without input and output messages. - `wrapAnthropic` and `wrapGemini` take the same options for Anthropic and Gemini clients. - In a short-lived process, such as a script or a serverless function, call `await statsigAI.flushEvents()` before the process exits. Run your app, then go to _Agent Experimentation > AI Traces_ to check that the spans arrive. For every tracing option, go to [Trace model calls](https://docs.statsig.com/ai-evals/node#trace-model-calls). To grade a multi-step agent turn as one span, go to [Grade a multi-step agent turn](https://docs.statsig.com/ai-evals/online-evals#grade-a-multi-step-agent-turn). ## Grade production traffic An online grader scores a sample of your app's spans about one minute after Statsig receives them. Each grader's online targeting rules decide which spans the grader scores. Add an online rule to the grader from [Add a dataset and a grader](#add-a-dataset-and-a-grader), then turn on online eval for the AI Config. A project or org admin must save the rule and turn on online eval. 1. Go to _Agent Experimentation > Graders_ and open your grader. 2. On the grader's _Setup_ tab, under _Targeting rules_, click **Add rule** and check **Online**. 3. Add a condition: choose **AI config**, choose **is any of**, and select your AI Config. 4. In **Sample**, enter the percentage of matching traces to grade. New rules start at 10%. While you test with a few requests, enter 100 so that Statsig grades every trace. 5. Click **Save Grader**. 6. Open the AI Config. In the AI Config's header, open the actions menu, click **Enable Online Eval**, and then click **Enable**. The grader's _Targeting rules_ also list an offline rule for your AI Config, which **Add grader** created. You can check **Online** on that rule instead of adding a rule. Statsig grades at most 1,000 spans per hour for each AI Config that has online eval on. Statsig processes online-eval traces in the US only, and plans to support EU data residency. For every rule field, go to [Online rules](https://docs.statsig.com/ai-evals/graders#online-rules). For every limit, go to [Online grading limits](https://docs.statsig.com/ai-evals/online-evals#online-grading-limits). ## Review online eval results Statsig shows online grades on the AI Config's _Traces_ tab: 1. Open the AI Config and click the **Traces** tab. 2. Read the Online graders chart above the span list. Choose **Single version** to show each grader's average score over time for one version. Choose **Compare** to show each grader's score change relative to the Live version. 3. Click a span in the list to open the trace drawer. The _Trace_ tab shows the span's messages, and the _Details_ tab shows the model, tokens, and cost. The _Graders_ tab shows each grader's score, with the judge's reasoning. The span list's Graders column shows a pass or fail chip for each grader, or `Not graded`. If a span still shows `Not graded` after a few minutes, check these causes: - The span has no messages. Turn on `captureOptions` for input and output messages. - The rule's **Sample** percentage skipped the span's trace. - Online eval is off for the AI Config. - Your organization's Included Credits ran out, and your project has no API key for the grader's provider. If your spans don't appear on the _Traces_ tab at all, check that the model call runs inside `withLive()`. For every requirement a span must meet, go to [What Statsig grades](https://docs.statsig.com/ai-evals/online-evals#what-statsig-grades). For the trace drawer, go to [Inspect a trace](https://docs.statsig.com/ai-evals/ai-traces#inspect-a-trace). To grade a Candidate version on production traffic before you promote it, run the version in the background with `prompt.withVersion()`. Users never see the Candidate version's answers. For an example, go to [Grade a single model call](https://docs.statsig.com/ai-evals/online-evals#grade-a-single-model-call). ================================================================================ # AI Configs URL: https://docs.statsig.com/ai-evals/prompts ================================================================================ # AI Configs An AI Config stores the model, prompt messages, and parameters for one LLM task in your app, such as classifying a support ticket. Your app fetches the AI Config at runtime with a Statsig AI SDK, so you can change the model or the prompt without deploying code. Each AI Config has versions. Your app serves the Live version, and you evaluate other versions before you promote one to Live. Use an AI Config to serve, evaluate, and roll out a prompt in production. To compare prompts side by side before you commit to one, use the [Playground](https://docs.statsig.com/ai-evals/playground) instead. The Statsig SDKs and the Console API still call AI Configs "prompts." For example, the Node AI SDK fetches an AI Config with `getPrompt`. ## Find an AI Config Go to _Agent Experimentation > AI Configs_ to open the list of AI Configs in your project. The list has these columns: | Column | Shows | | --- | --- | | Name | The AI Config's name | | Last Modified | When someone last changed the AI Config | | Live Version | The version your app serves | | Creator | The person who created the AI Config | | Target Applications | The target applications that receive the AI Config. This column appears only when your project uses target applications. | | Tags | The AI Config's tags | Search the list by name, or sort it by **Name** or **Last Modified**. Filter it by **Creator**, **Tag**, or **Target Application**. The **Target Application** filter appears only when your project uses target applications. Click an AI Config to open it. The AI Config page has three tabs: _Setup_, _Evals_, and _Traces_. ## Create an AI Config 1. Go to _Agent Experimentation > AI Configs_ and click **Create**. You can also click **Create** on the Statsig home page, then click **AI Config**. 2. In the _Create New AI Config_ dialog, enter a name. Statsig shows the AI Config ID under the name, after `ai_config_name:`. The ID is the name in lowercase, with underscores in place of spaces. Your app uses the ID to fetch the AI Config. 3. (Optional) Enter a description. 4. (Optional) Choose a **Team**, **Tags**, and **Target Apps**. By default, a new AI Config uses your first team and that team's default target applications. 5. Click **Create**. Statsig creates the AI Config and opens its _Setup_ tab. The AI Config starts with one Live version named "Version 1," with an empty System message and an empty User message. Saved changes to Version 1 reach your app right away, because Version 1 is Live. To turn prompts that you tested in a playground into an AI Config, go to [Promote prompts to an AI Config](https://docs.statsig.com/ai-evals/playground#promote-prompts-to-an-ai-config). ## Configure a version Configure an AI Config version on the AI Config's _Setup_ tab. The tab is one page with two groups of settings: - **Config Setup**: The selected version's settings: _Version_, _Custom workflow_, _Model_, _Prompt_, and _Parameters_. Choose the version to configure from the **Version** list. - **Eval Setup**: The graders and the dataset that offline evals use. These settings apply to every version of the AI Config. To add graders, go to [Graders](https://docs.statsig.com/ai-evals/graders). Graders also decide a version's overall score. The AI Config's [primary grader](https://docs.statsig.com/ai-evals/graders#what-is-a-primary-grader) sets the score, and a [critical grader](https://docs.statsig.com/ai-evals/graders#what-is-a-critical-grader) fails a run when it scores 0. To add a dataset, go to [Add a dataset to an AI Config](https://docs.statsig.com/ai-evals/datasets#add-a-dataset-to-an-ai-config). Changes on the _Setup_ tab stay unsaved until you click **Save**. Click **Discard Changes** to undo them. ### Choose a model Under _Model_, choose a **Provider** and a **Model**. Statsig maintains the list of models for each provider: OpenAI, Anthropic, and Google. Some models limit the other settings: | Models | Limit | | --- | --- | | Models whose IDs start with `gpt-5`, `gpt-6`, `o1`, `o3`, or `o4` | **Temperature** stays at 1. The field's tooltip reads "This model only supports the default temperature of 1." | | Anthropic and Google models | At least one message must have the User role. | | `claude-fable-5`, `claude-opus-4.8`, `claude-sonnet-5`, `claude-sonnet-4.5`, and `claude-haiku-4.5` | These models reject **Temperature** and **Top P** set together. Leave **Top P** off. | Statsig charges previews and evals to your Included Credits unless your company has an API key for the provider. Without a key, a notice under _Model_ shows an **Add API key** link. For details, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). ### Write the prompt messages Under _Prompt_, each message has a role: System, User, or Assistant. Click the role on a message to change it. An AI Config version holds up to 10 messages. - To add a message, click **Add New Message**. - To copy or remove a message, open the message's menu and click **Clone Prompt** or **Delete Prompt**. Messages can't be empty. When the AI Config has a dataset, at least one message must reference a dataset column with a variable. A variable is a dataset column name in double braces, such as `{{input}}`. In previews and offline evals, Statsig replaces each variable with the row's value from that column. The _Variables_ list under the messages shows every column in the AI Config's dataset. Click a variable to insert it at the cursor. A variable uses underscores where its column name has spaces. When a column holds JSON, `{{column}}` inserts the whole value. To insert one field, add a dot path of keys and array indexes, such as `{{order.items.0.name}}`. A negative index counts from the end of the array. A path that doesn't exist inserts an empty string. A path that points to an object or an array inserts it as JSON. ### Preview output Results Preview runs the version on the first 5 rows of the AI Config's dataset and shows each output. Use the preview to check a prompt before you run a full eval. The preview uses the current settings, including unsaved changes. To run the preview, click **Preview Output** under the messages. To run it again after a change, click **Reload Preview**. The AI Config needs a dataset first. ### Improve the prompt with Prompt Advisor Prompt Advisor uses Statsig AI to rate the prompt messages and suggest a rewrite. When Prompt Advisor is on, a badge under the messages rates them as Weak, Acceptable, or Great. 1. Click the badge to show the _Prompt Suggestion_ comments. 2. Click **Rewrite with suggestions** to get rewritten messages. 3. Click **Apply** to replace all of the version's messages with the suggestion. An admin turns on Prompt Advisor in _Settings > Product Configuration > AI Features_. In the _AI Configs_ section, turn on **Prompt Advisor**. ### Set parameters Under _Parameters_, set the values that Statsig sends to the model. **Top P**, **Frequency Penalty**, and **Presence Penalty** each have a switch. Statsig sends one of these values only when its switch is on. | Parameter | Range | Default | | --- | --- | --- | | **Temperature** | 0 to 2 | 1 | | **Max tokens** | 1 to 1,500 | 1,000 | | **Top P** | 0 to 1 | Off | | **Frequency Penalty** | -2 to 2 | Off | | **Presence Penalty** | -2 to 2 | Off | Under _Output Format_, choose the format of the model's response: - **Text**: Plain text. - **JSON Object**: A JSON object. - **Structured Output (JSON Schema)**: JSON that matches a schema you enter. The schema is a JSON object with a `name` field and a `schema` field. The `schema` field needs `type` and `properties` fields. ## Call your own endpoint with a custom workflow A custom workflow sends each offline eval row to your own endpoint instead of to the model. Use a custom workflow when your app produces the output with more than one model call, such as an agent that calls tools or retrieves documents. Statsig grades your endpoint's response. Your app still receives the version's model and prompt through the SDK. To set up a custom workflow, open the AI Config's _Setup_ tab and turn on **Call your own endpoint for more complex workflows** under _Custom workflow_. Then fill in these fields. The version's _Prompt_ messages become optional. | Field | Value | | --- | --- | | **Workflow URL** | The endpoint that Statsig calls for each row. Required. | | **Output JSON field path** | If the endpoint returns JSON, the dot path to the output, such as `result.output_text`. Put quotes around a key that contains a dot. | | **Workflow batch size** | The number of requests in each batch. Statsig sends batches one after another. Default: 500. | | **Workflow Body** | The JSON request body. The body must contain at least one variable. | | **Workflow Headers** | Request headers. Click **Add Header** to add one. Up to 15 headers. | | Auth headers | Headers with secret values, such as an API key. Click **Add Auth Header** to add one. Statsig hides their values after you save. Up to 15 headers. | To check the settings, click **Test Connection**. Statsig sends one request and shows the response, or the HTTP error code. During an eval run, Statsig adds two headers to each request. `x-statsig-eval-run` holds the run's ID, so your endpoint can skip side effects for eval requests. `traceparent` holds the W3C trace context of the row's trace in AI Traces. A header that you set with the same name replaces Statsig's. **Test Connection** doesn't send these headers. To show your endpoint's spans in the row's trace, go to [Join a workflow eval's trace](https://docs.statsig.com/ai-evals/node#join-a-workflow-eval-trace). The workflow body accepts dataset columns, such as `{{input}}`, and these variables from the version: | Variable | Value | | --- | --- | | `{{prompt.prompts}}` | All messages as a JSON array of objects with `role` and `content` fields. Statsig fills in the dataset variables first. | | `{{prompt.prompts.0.content}}`, `{{prompt.prompts.0.role}}` | One message's content or role. Messages count from 0. | | `{{prompt.model}}` | The model ID | | `{{prompt.temperature}}`, `{{prompt.top_p}}`, `{{prompt.frequency_penalty}}`, `{{prompt.presence_penalty}}`, `{{prompt.max_tokens}}` | The version's parameters | For example, this body sends the messages, the model, and the row's `input` column: ```json { "messages": {{prompt.prompts}}, "model": "{{prompt.model}}", "question": "{{input}}" } ``` The SDK receives the workflow URL, body, and output field path with the version. The headers, auth headers, and batch size stay on Statsig's servers. ## Manage versions Each version of an AI Config holds its own model, messages, and parameters. Your app serves the Live version by default, so you can test a change in another version first. Manage versions in the _Version_ section of the AI Config's _Setup_ tab. ### Version types Every version has one of four types. The type decides whether your app receives the version and whether you can promote it. | Type | Sent to the SDK | Use it for | | --- | --- | --- | | Live | Yes | The version your app serves. Each AI Config has exactly one Live version. | | Candidate | Yes | A version that you evaluate against Live or test in an experiment. Read Candidate versions in code to shadow-run them without exposing them to users. | | Draft | No | Work in progress in the console | | Archived | No | Versions that you keep for reference. Set an Archived version to Draft or Candidate before you promote it. | ### Create and change versions To create a version, open the **Version** list and click **New version**. A new version starts as a Draft copy of the Live version. The menu next to the **Version** list has these actions: | Action | What it does | | --- | --- | | **Promote to Live** | Makes the version Live. The previous Live version becomes a Candidate. | | **Rename Version** | Changes the version's name. | | **Clone Version** | Copies the version into a new version of the same type. A copy of the Live version is a Draft. | | **Start Evaluation** or **Stop Evaluation** | Starts or stops an offline eval of the version. | | **Set to Candidate** | Makes the version a Candidate. Not available for the Live version. | | **Set to Draft** | Makes the version a Draft. Not available for the Live version. | | **Archive** | Archives the version. Not available for the Live version. | | **Delete Version** | Deletes the version. Not available for the Live version or for an AI Config's only version. | ### Promote a version to Live **Promote to Live** compares the version's latest completed offline eval with the Live version's latest completed offline eval. If the Live version has no completed eval, Statsig promotes the version without asking. Otherwise, Statsig asks you to confirm in these cases: | Dialog | Appears when | | --- | --- | | Promote a lower-scoring version? | The version scores lower than the Live version. | | Promote without a completed eval? | The version has no completed eval, for example because its eval is still running. | Click **Promote Anyway** to promote the version. ### Edit the Live version Saving a change to the Live version changes what your app serves right away. If your app fetched the AI Config recently, Statsig asks you to confirm in the _Save Changes to Live Version_ dialog. To test a change before your app serves it, click **New version**, make the change in the new version, and evaluate the new version. ## Run an offline eval An offline eval runs versions on every row of the AI Config's dataset and grades each output. The AI Config needs a dataset and at least one grader first. 1. In the AI Config's header, click **Run Eval**. 2. In the _Start Evaluation_ dialog, select the versions to evaluate. Save any changes to a version before you evaluate it. 3. Click **Start Evaluation**. While an eval runs, **Run Eval** becomes **Stop Evaluation**. Results appear on the _Evals_ tab. For how to read them, go to [Offline Evals](https://docs.statsig.com/ai-evals/offline-evals). ## Create an experiment from an AI Config An experiment serves different versions of an AI Config to different users and compares their metrics. You need at least two versions that are Live or Candidate. 1. In the AI Config's header, click **Create Experiment**. 2. In the _Create Experiment_ dialog, select at least two Live or Candidate versions, then click **Create Experiment**. 3. In the experiment form, choose the **Control** version and one or more **Treatment** versions. 4. Name the experiment, add a hypothesis, and create the experiment. Statsig creates the experiment in the AI Config's layer. The control group serves the Control version. Each Treatment version gets a test group, and Statsig splits traffic evenly across the groups. For each grader on the AI Config, Statsig adds a primary metric named after the experiment and the grader. The experiment appears in the AI Config's header and in the _Linked Experiments_ list in the _Details_ panel. When you create an experiment from the _Experiments_ page instead, the form shows a "Testing prompts or agents?" notice that links to Agent Experimentation. ## Other AI Config actions Besides **Run Eval** and **Create Experiment**, the AI Config's header has these actions. **History**, **Edit Targeting Rules**, and **Code Snippets** are icon buttons. The other actions are in the header's menu. | Action | What it does | | --- | --- | | **History** | Shows the AI Config's change history. | | **Edit Targeting Rules** | Serves a different AI Config to users who match a rule. Each rule has conditions, a pass percentage, and a target AI Config. An AI Config can't target itself or an AI Config that targets it. | | **Code Snippets** | Shows SDK code that fetches the AI Config. | | **Clone** | Copies the Live version, graders, and dataset into a new AI Config. | | **Edit Scheduled Runs** | Runs an offline eval of the versions you choose every day at the **Reload Time** you choose, in UTC. Statsig skips scheduled runs when your Included Credits run out. | | **Enable Online Eval** or **Pause Online Eval** | Turns online grading of the AI Config's live traffic on or off. Only admins can use this action. For details, go to [Turn on online eval for an AI Config](https://docs.statsig.com/ai-evals/graders#turn-on-online-eval-for-an-ai-config). | | **Delete** | Deletes the AI Config. You can't delete an AI Config that another AI Config's targeting rules reference. | The _Included Credits_ indicator next to the tabs shows the percentage of your Included Credits that your company has used. Hover over the indicator to find the **Add API key** link. The indicator disappears when your company has an API key for every provider in _AI Provider API Keys_. ## Review results on the Evals and Traces tabs - **Evals**: The results of offline evals for one version, or for two versions side by side. For details, go to [Offline Evals](https://docs.statsig.com/ai-evals/offline-evals). - **Traces**: The traces your app sends for the AI Config, with online grader scores. For details, go to [AI Traces](https://docs.statsig.com/ai-evals/ai-traces) and [Online Evals](https://docs.statsig.com/ai-evals/online-evals). ## Serve an AI Config in your app Your app fetches an AI Config by its ID with a Statsig AI SDK, then reads the Live version or the Candidate versions. In the [Node AI SDK](https://docs.statsig.com/ai-evals/node#getting-a-prompt), call `getPrompt`. In the [Python AI SDK](https://docs.statsig.com/ai-evals/python#getting-a-prompt), call `get_prompt`. To copy code for a specific AI Config, click **Code Snippets** in the AI Config's header. ## Manage AI Configs programmatically To create, edit, and evaluate AI Configs from code or from an AI agent, use the Console API or the [Statsig MCP server](https://docs.statsig.com/integrations/mcp/overview). The Console API's AI Config endpoints are in the Prompts section of the reference, starting with [List Prompts](https://docs.statsig.com/api-reference/prompts/list-prompts). ================================================================================ # Graders URL: https://docs.statsig.com/ai-evals/graders ================================================================================ # Graders A grader scores AI output with a number from 0 to 1. Statsig runs graders in two places: offline evals, which grade every row of a dataset, and online evals, which grade a sample of live traffic. Graders live in one catalog for your company. Any AI Config or eval can reuse a grader, so its scores stay comparable across versions. Use a grader when you want Statsig to compute the score. To record a score that your own code computes, such as user feedback, call `logEvalGrade` from the [Node AI SDK](https://docs.statsig.com/ai-evals/node#logging-eval-results) instead. ## Grader types Every grader has one of four types. The type decides how the grader scores output and whether it can run in online evals. | Type | How it scores | Runs online | | --- | --- | --- | | LLM as a Judge | A model reads your prompt and the output, then returns a score from 0 to 1 with its reasoning. | Yes, when the prompt uses only `{{input}}`, `{{output}}`, and `{{trajectory}}` | | String Comparison | Compares `{{output}}` with a dataset column using Equals, Does not equal, Contains, or Contains (ignore case). Scores 1 when the comparison holds and 0 when it doesn't. | No | | Text Similarity | Scores how similar `{{output}}` is to a dataset column, using Fuzzy match, BLEU, GLEU, METEOR, ROUGE-1 through ROUGE-5, ROUGE-L, or Cosine. Cosine embeds both texts with the OpenAI `text-embedding-3-large` model. | No | | Python | Runs your `grade(sample, item)` function, which returns a number. | Yes, when the code reads only `item["input"]` and `item["trajectory"]` | A row or span passes a grader when it scores 0.67 or higher. String Comparison and Text Similarity compare the output with a dataset column. Live traffic has no dataset, so these types run only in offline evals. ## Find a grader The Graders page lists every grader in your company. Go to _Agent Experimentation > Graders_ to open it. The list has the columns **Name**, **Type**, **Last Modified**, and **Creator**. Search the list, filter it by **Creator**, or sort it by **Name** or **Last Modified**. Click a grader to open its page, which has three tabs: _Setup_, _Results_, and _Traces_. ## Create a grader Start from a template when one matches your check. Start from scratch to write your own. 1. Go to _Agent Experimentation > Graders_ and click **Create**. If your company has no graders yet, click **Create a Grader**. 2. In the _Create Grader_ dialog, click a template under **Create from Template**, or click **Create from Scratch**. 3. Enter a **Grader Name**. Grader names must be unique in your company. 4. (Optional) Enter a description. 5. Click **Create**. Statsig creates the grader and opens its _Setup_ tab. A template grader starts with the template's prompt or code saved. A grader created from scratch starts as an LLM as a Judge grader with an empty prompt. You can also create a grader from an AI Config. On the AI Config's _Setup_ tab, in the _Eval Setup_ section, click **Add grader**, then click **Create new grader**. Graders you create this way join the same catalog. For more about AI Configs, go to [AI Configs](https://docs.statsig.com/ai-evals/prompts). ### Grader templates The _Create Grader_ dialog offers six templates. Each template is a starting point that you can edit after you create the grader. | Template | Type | What it checks | Runs online | | --- | --- | --- | --- | | Helpfulness | LLM as a Judge | Whether the response resolves the request | Yes | | Tone Check | LLM as a Judge | Whether the response is polite and on-brand. Edit the voice list in the prompt to match your brand. | Yes | | Groundedness | LLM as a Judge | Whether the request or tool results back every claim | Yes | | Faithfulness | LLM as a Judge | Whether the output contradicts the request or tool results | Yes | | Exact Match | Python | Whether the output equals the value in a dataset column, `expected` by default | No, dataset evals only | | JSON Validity | Python | Whether the output parses as JSON, with optional required fields | Yes | ## Set up a grader The _Setup_ tab holds the grader's definition and its targeting rules. It has these fields: - **Name**: The grader's name in the catalog. - **Type**: One of the four [grader types](#grader-types). - **Evaluation Model**: The provider and model that score output. This field appears for LLM as a Judge graders only. - **Prompt** or **Definition**: The judge prompt for LLM as a Judge graders, or the comparison or code for the other types. - **Targeting rules**: Where the grader runs. For details, go to [Choose where a grader runs](#choose-where-a-grader-runs). ### Choose the evaluation model An LLM as a Judge grader uses the model in **Evaluation Model** to score each row or span. Choose a **Provider**, such as OpenAI, Anthropic, or Google, and then a **Model**. New graders use OpenAI `gpt-5-mini`. Judge calls use your company's Included Credits unless your company has an API key for that provider. Without a key for the provider, the _Setup_ tab shows a notice with an **Add API key** link. For details, go to [Grader costs](#grader-costs). ### Write a judge prompt The judge prompt tells the evaluation model what to check and how to score it. Reference the output and its context with these variables. To insert a variable, click it in the _Variables_ list under the prompt. | Variable | Value | | --- | --- | | `{{input}}` | The input messages, one `role: text` line for each message. In offline evals, the dataset's Input column. | | `{{output}}` | The final answer text. | | `{{trajectory}}` | The tool calls, tool results, and reasoning before the final answer. Empty when the output has none. | Wrap a variable in three braces, such as `{{{output}}}`, to pass its text unchanged. With two braces, Statsig HTML-escapes the text, so the judge reads characters such as `"` and `<` as `"` and `<`. The templates use three braces. For example: ```text Score how well the answer resolves the request, from 0 to 1. <request> {{{input}}} </request> <answer> {{{output}}} </answer> ``` A prompt can also reference a dataset column by name, such as `{{expected}}`. A grader whose prompt references any variable other than `{{input}}`, `{{output}}`, and `{{trajectory}}` runs in offline evals only. ### Define a String Comparison or Text Similarity grader String Comparison and Text Similarity graders compare `{{output}}` with a column from the dataset that an eval runs on. - **String Comparison**: Choose an operation and the column to compare with. The operations are Equals, Does not equal, Contains, and Contains (ignore case). - **Text Similarity**: Choose a function and the column to compare with. The functions are Fuzzy match, BLEU, GLEU, METEOR, ROUGE-1 through ROUGE-5, ROUGE-L, and Cosine. The **Column** list shows the columns of an AI Config's dataset, so create these graders from the AI Config that runs them. On the AI Config's _Setup_ tab, click **Add grader**, then click **Create new grader**. ### Write a Python grader A Python grader runs your code once for each row in an offline eval, or once for each graded span in an online eval. The code must define a `grade(sample, item)` function that returns a number. For example, this grader passes outputs of 500 characters or fewer: ```python def grade(sample, item): output = sample["output_text"] return 1.0 if len(output) <= 500 else 0.0 ``` | Part | Contract | | --- | --- | | Function | `grade(sample, item)`, defined at the top level of your code | | Output | `sample["output_text"]` holds the output text. | | Item | `item` holds the dataset row's columns by name. `item["input"]` and `item["trajectory"]` hold the input and trajectory in both offline and online evals. | | Return value | An `int` or `float` that isn't `NaN` or infinite. A score of 0.67 or higher passes. | | Errors | If the code has no `grade` function, raises an exception, or returns anything other than a finite number, the row scores 0. Statsig records the error message as the grader's response for that row. | | Time limit | 10 seconds for each row. A row that runs longer scores 0. | | Source limit | 100,000 characters. Code over the limit fails every row. | | Environment | A sandbox with the Python standard library. Statsig clears environment variables. | To run online, a Python grader can read only `item["input"]` and `item["trajectory"]` from `item`, written as literal keys. Code that reads any other key, or a key held in a variable, runs in offline evals only. ### Save a grader version Edits on the _Setup_ tab stay unsaved until you click **Save Grader**. Click **Discard Changes** to undo them. Saving a change to the grader's definition creates a new version of the grader. When AI Configs use the grader, Statsig first shows the _Update this grader?_ dialog, which calls AI Configs "prompts." Saving updates the grader for the latest version of each AI Config that uses it. Eval runs that already finished keep the grader version they used. ## Choose where a grader runs Targeting rules decide which offline evals include a grader and which live traffic it grades online. Set them in the **Targeting rules** section of the grader's _Setup_ tab. Each rule is an offline rule, an online rule, or both. To add a rule: 1. On the grader's _Setup_ tab, under **Targeting rules**, click **Add rule**. 2. Check **Offline**, **Online**, or both. 3. Set the rule's conditions. For each condition, choose a field, an operator, and one or more values. 4. For an online rule, enter the percentage of matching traffic to grade in **Sample**. 5. Click **Save Grader**. A rule can be both offline and online when its only condition is "AI config is any of." The **Sample** percentage then applies to online grading only, because offline evals grade every row. ### Offline rules An offline rule adds the grader to the version evals of AI Configs. It takes exactly one condition, "AI config is any of," with no sampling. Check **Critical** to make the grader a [critical grader](#what-is-a-critical-grader) for these AI Configs. On each AI Config's _Setup_ tab, the grader card shows an Offline badge. Adding a grader from an AI Config's _Setup_ tab with **Add grader** has the same effect as an "AI config is any of" rule. A version eval runs at most 10 graders. Runs on the _Evals_ page don't use offline rules. Each run uses the graders you pick when you create the run. ### Online rules An online rule grades a sample of live traffic as it arrives. Only graders that can run online, as listed in [Grader types](#grader-types), can have online rules. Online evals grade one span for each agent turn: the workflow span when the trace has one, or else the outermost LLM call. The span must carry input and output messages, and tool spans are never graded. Spans don't need an AI Config, so a rule can also grade traced LLM calls that your app makes without one. For how to send traces, go to [Online Evals](https://docs.statsig.com/ai-evals/online-evals). An online rule matches a span when all of its conditions match. A rule with no conditions matches every span. Each condition uses one of these fields: | Field | Matches | | --- | --- | | AI config | The span's AI Config, from `statsig.llm.prompt_name` | | Environment | `statsig.environment` | | Span name | The span's name | | Model | The requested model, from `gen_ai.request.model` | | Span attribute | Any span attribute. Enter the attribute name, then the values. | Each condition uses the operator **is any of** or **is not**. Values match exactly, with no wildcards, and can't contain `%`. A span that doesn't have the attribute counts as an empty value, so **is not** matches it. Each grader grades a span at most once, under the first enabled online rule that matches the span. Use the arrows on a rule to move it up or down. **Sample** sets the percentage of matching traces that the rule grades, from 0 to 100. New rules start at 10%. Statsig samples by trace: it hashes the trace ID, so every span in a trace gets the same sampling decision. Online grading has these limits: - Statsig grades at most 1,000 spans per hour for each AI Config that has online eval turned on. Other spans that online rules grade share one limit of 1,000 spans per hour for your company. - Statsig processes online-eval traces in the US only. Statsig plans to support EU data residency. ### Turn on online eval for an AI Config A rule with an "AI config is any of" condition grades that AI Config's spans only while online eval is on for the AI Config. To turn it on, an admin opens the actions menu in the AI Config's header and clicks **Enable Online Eval**. The AI Config needs at least one saved online grader first. **Pause Online Eval** in the same menu turns online eval off. While online eval is off for an AI Config, each rule that names the AI Config skips the AI Config's spans. Statsig checks those spans against the grader's later rules instead. The rule shows a warning that online evals are off for the AI Config, and the AI Config's grader card shows a Paused badge. Rules that don't name the AI Config keep grading its spans. ### Disable an online rule To stop an online rule without deleting it, clear its **Online** checkbox and save. Statsig keeps the rule, and AI Config grader cards show it with a Disabled badge. ### Who can edit targeting rules Enabled online rules start grading live traffic, so a project or org admin must save any change to them. This includes adding, editing, disabling, or deleting an enabled online rule. Anyone who can edit the grader can change its offline rules and its disabled online rules. ### Targeting rule errors **Save Grader** stays disabled until every rule is valid. These messages explain what to fix: | Message | Fix | | --- | --- | | Check Offline, Online or both | Check at least one of **Offline** and **Online**. | | Offline rules need one "AI config is any of" condition | Reduce the offline rule to one "AI config is any of" condition. | | Every condition needs at least one value | Add a value to each condition, or remove the empty condition. | | Span attribute conditions need an attribute name | Enter the attribute name in the Span attribute condition. | | Condition values cannot contain % | Remove `%` from the value. Values match exactly. | | Sampling rate must be between 0% and 100% | Enter a **Sample** value from 0 to 100. | | Online rules need a grader that reads just `{{input}}`, `{{output}}` and `{{trajectory}}` | Remove the online rules, or change the definition so the grader can run online. | ## What is a primary grader A primary grader is the grader whose score becomes an AI Config version's overall score, the number you compare across versions. Each AI Config has one primary grader. To change it, open the menu on a grader card in the AI Config's _Eval Setup_ section and click **Set as Primary**. If you remove the primary grader, the next grader becomes primary. ## What is a critical grader A critical grader is a must-pass check for an AI Config's version evals. When a critical grader's score for a run is 0, the whole run fails. The run shows "This eval run failed due to the critical grader" with the grader's name, and the version's overall score is 0. When a critical grader scores above 0, it behaves like any other grader. For example, if your app parses an AI Config's output as JSON, mark a JSON Validity grader critical for that AI Config. A version whose output never parses then fails its eval, whatever its other graders score. You set Critical separately for each AI Config. Make a grader critical for an AI Config in either place: - On the AI Config's _Setup_ tab, open the menu on the grader card and click **Set as Critical Grader**. - On the grader's _Setup_ tab, check **Critical** on an offline rule with an "AI config is any of" condition. Critical grading applies to offline evals only. ## Review a grader's results The grader's _Results_ and _Traces_ tabs show where it runs and how it scores. - **Results**: The _Used by_ table lists each AI Config and Playground that uses the grader. Its Type column shows Prompt for an AI Config. The _Eval runs_ table lists each eval that ran the grader, with columns for Score, Eval, Type, Config, and Last run. Type is Online for online evals and On Demand for all other evals. A grader that nothing uses shows "This grader is currently unused." - **Traces**: The AI traces that the grader scored, from the last day by default. Change the time range or add filters, and click a trace to open its details. Statsig tracks scores by grader ID, so renaming a grader keeps its history. ## Grader costs LLM as a Judge graders and Text Similarity graders that use Cosine call a model provider. Statsig charges these calls to your Included Credits unless your company has its own API key for the provider. Other graders run inside Statsig at no cost. | Grader | Provider it calls | Cost | | --- | --- | --- | | LLM as a Judge | The provider in **Evaluation Model** | Included Credits, or your own key for that provider | | Text Similarity with Cosine | OpenAI, for `text-embedding-3-large` embeddings | Included Credits, or your own OpenAI key | | String Comparison, Python, and other Text Similarity functions | None | Free | Statsig doesn't meter calls on your own API keys. An admin adds keys in _Settings > Product Configuration > General_, under **AI Provider API Keys**. When your Included Credits run out, online evals keep running the graders that use your own keys and skip the rest. For details on Included Credits, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). ================================================================================ # Datasets URL: https://docs.statsig.com/ai-evals/datasets ================================================================================ # Datasets A dataset is a table of test cases that Statsig Agent Experimentation evals grade. Each row is one test case, such as a user question and the answer you expect. Each column is a variable that prompts and graders reference by name, such as `{{input}}`. Use a dataset to grade an AI Config version, or outputs your agent already produced, against the same cases every time. To grade live production traffic instead, use [online evals](https://docs.statsig.com/ai-evals/online-evals). A dataset holds test cases, not graders. An AI Config's version evals use the graders attached to the AI Config. A run on the _Evals_ page uses the graders you pick when you create the run. Refer to [Choose where a grader runs](https://docs.statsig.com/ai-evals/graders#choose-where-a-grader-runs). ## Global and local datasets Agent Experimentation has two kinds of dataset: | Kind | Where you create it | Listed on the _Datasets_ page | | --- | --- | --- | | Global | The _Datasets_ page, AI Traces, or **Make Dataset Global** in an AI Config | Yes | | Local | An AI Config's _Eval Setup_, or a new local dataset for a run on the _Evals_ page | No | Any AI Config or eval can use a global dataset. A local dataset belongs to the AI Config or run that created it. ## Create a dataset from a CSV file 1. Go to _Agent Experimentation > Datasets_ and select **Create**. 2. Enter a **Dataset Name** and an optional **Description**. Each global dataset in a project needs a unique name. 3. Drag a CSV file onto the upload area, or select **Upload CSV** and choose the file. 4. Check the preview, then select **Upload**. Statsig creates a global dataset and opens its page. To mark output or image columns, use the column menu after the upload. Refer to [Output and image columns](#output-and-image-columns). ### CSV format The first row of the file holds the column names, and each later row becomes one test case: ```csv input,expected_output,categories "My order arrived damaged. What should I do?","Apologize and offer a replacement.","shipping,refunds" How do I reset my password?,Send the password reset link.,account ``` Statsig converts column names to lowercase, replaces spaces with underscores, and removes every other character that isn't a letter, digit, or underscore. For example, a column named `Expected Answer` becomes `expected_answer`, which you reference as `{{expected_answer}}`. Two column names have special behavior: | Column | What Statsig does with it | | --- | --- | | `categories` | Reads a comma-separated list of categories for each row and stores them as row categories, not as a regular column. Optional. | | `annotations` | Suggests categories from the annotation text when more than five rows have a value. Optional. Refer to [Suggested categories](#suggested-categories). | The upload accepts one CSV file of up to 2 MB and 1,000 rows. Statsig skips empty rows. ## Add a dataset to an AI Config Every version of an [AI Config](https://docs.statsig.com/ai-evals/prompts) runs its offline evals against the same dataset. To choose that dataset, open the AI Config's _Setup_ tab. In the _Eval Setup_ group, under _Dataset_, select **Select a Dataset**, then choose one option: - **Upload Dataset**: Upload a CSV file as the AI Config's local dataset. - **Browse from Existing Datasets**: Search the global datasets and pick one. - **AI Dataset Generation**: Describe the test cases you want in a prompt and set **Total rows**, from the default of 20 up to 300. Select **Preview Dataset** to inspect the rows, or **Apply Dataset** to use them as the AI Config's local dataset. - **Make Dataset Global**: Convert the AI Config's local dataset into a global dataset. The dataset then appears on the _Datasets_ page, and other AI Configs and evals can use it. The dataset table under _Dataset_ works like the table on a dataset's page, and you save its edits with the AI Config. Each kind of change affects the dataset differently: - **Upload or generate a dataset**: Statsig replaces the rows of the AI Config's local dataset. If the AI Config uses a global dataset, Statsig detaches it and creates a new local dataset. The global dataset doesn't change. - **Switch to another dataset**: Statsig deletes the rows of the AI Config's local dataset. To keep those rows, select **Make Dataset Global** before you switch. - **Edit a global dataset**: Edits you make from inside an AI Config change that dataset for every AI Config and eval that uses it. Each upload, generated dataset, or edit starts a new dataset version for the AI Config. The AI Config's _Evals_ tab compares two runs only when both used the same dataset version. ## Edit rows and columns Open a dataset from the _Datasets_ page to edit it on the _Setup_ tab. Your edits apply only after you select **Save** in the save bar, and **Discard Changes** reverts them. If you try to leave the page with unsaved changes, Statsig asks you to confirm. To work with rows: - Filter the table with **Search**. - Select **Add Row**, fill in each column in the drawer, and confirm the row. - Select a row to open it in a drawer. Select **Edit** on a column, change the value, and select **Save**. Press the up and down arrow keys to move between rows. - Select a row's delete icon to remove it. A dataset must keep at least one row. To work with columns, open the menu in a column header: - **Add Column**: Add a new column. - **Mark as Output** or **Unmark as Output**: Set or clear the column's output flag. - **Mark as Image** or **Unmark as Image**: Set or clear the column's image flag. - **Delete Column**: Remove the column. A dataset must keep at least one column. To rename a column, select its name and type a new one. Each column needs a unique name that isn't empty. ### Output and image columns An icon in the column header shows each flag: - **Output column**: Holds an output your agent already produced. A run on the _Evals_ page grades the values in the output column. A run can use a dataset only after you mark at least one output column. Evals that you start from an AI Config generate their own output, so they don't need an output column. - **Image column**: Holds image URLs. Statsig sends those images to LLM-as-a-judge graders along with the grading prompt. When you create a local dataset for a run on the _Evals_ page, the upload drawer also shows **Output Columns** and **Image Columns**. That drawer requires at least one output column. ## Categorize rows Categories group rows so a run on the _Evals_ page can show scores for each category. A row's categories appear in the `categories` column at the end of the table. - **Add a category to a row**: Hover over the row's `categories` cell, select the add icon, and pick a category. To create a category, type a name of up to 30 characters and select the **Create** option. - **Remove a category from a row**: Select the delete icon on the category chip. - **Rename or delete categories**: Select **Manage Categories** at the bottom of the category picker. Edit the list, select **Add New Category** to add one, and then select **Save**. ### Suggested categories Statsig suggests categories when you create a dataset in which more than five rows have an `annotations` value. An LLM reads each annotation and proposes short categories for its row. Datasets you create from annotated traces often qualify. The console calls these suggestions tags. After the suggestions are ready, the toolbar shows two options: - **Apply all suggested tags**: Add every suggested category to its rows. - **Review Results**: Open _Suggested Tags_, which lists each suggestion with the annotations behind it. Clear the suggestions you don't want, and then apply the rest. When any row has an `annotations` value, **All** and **Annotated** tabs appear above the table. The **Annotated** tab shows only the rows that have annotations. ## Add traces from AI Traces [AI Traces](https://docs.statsig.com/ai-evals/ai-traces) can turn production spans into test cases: 1. Go to _Agent Experimentation > AI Traces_. 2. Select one or more spans and select **Add to Dataset**. You can also open a trace and select **Add to dataset**. 3. Pick a global dataset, or find one with **Search datasets**. To start a new dataset, select **Create new Dataset**, enter a **Dataset Name**, and select **Create**. Each selected span becomes one row with these columns: | Column | Value | | --- | --- | | `input` | The span's input messages from `gen_ai.input.messages`, one `role: text` line per message. | | `output` | The text of the final assistant message in `gen_ai.output.messages`, without tool calls or earlier steps. | | `metadata` | JSON with the model, token counts, AI Config name (`promptName`), trace and span IDs, status, and timing. | | `annotations` | JSON list of the span's annotations. Statsig adds this column only when the span has annotations. | The span's tags become the row's categories. When you add spans to an existing dataset, Statsig adds any of these columns that the dataset lacks. The dataset keeps its output and image flags. A new dataset from AI Traces has no output column. To use it in a run on the _Evals_ page, select **Mark as Output** on the `output` column. ## View the runs that used a dataset A dataset's _Results_ tab lists the runs on the _Evals_ page that used the dataset, with columns for Score, Run, Eval, and Started. A run that's still grading shows a Running badge, and a failed run shows an Error badge. Evals that you start from an AI Config don't appear here; their results are on the AI Config's _Evals_ tab. Refer to [Offline evals](https://docs.statsig.com/ai-evals/offline-evals). ## Export or delete a dataset Open the more-actions menu in the dataset's header: - **Export to CSV**: Download the rows as a CSV file. When rows have categories, the file includes a `categories` column, so you can upload it again. The file doesn't record output or image flags. - **Delete**: Delete the dataset after you confirm. ================================================================================ # Evals URL: https://docs.statsig.com/ai-evals/evals ================================================================================ # Evals An eval in Statsig Agent Experimentation grades outputs that already exist and keeps every run, so you can track scores over time. Each run applies [graders](https://docs.statsig.com/ai-evals/graders) to the output column of a [dataset](https://docs.statsig.com/ai-evals/datasets). The outputs can be answers your agent produced, responses from a model you plan to replace, or production traces. Compare runs to find out whether a change to your agent, model, or graders raised or lowered scores. Use an eval when you already have the outputs. To generate outputs from AI Config versions and grade them, run an [offline eval from the AI Config](https://docs.statsig.com/ai-evals/offline-evals) instead. To grade live traffic as it arrives, use [online evals](https://docs.statsig.com/ai-evals/online-evals). ## Evals and AI Config evals Both kinds of eval grade every row of a dataset. They differ in where the output comes from and in what they compare. | Difference | Eval on the _Evals_ page | Offline eval from an AI Config | | --- | --- | --- | | Output it grades | The output column of the dataset, or results you score in your own code | Output that Statsig generates by running each AI Config version on the dataset's inputs | | Dataset | Needs at least one output column | Needs inputs only | | Graders | Chosen for each run | Attached to the AI Config | | Results | The eval's _Runs_ and _Compare_ tabs | The AI Config's _Evals_ tab | | What you compare | Runs of the eval | Versions of the AI Config | ## Create an eval An eval holds a series of runs. Create one eval for each thing you want to track, such as an agent or a regression suite. 1. In the Statsig console, go to _Agent Experimentation > Evals_. 2. Click **Create**. If your project has no evals yet, click **Create an Eval**. 3. In the _Create New Eval_ dialog, enter a name and an optional description. 4. Click **Create**. Statsig opens the new eval on its _Runs_ tab, with the form for its first run. The _Evals_ page lists each eval with its name, last modified date, and creator. Search the list, filter it by creator, or sort it by name or last modified date. To delete an eval, open it, open the more actions menu (**⋯**) in the header, and click **Delete**. Statsig deletes the results of every run on the eval. ## Create a run A run grades every row of one dataset with the graders you choose. The dataset needs at least one [output column](https://docs.statsig.com/ai-evals/datasets#output-and-image-columns), which holds the output to grade. 1. Open the eval's _Runs_ tab. A new eval already shows the run form. Otherwise, click **Create** above the list of runs. 2. In **Run Name**, enter a name for the run, such as the change it tests. 3. Under _Dataset_, click **Select a dataset**. Pick a dataset from the list, or click **Create new local dataset** to upload a CSV file and mark its output columns. 4. Click **Add Grader**, and then pick a grader from the catalog or click **Create new grader**. Repeat for each grader. Graders you create here join the [Graders](https://docs.statsig.com/ai-evals/graders) catalog. 5. (Optional) To change a grader's role in the run, open its more actions menu (**⋯**) and click **Set as Primary** or **Set as Critical Grader**. 6. Click **Create Run**. Statsig grades the rows in the background. The run's card shows a progress bar until grading finishes. The dataset list shows global datasets and the datasets of earlier runs on this eval. You can't pick a dataset that has no output column. A local dataset that you create in the run form belongs to the eval and doesn't appear on the _Datasets_ page. **Create Run** stays disabled until the run has a name, a dataset, and at least one grader. It also stays disabled when your company has used up its Included Credits and has no OpenAI API key. For details, go to [Grader costs](https://docs.statsig.com/ai-evals/graders#grader-costs). ### What graders read from each row Graders read the row's output column as `{{output}}`. If the dataset has more than one output column, `{{output}}` holds a JSON object that maps each output column name to its value. A column named `input` fills `{{input}}`, and a column named `trajectory` fills `{{trajectory}}`. Graders can also reference any other column by name. For the full list of variables, go to [Write a judge prompt](https://docs.statsig.com/ai-evals/graders#write-a-judge-prompt). ### Primary and critical graders in a run - **Primary grader**: The run's card shows the primary grader's score. The first grader you add is the primary grader. - **Critical grader**: A must-pass check. When a critical grader's score for the run is 0, the run's score is 0, whatever the other graders score. For more about critical graders, go to [What is a critical grader](https://docs.statsig.com/ai-evals/graders#what-is-a-critical-grader). ## Review a run The _Runs_ tab lists the eval's runs on the left. Each run card shows the run's name, its score, and how long ago it started. Search the list with **Search runs**, and click a run to open it. To delete a run, open the more actions menu (**⋯**) on its card and click **Delete**. A run has two tabs: _Run Results_, which opens first, and _Run Setup_. ### Results for each grader The _Run Results_ tab shows one card for each grader. The card header shows the grader's name, type, and score for the run. For graders that call a model, the header also shows the average number of tokens the grader used for each row. A Primary badge or a Critical chip marks those roles. Click a card to expand it: - **Score**: A gauge with the grader's mean score. It shows "No Score" when the grader scored no rows. - **Categories**: When the dataset's rows have [categories](https://docs.statsig.com/ai-evals/datasets#categorize-rows), click **All** or a category tab to filter the score and the rows. A bar chart shows the score for each category. Click a bar to open that category's tab. - **Rows**: A table with the dataset's columns, including the output column, and the grader's Score for each row. Search the rows, filter them by score, pick the columns to show with **Columns**, or click **Download results as CSV**. A row that a grader couldn't score shows N/A. Statsig leaves unscored rows out of the grader's score and its category scores. Click a row to open _Row Details_. The drawer shows the row's columns and the grader's score. For LLM as a Judge graders, _Judge Response_ shows the judge's reasoning. Expand _Evaluation Prompt_ to read the grader's prompt with the row's values filled in. Press the up and down arrow keys to move between rows. ### What a run used The _Run Setup_ tab shows what the run used: - **Graders**: A card for each grader, with the version that the run used. "Latest version" means the grader hasn't changed since the run. Otherwise, the card shows "Version N of M, used for this run" and a **View current grader** link. Expand a card to read the grader's definition and targeting rules. Editing a grader later doesn't change the run's results. - **Dataset**: A preview of the dataset's rows, with search. Icons mark the output and image columns. Click the dataset's name to open its page. - **Parameters**: Any parameters that your code sent with its results. Refer to [Send results from your code](#send-results-from-your-code). ## Compare runs The _Compare_ tab shows how scores change across the eval's finished runs. It leaves out runs that are still grading and runs that failed. What the tab shows depends on whether runs share a dataset: - **Runs that share a dataset**: Statsig compares them in a card named after the dataset. Choose a **Baseline** run and one or more **Runs to compare**. The baseline starts as the earliest run, and the comparison starts as the latest run. For each grader and category, Statsig compares the scores of the rows that both runs scored and shows whether the change is statistically significant. - **Runs that don't share a dataset**: Each grader gets a chart of its mean score over time, after at least two of these runs finish. Each chart has an **All** tab and a tab for each category. Runs from production traces, and results from your code that don't name a dataset, usually appear here, because each of these runs has its own dataset or none. Until a second run finishes, the tab shows "A second finished run shows a comparison here." ## Grade the past hour of production traces A project or org admin can turn the past hour of an AI Config's production traces into a run. Statsig grades the run with the AI Config's [online graders](https://docs.statsig.com/ai-evals/graders#online-rules). Use a run from traces to check an AI Config's live outputs on demand. Start the run in either place: - **From the AI Config**: In the AI Config's header actions menu, click **Enable Online Eval**. In the _Enable online eval_ dialog, click **Run online graders for the last hour of traces instead**. - **From the AI Config's eval**: Open the more actions menu (**⋯**) in the eval's header and click **Run eval from traces**. **Navigate to original prompt** in the same menu opens the AI Config. Statsig builds the run in four steps: 1. Statsig collects the AI Config's spans from the past hour that have input and output messages. When a trace has a workflow span, Statsig uses only that span. It skips tool spans and the spans that Statsig generates itself. 2. Statsig builds a local dataset with one row per span. The columns are `Input`, `Trajectory`, and `Output`, plus `Prompt Version ID` and `Template Variables`. `Output` is the output column. 3. Statsig grades the dataset with the AI Config's online graders. 4. Statsig adds the run to the AI Config's eval. The first time, Statsig creates that eval with the name `auto_eval_from_traces_eval:` followed by the AI Config's name. The run's name is the hour it covers, as a timestamp such as `2026-11-04T15:00:00.000Z`. Its card shows an Auto chip, and its _Run Setup_ tab explains where the run came from. The scores also appear on the original spans in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces). The AI Config needs at least one online grader. If no span from the past hour qualifies, Statsig doesn't create a run. ## Send results from your code You can score outputs in your own code and record the results as runs on an eval: - **AI SDKs**: The `Eval()` function in the [Node](https://docs.statsig.com/ai-evals/node#programmatic-evaluation) and [Python](https://docs.statsig.com/ai-evals/python#programmatic-evaluation) AI SDKs runs your task and scorers on each record, and then sends the results to the eval you name. - **Console API**: The [Send eval results](https://docs.statsig.com/api-reference/evals/send-eval-results) endpoint, `POST /console/v1/evals/send_results/{name}`, accepts results that you scored anywhere. `Eval()` sends its results through this endpoint. Both methods need an existing eval with the name you send. Create the eval first, on the _Evals_ page or with [Create Eval](https://docs.statsig.com/api-reference/evals/create-eval). If no eval has the name, Statsig rejects the results with a 404 error. Give each eval a unique name, because Statsig finds the eval by name. Requests authenticate with a Console API key. Each call adds one run to the eval. Statsig names the run with the name you send, or `Eval Run N` when you don't send one. The results appear on the run as follows: - **Scores**: Each named score becomes a grader card on _Run Results_. The first score is the primary grader unless the request sets `primaryGrader`. Scores listed in the request's `criticalGraders` are critical. - **Categories**: Each record's categories become category tabs. - **Summary scores**: These appear in a _Summary Scores_ card on _Run Results_. - **Parameters**: These appear on _Run Setup_. - **Trace IDs**: When a result includes a `traceID` and `spanID`, its scores also appear on that span in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces) as offline eval scores. To compare runs row by row, name a [dataset](https://docs.statsig.com/ai-evals/datasets) in the request's `dataset` field, by its name or ID, and give each result the `rowID` of a different row of that dataset. Statsig rejects the results when a `rowID` is missing, repeated, or not a row of the dataset. Runs on the same dataset appear in the dataset's card on the _Compare_ tab. In the Node AI SDK, pass `statsigDataset()` as `Eval()`'s `data`. For details, go to [Run an eval on a Statsig dataset](https://docs.statsig.com/ai-evals/node#run-an-eval-on-a-statsig-dataset). Runs without a dataset appear on the mean score charts on the _Compare_ tab. To start a run on a dataset with catalog graders from code, call [Create Eval Run](https://docs.statsig.com/api-reference/evals/create-eval-run), and then read the results with [Get Eval Run Results](https://docs.statsig.com/api-reference/evals/get-eval-run-results). The Console API calls AI Configs prompts, so to link an eval to an AI Config, pass the AI Config's name or ID as `promptID` when you create the eval. ## Traces for eval rows Statsig links each graded row of a run that you create on the _Evals_ page to a trace in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces). The trace shows the row's input and output next to its scores. - **First run**: Statsig creates a small trace for the row in the `eval` [environment](https://docs.statsig.com/ai-evals/ai-traces#environments). - **Later runs**: Statsig adds their scores to the same trace, so the row's scores from every run stay together. - **Edited rows**: After you edit a row's values, its next run creates a new trace. - **Rows copied from production traces**: A row that Statsig copied from a production trace, and that you haven't edited, adds its scores to the original trace. These scores appear on the trace's _Graders_ tab as offline eval scores, with a **View eval** link to the run. They don't count toward online eval results. AI Traces hides the `eval` environment by default, so remove that filter to find these traces. ================================================================================ # Playground URL: https://docs.statsig.com/ai-evals/playground ================================================================================ # Playground The Statsig Playground runs up to 10 prompts on the same inputs and shows their outputs side by side. Each output includes the latency and token count of the response. Use the Playground to try different models, messages, and parameters before you create an [AI Config](https://docs.statsig.com/ai-evals/prompts). When a prompt works the way you want, promote the playground's prompts to a new AI Config. The Playground doesn't grade outputs, and it runs on 10 inputs at most. To score AI Config versions against a full dataset with graders, run an [offline eval](https://docs.statsig.com/ai-evals/offline-evals) instead. ## Create a playground 1. In the Statsig console, go to _Agent Experimentation > Playground_. The list shows each playground's name, last modified date, and creator. 2. Click **Create**. 3. In the _Create New Playground_ dialog, enter a name. You can also add a description, a team, and tags. 4. Click **Create**. Statsig opens the new playground on the _Setup_ tab. A new playground has one blank prompt and an empty inputs table with one column, `input`. To delete a playground, open the more actions menu (**⋯**) in the header and click **Delete**. Statsig deletes the playground with its prompts and inputs. You can't undo a deletion. ## Set up prompts The _Setup_ tab shows the playground's prompts side by side. Statsig labels them A, B, C, and so on, in order. Each prompt has its own provider, model, parameters, and messages. To configure a prompt: 1. Select a provider and a model from the menus next to the prompt's letter. 2. To change model parameters, click the options icon next to the model. You can set **Temperature**, **Top P**, **Frequency Penalty**, **Presence Penalty**, and **Max Tokens**. 3. Write the prompt's messages. Set the role of each message to **System**, **User**, or **Assistant**. To add a message, click **Message**. 4. To use an input in a message, click its variable in the _Variables_ list below the messages. For example, `{{input}}` refers to the `input` column. When the playground runs, Statsig replaces each variable with the row's value. To add a prompt, click **Clone Prompt** at the top of the tab. Statsig adds a copy of the last prompt. To copy or remove a specific prompt, open that prompt's more actions menu (**⋯**) and click **Clone Prompt** or **Delete Prompt**. A playground holds 1 to 10 prompts. ### Start from an AI Config To start from a prompt you already serve, click **Start from config** on a prompt on the playground's _Setup_ tab, then select an AI Config. Statsig copies the provider, model, parameters, and messages of the AI Config's Live version into the prompt. The menu shows the Live version number of each AI Config. The menu doesn't list AI Configs whose Live version uses a custom workflow. The copy isn't linked to the AI Config. Edits to the prompt don't change the AI Config, and later changes to the AI Config don't update the prompt. To reset the prompt to a blank prompt, select **None** in the same menu. ## Add inputs A playground's _Results_ tab holds the inputs table. Each column is a variable that prompts can reference. Each row is one input, and every prompt runs on every row. - To add a row, click **Add New Input**. The table holds up to 10 rows. - To edit a value, click its cell and type. - To rename a column, click its name. Column names must be unique. - To add, clone, or delete a column, open the column's more actions menu (**⋯**). - To remove a row, click its delete icon. ### Load inputs from a dataset To fill the table from a [dataset](https://docs.statsig.com/ai-evals/datasets), click **Select a Dataset** and choose one of these options: - **Browse from Existing Datasets**: Statsig copies the first 10 rows of the dataset you select. If the dataset has more than 10 rows, a message shows how many of its rows Statsig copied. - **Upload Dataset**: Statsig keeps the first 10 rows of the CSV file you upload. - **AI Dataset Generation**: Statsig generates rows with AI. Each option replaces the playground's columns and rows. The playground keeps its own copy of the rows, so edits in the playground don't change the original dataset. ## Save and run a playground Statsig keeps unsaved changes when you switch between a playground's _Setup_ and _Results_ tabs. If you leave the page with unsaved changes, Statsig asks you to confirm. The header has these controls: - **Save Changes** (save icon): Saves the prompts and inputs. You can save a playground that has empty messages or empty rows. To save, column names must be unique and not empty, and parameters must be in the ranges listed in [Playground limits](#playground-limits). - **Discard Changes** (reset icon): Returns the playground to its last saved state. - **Start**: Saves any unsaved changes, runs every prompt on every row, and opens the _Results_ tab. **Start** stays disabled until the playground can run. Hold the pointer over **Start** to show the reason. A playground can run when all of these conditions are true: - Every prompt message has content. - Every prompt that uses Google or Anthropic has at least one **User** message. - The inputs table has at least one row, and every row has a value in at least one column. - Included Credits remain, or you've added an API key for each provider that the prompts use. For details, go to [Credits and API keys for playground runs](#credits-and-api-keys-for-playground-runs). Each run replaces the previous results. You can't save the playground while a run is in progress. ### Read run results After a playground run, the _Results_ tab shows one output column for each prompt, labeled with the prompt's letter. Each output cell shows the response, the latency in seconds, and the token count. Click an output cell to open the _Run Details_ drawer for that row. For each prompt, the drawer shows: - **Metrics**: The latency and token count. - **Inputs**: The row's value for each column. - **Output**: The full model response. - **Resolved Prompts**: The messages Statsig sent to the model, with each variable set to the row's value. After a run, editing an input value or changing the columns clears the affected outputs. Those cells show "Click start to generate output" until the next run. Changes to prompts don't clear existing outputs, so click **Start** again to get outputs for a changed prompt. ## Credits and API keys for playground runs Each playground run calls the model provider of every prompt. If you haven't added your own API key for a prompt's provider, the run uses your Included Credits. When Included Credits run out, **Start** stays disabled until you add an API key for each provider that the prompts use. An admin adds keys in _Settings > Product Configuration > General_, under **AI Provider API Keys**. For how Included Credits work, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). ## Promote prompts to an AI Config To turn a playground's prompts into an AI Config: 1. In the header, click **Promote to Config**. 2. In the _Create New AI Config_ dialog, review the name. The name defaults to the playground's name. You can also add a description, a team, tags, and target applications. 3. Click **Create**. Statsig creates the AI Config and opens it. Prompt A becomes the Live version. Every other prompt becomes a Draft version, in the same order. **Promote to Config** uses the prompts as they appear on the _Setup_ tab, including unsaved changes. The playground doesn't change. ## Save results as a dataset To keep the outputs of a playground run, open the more actions menu (**⋯**) in the header and click **Save results**. Statsig creates a [global dataset](https://docs.statsig.com/ai-evals/datasets#global-and-local-datasets) and opens it. The dataset has the playground's input columns, plus one output column for each prompt, named A, B, and so on. The dataset name starts with `saved_playground_results:`, followed by the playground ID and a timestamp. Statsig disables **Save results** before the first run and while a run is in progress. ## Review playground history To review changes to a playground, click the history icon in the header. The _Playground History_ dialog lists each change, such as saves and runs, with the person who made it and the time. To open a read-only view of a change, click **View Changes** on its entry. ## Playground limits | Item | Limit | | --- | --- | | Prompts per playground | 10 | | Messages per prompt | 10 | | Rows in the inputs table | 10 | | Rows copied from a dataset or CSV file | First 10 | | Temperature | 0 to 2 | | Top P | 0 to 1 | | Frequency Penalty, Presence Penalty | -1 to 1 | | Max Tokens | 0 to 1,500 | ================================================================================ # Offline Evals URL: https://docs.statsig.com/ai-evals/offline-evals ================================================================================ # Offline Evals An offline eval grades AI output for every row of a fixed dataset of test cases, before any user sees that output. Statsig scores each row with the graders you choose, then reports each grader's score and an overall score for the run. Use offline evals to compare AI Config versions and catch regressions before you promote a version to Live. To grade a sample of live production traffic instead, use [online evals](https://docs.statsig.com/ai-evals/online-evals). To try a few prompts side by side without grading, use the [Playground](https://docs.statsig.com/ai-evals/playground). ## Choose where to run an offline eval Agent Experimentation runs offline evals in two places. Choose the one that matches the outputs you want to grade: | | Eval from an AI Config | Run on the Evals page | | --- | --- | --- | | What it grades | New outputs that each AI Config version generates for every dataset row | Outputs already stored in a dataset's output column | | Use it to | Compare prompt, model, and parameter changes between versions | Grade outputs from your own agent or from production traces, without generating new ones | | Where results appear | The AI Config's _Evals_ tab | The eval's _Runs_ and _Compare_ tabs | This page covers evals from an AI Config. For grade-only runs on stored outputs, go to [Evals](https://docs.statsig.com/ai-evals/evals). To run an eval from your own code with `Eval()`, go to the [Node AI SDK](https://docs.statsig.com/ai-evals/node). ## Set up an eval on an AI Config Every version of an AI Config shares one set of graders and one dataset, so each version's eval grades the same test cases in the same way. Set both on the AI Config's _Setup_ tab, in the _Eval Setup_ group. You need an AI Config with at least one version. To create one, go to [AI Configs](https://docs.statsig.com/ai-evals/prompts). ### Add graders 1. Go to _Agent Experimentation > AI Configs_ and open the AI Config. 2. On the _Setup_ tab, go to the _Graders_ section of the _Eval Setup_ group. 3. Click **Add grader**, then choose one option: - **A grader from the list**: Click its name. The list shows the graders in your company's catalog. - **Create new grader**: Choose a grader type, define the grader in the _Create New Grader_ drawer, and click **Add Grader**. 4. Click **Save**. An AI Config's eval runs at most 10 graders. Graders that you create from an AI Config join your company's catalog. For grader types and how to define them, go to [Graders](https://docs.statsig.com/ai-evals/graders). Each grader appears as a card. To change a saved grader's definition, click the card's edit icon, which opens the grader's page. The card's menu sets the grader's role in this AI Config: - **Set as Primary**: Use this grader's score as each run's overall score. For details, go to [What is a primary grader](https://docs.statsig.com/ai-evals/graders#what-is-a-primary-grader). - **Set as Critical Grader**: Fail the run when this grader's score for the run is 0. For details, go to [What is a critical grader](https://docs.statsig.com/ai-evals/graders#what-is-a-critical-grader). - **Clone Grader**: Add a copy of the grader to this AI Config. - **Remove Grader**: Remove the grader from this AI Config. ### Add a dataset 1. On the AI Config's _Setup_ tab, go to the _Dataset_ section of the _Eval Setup_ group. 2. Click **Select a Dataset**, then choose one option: - **Upload Dataset**: Upload a CSV file as a local dataset for this AI Config. - **Browse from Existing Datasets**: Pick a global dataset. - **AI Dataset Generation**: Generate test cases from a description. 3. Click **Save**. The button then shows the dataset name with its row count. A local dataset shows as "Custom dataset." For dataset limits, row editing, and the differences between global and local datasets, go to [Add a dataset to an AI Config](https://docs.statsig.com/ai-evals/datasets#add-a-dataset-to-an-ai-config). Each dataset column is a variable that the version's prompt can reference by name, such as `{{question}}`. For each row, Statsig fills the variables with the row's values before it calls the model. When a column holds JSON, `{{column}}` inserts the whole value, and a dotted path such as `{{column.items.0.name}}` inserts one field. Graders can reference columns too, such as `{{expected}}`. An eval from an AI Config generates its own output for each row, so its dataset doesn't need an output column. ## Run an offline eval 1. In the AI Config's header, click **Run Eval**. 2. In the _Start Evaluation_ dialog, select the versions to evaluate. Statsig selects every version by default and lists the Live version first. 3. Click **Start Evaluation**. Statsig starts one run for each selected version and opens the AI Config's _Evals_ tab on the first run. While a run is in progress, the tab shows how many rows are complete. A run can take a few minutes. To stop a version's run, select the version on the _Setup_ tab and click **Stop Evaluation** in the header. To evaluate one version, select it in the _Version_ section of the _Setup_ tab, open the version's menu, and click **Start Evaluation**. If the AI Config has unsaved changes, you can't select the version you're editing. When you start an eval on other versions, Statsig asks you to discard the unsaved changes first. To include the edited version, save your changes before you click **Run Eval**. ### Model calls and Included Credits For each row, Statsig calls the version's model provider to generate the output. A version with a custom workflow calls your workflow endpoint instead. LLM as a Judge graders call the provider set in each grader's **Evaluation Model**. Statsig charges these model calls to your Included Credits unless your company has its own API key for the provider. For details, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). ### Why Run Eval is disabled Hover over the disabled button to see the reason: | Message | Cause | Fix | | --- | --- | --- | | No evaluation dataset available | The AI Config has no saved dataset, or its dataset has no rows. | Add a dataset that has at least one row, and save. | | No graders configured | The AI Config has no graders. | Add a grader, and save. | | Changes must be saved before starting an evaluation | The version you're editing has unsaved changes, and the AI Config has no other version. | Save or discard your changes. | | Changes must be saved before this version can be used | In the _Start Evaluation_ dialog, the version you're editing has unsaved changes. | Close the dialog, save your changes, and start the eval again. | | Select at least one version | You haven't selected a version in the _Start Evaluation_ dialog. | Select a version. | | Included Credits have run out | Your Included Credits have run out, and your company has no API key for a provider that the eval calls. | Ask an admin to add an API key for the provider in _Settings > Product Configuration > General_, under **AI Provider API Keys**. | ## Review results on the Evals tab The AI Config's _Evals_ tab shows offline eval results for one version at a time. At the top of the tab, choose **Single version** or **Compare**, then choose a version and a run. Statsig numbers each version's runs in order, such as Run #1 and Run #2. ### Review a single run With **Single version** selected, the _Evals_ tab shows these results for the chosen run: - **Model, Score, and Prompt cards**: The model that the run used, the run's overall score, and the prompt messages that the run used. The overall score is the primary grader's score for the run, from 0 to 1. Click the **Prompt** card to read the full messages. - **Offline graders chart**: Each grader's score for the run, which is the mean of its row scores. A score above 0.66 counts as a pass. - **Results table**: One row for each dataset row, with the output, the latency, and each grader's score. Filter the table with **Search rows**, and use **Columns** to show or hide dataset columns. To export the table, click the **Download results as CSV** icon. Click a row in the results table to open _Row Details_. The drawer shows the row's dataset values, the output, the latency, and a card for each grader with its score. For LLM as a Judge graders, the card lists the judge's reasoning steps. ### Compare two versions To compare two versions' runs, click **Compare**. Choose the version and run to compare. Then, after "relative to," choose the baseline version and run. The baseline is the Live version's latest finished run by default. The comparison shows: - Model, Score, and Prompts cards for both runs. - An Offline graders chart that rates the compared run against the baseline run for each grader: Better, Worse, or No significant change. - A results table with both runs' outputs and scores for each row. _Row Details_ shows the two runs side by side. Statsig compares two runs only when both runs have finished, both have a primary grader score, and both used the same dataset version. Otherwise, the tab explains what's missing, for example "Both runs must use the same dataset version." Each upload, generated dataset, or edit to the AI Config's dataset starts a new dataset version. After you change the dataset, run the eval again on both versions before you compare them. ### Stale runs and critical grader failures Two indicators on the _Evals_ tab mean that a run's score needs attention: - **Stale**: This chip appears when the version changed after the run. The run's results reflect the earlier version. To grade the current version, run the eval again. - **Critical grader failure**: The banner "This eval run failed due to the critical grader" appears, with the grader's name, when a critical grader's score for the run is 0. The run's overall score is then 0. For details, go to [What is a critical grader](https://docs.statsig.com/ai-evals/graders#what-is-a-critical-grader). ### Rows that fail to generate If Statsig can't generate a row's output, for example because the model provider or workflow endpoint returns an error, the results table shows the error in place of the output. The row's graders show "Not graded," and its latency shows N/A. Statsig leaves the row out of grader scores, the run's overall score, version comparisons, and the scores in the CSV download. A grader error is different from a failed row. If a grader fails on a row, such as a Python grader that raises an exception, the row scores 0 for that grader. For details, go to [Write a Python grader](https://docs.statsig.com/ai-evals/graders#write-a-python-grader). ## Find offline eval traces in AI Traces Each row of an offline eval run produces one trace in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces): - The root span has the AI Config's name. Its child span, named `chat` and the model name, such as `chat gpt-5-mini`, records the model call that generated the output. A version with a custom workflow has no child span, because your workflow endpoint makes its own model calls. To show your endpoint's spans under the root span, go to [Join a workflow eval's trace](https://docs.statsig.com/ai-evals/node#join-a-workflow-eval-trace). - Both spans set `statsig.environment` to `eval`, and the Service column shows `statsig-offline-evals`. - The root span records the run, dataset, and row in `statsig.eval.run_id`, `statsig.eval.dataset_id`, and `statsig.eval.dataset_row_id`. - When a row fails to generate, its spans have an error status. AI Traces hides `eval` spans by default. To show them, remove `eval` from the default environment filter in the search bar. For details, go to [Environments](https://docs.statsig.com/ai-evals/ai-traces#environments). Click a span to open the trace drawer. The _Graders_ tab shows each grader's score for the row, with the judge's reasoning for LLM as a Judge graders. Statsig keeps offline eval scores out of the online grader results on the AI Config's _Traces_ tab, so dataset runs don't change the scores for your production traffic. ================================================================================ # Online Evals URL: https://docs.statsig.com/ai-evals/online-evals ================================================================================ # Online Evals Online evals grade your AI app's production traffic. Statsig samples the traces your app sends and picks one span for each agent turn. About one minute after that span arrives, Statsig runs your online graders on it. Online graders score each answer on its own, without an expected answer to compare against. Use online evals to compare an AI Config's Live version with its Candidate versions on real requests. To score versions against a dataset of expected answers before you release them, use [offline evals](https://docs.statsig.com/ai-evals/offline-evals) instead. ## How online evals work An online eval has four stages: 1. Your app answers each request with the AI Config's Live version. It can also run Candidate versions on the same input without showing their answers to users. Your code runs the candidates. Statsig doesn't run them for you. 2. Your app sends a span for each model call to Statsig, tagged with the AI Config and version that produced it. 3. Each grader's online rules decide which spans the grader scores and what percentage of traces it samples. 4. Statsig grades each sampled span once. Scores appear on the span and on the AI Config's _Traces_ tab. Your code can load an AI Config's Live version and its Candidate versions. Draft and Archived versions never reach your code. To manage versions, go to [AI Configs](https://docs.statsig.com/ai-evals/prompts). ## Instrument your app Online grading reads the spans your app sends. Each span needs its input and output messages, its AI Config, and its version. With the [Node AI SDK](https://docs.statsig.com/ai-evals/node), do the following: - Wrap your model client with `wrapOpenAI`, `wrapAnthropic`, or `wrapGemini`, and turn on `captureOptions` for input and output messages. The SDK doesn't record message content by default, and Statsig skips spans without messages. - Call the model inside `prompt.withLive()` or `prompt.withVersion()`. Both functions tag each span with the AI Config name and version. A span without an AI Config doesn't show on any AI Config's _Traces_ tab. - Wrap each multi-step agent turn in one workflow span with `wrap({ type: "workflow" })`. The SDK still calls an AI Config a prompt, so you load one with `getPrompt()`. To send spans without the SDK, set the attributes in the [span attribute reference](https://docs.statsig.com/ai-evals/ai-traces#span-attribute-reference) on each span yourself. The examples on this page share this setup: ```js import OpenAI from "openai"; import { StatsigAI, initializeTracing, wrapOpenAI } from "@statsig/statsig-ai"; // Sends spans to Statsig with the server secret key in STATSIG_SDK_KEY initializeTracing({ serviceName: "support-bot" }); const statsigAI = new StatsigAI({ sdkKey: process.env.STATSIG_SDK_KEY }); await statsigAI.initialize(); // Record the input and output messages that online graders read const openai = wrapOpenAI(new OpenAI(), { captureOptions: { capture_input_messages: true, capture_output_messages: true, }, }); ``` ### Grade a single model call When an agent turn makes one model call, Statsig grades that call. The SDK adds the `statsig.span.llm_root` marker to each model call that isn't inside another model call or a workflow span. An HTTP span or another app span around the call doesn't change the marker. Statsig grades the spans that carry this marker. The following example answers with the Live version. It also runs each Candidate version on the same question in the background. Each call produces its own span, tagged with its version, so Statsig grades each version separately. ```js // Calls the model with one AI Config version function callModel(version, question) { return openai.chat.completions.create({ model: version.getModel({ fallback: "gpt-5-mini" }), messages: version.getPromptMessages({ question }), }); } async function answerQuestion(user, question) { const prompt = statsigAI.getPrompt(user, "support_bot"); // Candidates answer in the background. Users never see these answers. for (const candidate of prompt.getCandidates()) { prompt .withVersion(candidate, (version) => callModel(version, question)) .catch(console.error); } const response = await prompt.withLive((version) => callModel(version, question), ); return response.choices[0].message.content; } ``` ### Grade a multi-step agent turn When one turn makes several model calls or tool calls, wrap the turn in a workflow span. The workflow span ends after every step in the turn, so it can hold the turn's input and final answer. Statsig grades the workflow span as the turn's answer. Statsig never grades tool spans, such as spans from `wrap({ type: "tool" })`. The SDK doesn't record messages on workflow spans. Before the workflow function returns, set `gen_ai.input.messages` and `gen_ai.output.messages` on the active span to the turn's input and final answer. Without these attributes, Statsig skips the workflow span. The SDK doesn't mark the model calls inside a workflow span, so Statsig then grades nothing in the turn. Start the turn inside `withLive()` or `withVersion()` so the workflow span records the AI Config and version. ```js import { trace } from "@opentelemetry/api"; import { wrap } from "@statsig/statsig-ai"; // One workflow span for each agent turn const runTurn = wrap( { type: "workflow", name: "support_turn" }, async (version, question) => { const model = version.getModel({ fallback: "gpt-5-mini" }); // Step 1: draft an answer from the AI Config's prompt const draft = await openai.chat.completions.create({ model, messages: version.getPromptMessages({ question }), }); // Step 2: revise the draft const revision = await openai.chat.completions.create({ model, messages: [ { role: "system", content: "Correct any errors in this answer and shorten it.", }, { role: "user", content: draft.choices[0].message.content ?? "" }, ], }); const answer = revision.choices[0].message.content ?? ""; // The SDK doesn't record messages on workflow spans, so set the turn's // question and final answer for online graders to read trace.getActiveSpan()?.setAttributes({ "gen_ai.input.messages": JSON.stringify([ { role: "user", content: question }, ]), "gen_ai.output.messages": JSON.stringify([ { role: "assistant", content: answer }, ]), }); return answer; }, ); async function answerWithAgent(user, question) { const prompt = statsigAI.getPrompt(user, "support_bot"); // Start the turn inside withLive so the workflow span records the AI Config and version return prompt.withLive((version) => runTurn(version, question)); } ``` > **Warning:** > > In `@statsig/statsig-ai` versions `0.0.1-beta.30` through `0.0.1-beta.33`, the SDK also marks each model call inside a workflow span with `statsig.span.llm_root`. Statsig checks each span on its own, so it grades the workflow span and each model call inside it. Version `0.0.1-beta.34` doesn't mark these calls. If you can't upgrade, add a **Span attribute** condition to the grader's online rule to grade only workflow spans. Set the attribute name to `statsig.span.gen_ai.type`, the operator to **is any of**, and the value to `workflow`. A rule with this condition doesn't grade turns that make a single model call. ## Turn on online grading Online grading starts when a grader has an online rule that matches your spans. When the rule names an AI Config, online eval must also be on for that AI Config. 1. Open a grader that can run online, or create one. LLM as a Judge and Python graders can run online when they read only `{{input}}`, `{{output}}`, and `{{trajectory}}`. For details, go to [Grader types](https://docs.statsig.com/ai-evals/graders#grader-types). 2. On the grader's _Setup_ tab, under **Targeting rules**, click **Add rule** and check **Online**. 3. Add conditions that match your spans. For example, choose **AI config**, choose **is any of**, and select your AI Config. 4. In **Sample**, enter the percentage of matching traces to grade. New rules start at 10%. 5. Click **Save Grader**. A project or org admin must save any change to an enabled online rule. 6. If the rule names an AI Config, turn on online eval for that AI Config. An admin must do this step: in the AI Config's header, open the actions menu, click **Enable Online Eval**, and then click **Enable**. For every rule field and operator, go to [Online rules](https://docs.statsig.com/ai-evals/graders#online-rules). Rules and the AI Config's online eval setting interact in these ways: - Each grader grades a span under the first enabled online rule that matches the span. - Statsig samples by trace. Statsig hashes the trace ID, so every span in a trace gets the same sampling decision. - **Enable Online Eval** needs at least one grader with an enabled online rule that names the AI Config. Only admins can enable or pause online eval. - **Pause Online Eval**, in the same menu, pauses only the rules that name the AI Config. Those rules skip the AI Config's spans, and the grader's later rules can still grade them. Rules that don't name the AI Config keep grading its spans. - A rule without an **AI config** condition can also grade spans that don't belong to any AI Config, such as model calls outside `withLive()` and `withVersion()`. Scores for these spans appear in the trace drawer and on the grader's _Traces_ tab, but not on an AI Config. ## What Statsig grades Statsig checks each span when it arrives. Statsig grades a span when every requirement in this table holds: | Requirement | Span attributes | | --- | --- | | The span is an LLM span. | `statsig.span.type` is `gen_ai`. | | The span is a workflow span or an outermost model call. Statsig never grades tool spans. | `statsig.span.gen_ai.type` is `workflow`, or `statsig.span.llm_root` is `"1"` and `statsig.span.gen_ai.type` isn't `tool`. | | The span has input and output messages. | `gen_ai.input.messages` and `gen_ai.output.messages` aren't empty. | | Statsig didn't generate the span. | `statsig.environment` isn't `eval`, `shadow`, or `online_eval_judge`. Statsig treats a span without `statsig.environment` as production. | | An online rule matches the span and samples its trace. | The attributes in the rule's conditions. | Statsig assigns each score to the AI Config version in `statsig.llm.prompt_version_id`. For spans from older SDKs that record only the version name, Statsig finds the version by its name. A grader reads three values from the span. `{{input}}` holds the input messages, `{{output}}` holds the final assistant answer, and `{{trajectory}}` holds the tool calls and results before that answer. For message formats and every attribute, go to the [span attribute reference](https://docs.statsig.com/ai-evals/ai-traces#span-attribute-reference). For the environment values, go to [Environments](https://docs.statsig.com/ai-evals/ai-traces#environments). ## Online grading limits Online grading has these limits: - **Latency**: A score appears on its span about one minute after Statsig receives the span. The Online graders chart can take longer to show the score. - **Hourly cap**: Statsig grades at most 1,000 spans per hour for each AI Config that has online eval on. A span counts toward its AI Config's cap when every rule that grades it names the AI Config. All other graded spans, including spans without an AI Config, share one cap of 1,000 spans per hour for your company. Statsig doesn't grade spans over a cap, and the trace drawer shows `No grader scores this span.` - **One grade per span**: Each grader grades a span at most once. Statsig retries failed judge calls. If a grader still fails, the span has no score from that grader. - **Included Credits**: When your company's Included Credits run out, Statsig keeps running the graders that use your own provider API key. Statsig skips the other graders. The trace drawer explains that Statsig didn't grade the span. An admin adds API keys in _Settings > Product Configuration > General_, under **AI Provider API Keys**. For which graders use credits, go to [Grader costs](https://docs.statsig.com/ai-evals/graders#grader-costs). For how Included Credits work, go to [Credits and API keys](https://docs.statsig.com/ai-evals/overview#credits-and-api-keys). - **Data residency**: Statsig processes online-eval traces in the US only. Statsig plans to support EU data residency. ## Review online eval results Statsig shows online grades on the AI Config's _Traces_ tab, on each span, and on each grader's page. ### Online graders chart To open the chart, go to _Agent Experimentation > AI Configs_, open the AI Config, and click the **Traces** tab. The Online graders chart appears above the span list and covers the last day by default. Choose a view: - **Single version**: Each grader's average score over time, for the version you select or for **All versions**. Grades that your code logs with `logEvalGrade` appear as separate lines, labeled with the grade name and "(SDK)". - **Compare**: Select the versions to compare with the Live version. For each grader, the chart shows the score change relative to the Live version. The legend marks each change as Better, Worse, or No significant change. ### How Statsig compares versions The Compare view tests each grader's score change for statistical significance at p < 0.05. The test depends on where the scores come from: | Score source | Comparison | | --- | --- | | Online graders | Welch's t-test, unpaired. Each graded span is one sample, because each trace comes from one version. Each version needs at least two scores. | | `logEvalGrade` (SDK) | Paired by `sessionId`. Statsig compares only sessions that have a grade for both versions. | | Offline evals | Not included. Offline evals grade dataset rows, not production traffic. | ### Scores on a span To open a span's scores, click the span in the list, then click the **Graders** tab in the trace drawer. Each score shows its grader and its score. Online grades show the grader type, such as LLM as a Judge or Python. Grades from `logEvalGrade` show SDK. For the full tab, go to [Graders tab](https://docs.statsig.com/ai-evals/ai-traces#graders-tab). A grader's _Results_ and _Traces_ tabs also list its online grades. Statsig tracks scores by grader ID, so a renamed grader keeps its history. For details, go to [Review a grader's results](https://docs.statsig.com/ai-evals/graders#review-a-graders-results). ## Log grades from your code Use `logEvalGrade` to record a score that your own code computes, such as a user's rating or a business outcome. Statsig shows these grades as SDK lines on the Online graders chart and as SDK scores in the trace drawer. ```js statsigAI.logEvalGrade(user, version, 1, "ticket_resolved", { sessionId: conversationId, traceId, spanId, reasoning: "The customer closed the ticket without escalating.", metadata: { channel: "chat" }, }); // Send the grade events to Statsig await statsigAI.flushEvents(); ``` `logEvalGrade` takes these arguments, in order: | Argument | Description | | --- | --- | | `user` | The `StatsigUser` for the request. | | `version` | The AI Config version that produced the answer, such as the version that `withLive()` passes to your function. | | `score` | A number from 0 to 1. The SDK skips scores outside this range and logs a warning. | | `graderName` | The name of the grade, such as `ticket_resolved`. | | `evalData` | An object with optional fields: `sessionId`, `activityId`, `traceId`, `spanId`, `reasoning`, and `metadata`. Always pass this argument. Pass `{}` when you set no fields. | The `evalData` object accepts these fields: | Field | Description | | --- | --- | | `sessionId` | Pairs grades across versions in the Compare view. Use the same ID for the live and candidate answers to one request. | | `activityId` | Adds a `statsig.activity_id` custom ID to the user. | | `traceId`, `spanId` | The span that the grade belongs to in the trace drawer. When you omit both, the SDK uses the active span. | | `reasoning` | Your explanation of the score, logged with the grade. | | `metadata` | Extra string fields to log with the grade. | To grade a workflow span after it ends, such as when a user rates an answer later, save the span's IDs during the turn. Inside the workflow function, `trace.getActiveSpan()?.spanContext()` returns the workflow span's `traceId` and `spanId`. ## Grade events in your project Statsig logs each online grade as a `statsig::eval_result` event in your project. The Online graders chart reads these events. The event's value is the AI Config name, or empty for a span without an AI Config. The events have no user ID. | Metadata field | Value | | --- | --- | | `score` | The score, from 0 to 1. | | `version_id`, `version_name` | The AI Config version that produced the span. | | `grader_id`, `grader_name`, `grader_version` | The grader and the grader version that scored the span. | | `ai_config_name` | The AI Config name. | | `source` | `online_eval`. | | `trace_id`, `span_id` | The graded span. | Statsig logs these events with a server secret key that has the description `AI_EVALS`. Statsig creates the key in your project the first time it logs an online grade. `logEvalGrade` logs the same event name with `source` set to `sdk`. Its events also carry `session_id`, `is_live`, and the fields you pass in `metadata`. Grader metrics in experiments that you create from an AI Config read only grades from `logEvalGrade`. Online grades don't feed those metrics. ================================================================================ # AI Traces URL: https://docs.statsig.com/ai-evals/ai-traces ================================================================================ # AI Traces AI Traces lists the LLM spans your app sends to Statsig: model calls, tool calls, and agent steps, each with its messages, model, token count, cost, and grader scores. Use AI Traces to debug a single agent turn, find slow or failing calls, review outputs by hand, and save useful examples to a dataset. To query every span your services send, including HTTP and database spans, use the [Traces Explorer](https://docs.statsig.com/infra-analytics/send-traces) instead. ## Where traces appear Statsig shows LLM spans in three places in the console: - **AI Traces page**: Every LLM span in your project. Open it from _Agent Experimentation > AI Traces_. - **Traces tab on an AI Config**: Spans tagged with that AI Config, with a filter for the AI Config version. The tab also shows online grader results, described in [Online Evals](https://docs.statsig.com/ai-evals/online-evals). - **Traces tab on a grader**: Spans that the grader scored. The tab opens on the last day of spans. In each of these views, click a span to open the trace drawer. ## Send traces to AI Traces AI Traces shows only spans whose `statsig.span.type` attribute is `gen_ai`. Spans you send by following the generic [Traces Explorer quick start](https://docs.statsig.com/infra-analytics/send-traces) don't carry that attribute, so they appear in the Traces Explorer but not in AI Traces. Choose one way to send LLM spans: - **Node AI SDK**: Call `initializeTracing()` and wrap your model client with `wrapOpenAI`, `wrapAnthropic`, or `wrapGemini`. The SDK sets the required attributes for you. The SDK doesn't record message content by default. Turn on `captureOptions` to see messages in the trace drawer and to make spans eligible for online grading. Call the model inside `withLive()` or `withVersion()` so each span records its AI Config and version. Go to [Node AI SDK](https://docs.statsig.com/ai-evals/node) for setup. - **Raw OpenTelemetry**: Export spans to Statsig over OTLP/HTTP, as the [Traces Explorer quick start](https://docs.statsig.com/infra-analytics/send-traces) shows, and set the attributes in the [span attribute reference](#span-attribute-reference) on each LLM span yourself. The following raw OpenTelemetry span sets the attributes that AI Traces and online grading read. OpenTelemetry attributes can't hold nested objects, so serialize message arrays as JSON strings. `callModel` stands in for your own model call. ```js import { trace } from "@opentelemetry/api"; const tracer = trace.getTracer("support-bot"); await tracer.startActiveSpan("chat gpt-5", async (span) => { const answer = await callModel(question); span.setAttributes({ "statsig.span.type": "gen_ai", "statsig.span.gen_ai.type": "generate_content", "statsig.span.llm_root": "1", // a string, not a number "statsig.llm.prompt_name": "support_bot", "gen_ai.request.model": "gpt-5", "gen_ai.input.messages": JSON.stringify([ { role: "user", parts: [{ type: "text", content: question }] }, ]), "gen_ai.output.messages": JSON.stringify([ { role: "assistant", parts: [{ type: "text", content: answer.text }] }, ]), "gen_ai.usage.input_tokens": answer.inputTokens, "gen_ai.usage.output_tokens": answer.outputTokens, }); span.end(); }); ``` ## Find spans in the explorer The AI Traces page opens on the past hour of spans. The search bar starts with `#environment!:eval,shadow,online_eval_judge`, which hides the spans Statsig generates itself. Remove that filter to include those spans. For what each value means, go to [Environments](#environments). The span scope menu next to the search bar sets which spans the list includes: - **All Spans**: Every LLM span. - **Trace Root Spans**: Only the first span in each trace. A trace whose first span isn't an LLM span, such as an HTTP request span that wraps your model calls, doesn't appear in this view. ### Columns | Column | Shows | | --- | --- | | Timestamp | When the span started. | | Duration | How long the span took. | | Name | The span name. | | Service | The service that sent the span, from the `service.name` resource attribute. | | Config | The AI Config the span belongs to, from `statsig.llm.prompt_name`. | | Graders | One chip per grader score, or `Not graded` when the span has no scores. | Each grader chip shows the grader name and `pass` or `fail`. A score above 0.66 counts as `pass`. The trace drawer shows the exact score. ### Filters Filters in the left rail narrow the span list. | Filter | Filters on | | --- | --- | | Duration (ms) | Span duration. | | Config | The AI Config, from `statsig.llm.prompt_name`. | | Grader | The graders that scored the span. | | Environment | The `statsig.environment` attribute. Only equality filters work. | | Status | Span status, such as `error`. | | Span name | The span name. | | Service | The `service.name` resource attribute. | | Cluster | The `cluster_name` resource attribute. | | Has activity ID | Whether the span has a `statsig.activity_id` custom ID. | ## Inspect a trace Click a span in the list to open the trace drawer. The drawer header shows the trace ID, duration, total tokens, cost in USD, and service, plus the review actions described in [Review and save spans](#review-and-save-spans). ### Span tree The left side of the drawer lists every span in the trace. Use **Search spans** to filter the list by span name, and switch between **Tree** and **Timeline** to show the spans as a hierarchy or on a time axis. Each row shows an icon for the span type (agent or workflow, tool, model call, or step), the span name, the tool or AI Config name, duration, cost, and up to three grader chips. When the selected span has a `statsig.activity_id` custom ID, the drawer loads every span with that activity ID, even across traces. Use an activity ID to group a multi-turn conversation or a long-running job into one view. ### Trace tab The **Trace** tab shows the selected span's messages. Switch between two views: - **Formatted**: A chat transcript that Statsig builds from `gen_ai.system_instructions`, `gen_ai.input.messages`, and `gen_ai.output.messages`. Each turn has a role label, such as System, User, Assistant, or Tool. A tool call appears as `Function call` with the tool name and its input, and a tool result appears as `Function output`. The tab shows `This span has no messages.` when the span has no message attributes. - **JSON**: Input and Output cards with the raw messages, and a Metadata card with every span attribute. Attributes that hold JSON strings expand into objects. ### Details tab The **Details** tab lists the span's Start, Duration, Service, Model, Agent, Trace ID, Tokens, and Cost (USD). Model, Agent, and Tokens appear only when the span sets the matching attribute. Go to the [span attribute reference](#span-attribute-reference) for the source of each field. ### Graders tab The **Graders** tab shows one card per score on the selected span. The tab label shows a count of scores. Each card shows: - The grader name and its score. - A label for the grader type, such as LLM as a Judge, String Comparison, Text Similarity, Python, or Programmatic Grader. Scores with no grader type show their source instead: Online eval, Offline eval, SDK, User feedback, Reviewer, or Other. - The judge's reasoning steps, for LLM-as-a-judge scores. - **View eval**, for scores from an eval run. The link opens that run. A span with no scores shows `No grader scores this span.` If your organization runs out of Included Credits, the tab explains that Statsig didn't grade the span and how to add your own API key. ## Review and save spans Use review actions to mark spans for follow-up and to build datasets from production traffic. Actions in the drawer header apply to the open span. - **Thumbs up or thumbs down**: Record a human review of the span. - **Add tag**: Apply an existing tag, or choose **Create New Tag**. Choose **Manage Tags** to rename or remove tags. - **Add Annotation**: Write a comment on the span. Edit or delete an annotation from its menu. - **Add to dataset**: Choose a dataset, or choose **Create new Dataset** and enter a **Dataset Name**. To act on many spans at once, hover over a row in the list and select its checkbox. A bar shows the number of selected spans with **Add to Dataset**, **Add Tag**, and thumbs up or down. When you add spans to a dataset, each span becomes a row. The `input` column holds the input messages, the `output` column holds the final answer, and the `metadata` column holds the model, token counts, and trace and span IDs. Spans with annotations add an `annotations` column, and a span's tags become categories on its row. ## Environments The `statsig.environment` span attribute records which deployment environment a span came from. AI Traces, the Environment filter, and online grading all read this attribute. A span gets its `statsig.environment` value in one of two ways: - The span sets `statsig.environment` itself. - The span doesn't set it, and the `deployment.environment.name` resource attribute names a non-production environment, such as `staging`. Statsig copies that name into `statsig.environment`. The Node AI SDK sets `deployment.environment.name` from the `environment` option of `initializeTracing()`, or from `NODE_ENV` when you don't pass one. Production spans usually have no `statsig.environment` value, because Statsig copies only non-production names. Online grading treats a span with no value as production, and can grade spans from any of your environments. Statsig reserves three values for spans it generates itself. The AI Traces page hides these spans by default, and online grading never grades them. | Value | Spans | | --- | --- | | `eval` | Offline eval runs, one trace per dataset row. | | `online_eval_judge` | The model calls an online grader makes while it scores your spans. | | `shadow` | Other runs that Statsig generates. | Don't use these values for your own spans. ## Span attribute reference These span attributes control what AI Traces shows and which spans online grading can score. The Node AI SDK sets them for you. If you send raw OpenTelemetry spans, set them yourself. ### Span type and structure | Attribute | Value | What it powers | | --- | --- | --- | | `statsig.span.type` | `gen_ai` | Required. Only spans with this value appear in AI Traces, in the Traces tabs, and in online grading. | | `statsig.span.gen_ai.type` | `workflow`, `agent`, `tool`, `generate_content`, `step` | The icon in the span tree. Online grading grades `workflow` spans and never grades `tool` spans. Without this attribute, Statsig reads `gen_ai.operation.name`, then the first word of the span name, such as `execute_tool` or `invoke_agent`. | | `statsig.span.llm_root` | `"1"` (string) | Marks the outermost LLM call in an agent turn. Online grading grades an LLM span only when it carries this marker or is a `workflow` span. | ### AI Config | Attribute | Value | What it powers | | --- | --- | --- | | `statsig.llm.prompt_name` | The AI Config name you pass to `getPrompt()` | The Config column and filter, and the AI Config's Traces tab. The AI Config's online eval grades only spans with this attribute. Without it, only a grader's grading rules can grade the span. | | `statsig.llm.prompt_version_id` | The AI Config version ID | The version filter on the AI Config's Traces tab, and the version online grading assigns each score to. Older SDKs send `statsig.llm.prompt_version_name` or `statsig.llm.prompt_version`. | The SDK, the API, and these attribute names use `prompt`, the earlier name for an AI Config. ### Messages Set message attributes to JSON strings. AI Traces accepts OpenTelemetry GenAI messages (`role` with `parts`) and OpenAI chat messages (`role` with `content`). | Attribute | What it powers | | --- | --- | | `gen_ai.system_instructions` | System turns in the Formatted view. | | `gen_ai.input.messages` | Input turns in the Formatted view, the Input card in the JSON view, the dataset `input` column, and the `{{input}}` grader variable. Online grading skips spans without input messages. | | `gen_ai.output.messages` | Output turns in the Formatted view and the Output card. The final assistant answer becomes the dataset `output` column and the `{{output}}` grader variable. The tool calls and results before it become `{{trajectory}}`. Online grading skips spans without output messages. | ### Model, tokens, and cost | Attribute | What it powers | | --- | --- | | `gen_ai.request.model` | Model in the Details tab. Statsig also uses it to estimate cost when `gen_ai.response.model` is missing. | | `gen_ai.response.model` | The model Statsig uses first to estimate cost. | | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | Cost estimates. | | `gen_ai.usage.input_cached_tokens` or `gen_ai.usage.cache_read.input_tokens` | Cost estimates. Statsig prices cached input tokens at the model's cached rate. | | `statsig.gen_ai.usage.total_tokens`, `gen_ai.usage.total_tokens` | Tokens in the Details tab. | | `statsig.gen_ai.usage.cost_usd` | Cost (USD) in the drawer and the span tree. If the span doesn't set a cost, Statsig estimates one from the model and token counts for models it has prices for. A cost you send always takes precedence. | ### Agents and tools | Attribute | What it powers | | --- | --- | | `gen_ai.agent.name` | Agent in the Details tab. | | `gen_ai.tool.name` | The tool name on the span's row in the span tree. | | `gen_ai.operation.name` | The span type icon, when the span doesn't set `statsig.span.gen_ai.type`. | ### Grouping and environment | Attribute | What it powers | | --- | --- | | `statsig.environment` | The Environment filter, the default filter that hides Statsig-generated spans, and which spans online grading skips. Go to [Environments](#environments). | | `statsig.custom_ids` | Custom IDs for the span, as a JSON string. Include a `statsig.activity_id` key, for example `{"statsig.activity_id":"conversation-123"}`, to power the Has activity ID filter and group spans across traces in the drawer. | ### Resource attributes Set these on the OpenTelemetry resource, not on individual spans. | Attribute | What it powers | | --- | --- | | `service.name` | The Service column and filter, and Service in the drawer. | | `cluster_name` | The Cluster filter. | | `deployment.environment.name` | The environment. Statsig copies non-production names into `statsig.environment`. Go to [Environments](#environments). | ================================================================================ # Statsig Visual Editor (Low-code Experiments) URL: https://docs.statsig.com/guides/sidecar-experiments/introduction ================================================================================ # Statsig Visual Editor (Low-code Experiments) Statsig's Visual Editor, also called Sidecar, is a low-code tool for building and running A/B tests on your website without engineering work. You use a point-and-click interface to change styling, text content, calls to action, and injected scripts. Statsig assigns visitors to variants and measures the results with its stats engine. ## How A/B testing works A/B testing, or split testing, is a fundamental method in digital marketing for validating website changes. It involves comparing two versions of a webpage to see which performs better with a target audience. Traditionally, implementing A/B tests required substantial technical skills and collaboration between marketers and developers. This requirement led to longer implementation times and reduced agility for marketing teams. ## Statsig's visual editor Statsig's Visual Editor lets marketers run A/B tests with minimal technical dependency. It provides an intuitive, point-and-click interface for setting up and managing A/B tests on your website. You can experiment on styling, text content, calls to action, and injected scripts that change page behavior. Combined with Statsig's [industry-leading stats engine](https://docs.statsig.com/experiments/overview), Sidecar is a useful tool in a marketer's toolkit. ![Statsig sidecar](https://docs.statsig.com/images/guides/sidecar-experiments/introduction/85a65ae3-6651-4d5b-87c0-4dadee6c8c30.png) > **Info:** > > This guide assumes you have an existing Statsig account. Go here to create a new free account if you don't already have one: https://statsig.com/signup ## Performance considerations Sidecar, like any client-side tooling, introduces some degree of page load latency. Test Sidecar and verify that the performance impact falls within your acceptable threshold. Performance-sensitive customers typically use the [JS-SDK](https://docs.statsig.com/client/javascript-sdk) for web testing. When using the JS/React SDKs with [Client Bootstrapping](https://docs.statsig.com/client/concepts/initialize), the latency is minimal because initialization requires no network requests. ================================================================================ # Visual Editor Setup & Usage URL: https://docs.statsig.com/guides/sidecar-experiments/sidecar-v3 Updated: 2026-04-01 ================================================================================ # Visual Editor Setup & Usage > **Warning:** > > Sidecar is in maintenance mode. Existing Sidecar setups continue to work, but Statsig doesn't release bug fixes or new features for Sidecar. > > For visual, low-code experimentation, use [Amplitude Web Experiment](https://amplitude.com/docs/web-experiment). ## How Visual Editor v3 works Visual Editor v3 is a no-code Chrome extension for building and running A/B tests directly on any website. You create the experiment in the Statsig Console, then edit variants on top of the live page with a point-and-click editor. Sidecar still runs through a JavaScript script tag, though the package name has changed from earlier versions. ## Prerequisites ### 1. Installing the Sidecar script For experiments to take effect, the visual editor ("sidecar") script must run on your website, on any page you want to experiment on: ```html <script src="https://cdn.jsdelivr.net/npm/statsig-sidecar-v2-beta/dist/index.min.js?apikey=client-key" ></script> ``` Replace `client-key` with a client key from your Statsig project. You can find it at [Settings > Keys & Environments](https://console.statsig.com/api_keys). Most website builders also support adding script tags on your website, like: [Webflow](https://university.webflow.com/lesson/custom-code-in-the-head-and-body-tags?topics=site-settings), [Wordpress](https://wordpress.com/go/website-building/how-to-properly-add-javascript-to-wordpress-3-top-methods/), [Wix](https://support.wix.com/en/article/embedding-custom-code-on-your-site), [Squarespace](https://support.squarespace.com/hc/en-us/articles/205815928-Adding-custom-code-to-your-site). ### 2. Installing the Chrome extension (for editing) To create edits for experiment variants, install the Statsig Visual Editor [Chrome Extension](https://chromewebstore.google.com/detail/statsig-sidecar-v3/mmgjfcbidnlghegclgpkgegpdhbopjhn). You also need to be a project admin or have permissions to access console API keys to use all Sidecar functionality. ## Creating an experiment Create experiments in the console by opening the Create Experiment dialog and changing the experiment type to "Visual Editor". ![Create Visual Editor Experiment](https://docs.statsig.com/images/sidecarcreation.gif) ## Setting up an experiment ### Metrics When you add the Statsig Visual Editor script to your website, Statsig automatically tracks events like clicks, page views, Core Web Vitals, and more. Statsig calls these [autocapture](https://docs.statsig.com/webanalytics/autocapture/) metrics. Go to [Metrics](https://docs.statsig.com/metrics/101) for more information. You can add any of these metrics to your experiment. You can also customize them to filter to certain attributes (e.g. clicking a certain button, visiting a certain page) by creating a new metric in the [Metrics Catalog](https://console.statsig.com/metrics/metrics_catalog) tab. You must add at least one metric to your experiment before continuing. ### URL filters To limit an experiment to a subset of pages on your website, configure which URLs the experiment runs on: - **All Pages**: anywhere you install the Sidecar client - **Contains**: The page URL must contain the value you enter, for example "pricing". - **Exact Match**: The page URL must match the exact value you specify here. - **Regex**: Regular expressions, for example `(http|https):\/\/www.statsig.com\/pricing` matches pages `http://www.statsig.com/pricing` or \`https://www.statsig.com/ ![URL Targeting](https://docs.statsig.com/images/sidecarv3urlfilters.png) ### Audiences Statsig infers information about each user, including country, device type, browser type, and a unique identifier called StableID. You can target based on any of these attributes using the "audiences" targeting section. You can also target custom attributes you add to the Window.statsigUser object, though adding custom attributes requires a small amount of code. ### Visual Editor starting URL Before editing experiment variants, add a Visual Editor URL. The editor opens at this URL when you begin editing. Add a URL starting with "https://", then click **Save**. To set up an experiment, enter your metrics and any targeting (on URL, or other user attributes from the [StatsigUser object](https://docs.statsig.com/sdks/user)), and the starting URL. The URL must begin with "https://". Click **Save**, then click **Open in Editor**. An editor bar appears along the bottom of the page: ![Visual Editor Page](https://docs.statsig.com/images/sidecarv3openxp.gif) ### Runtime settings For more advanced experiment flows, you can also configure runtime settings on the experiment setup page before opening the editor. - **Disable Auto Run** prevents the experiment from applying automatically on page load. - **Prerun Script** lets you run custom JavaScript before the experiment starts. The Prerun Script is useful for SPAs or other advanced flows where you need to bind listeners or evaluate custom logic before manually activating the experiment with `StatsigSidecar.activateExperiment("experiment_name")`. Go to [Advanced Configurations](https://docs.statsig.com/guides/sidecar-experiments/advanced-configurations-v3) for more detail on runtime settings, manual activation, and prerun scripts. ## Making your edits Click **Element selector** or press command + E to enable the element editor. The editor provides a preset set of editable attributes depending on the selected element, for example: - _Text:_ Text, Font attributes - _Button:_ Text, target link - _Image:_ Image source All elements also support rearranging or hiding attributes. ![Visual Editor Editor](https://docs.statsig.com/images/sidecarv3editor.png) ## Starting your experiment Click **Save** in the bottom-right of the visual editor to save changes to the console. Return to the console page and refresh to see your changes listed. Preview the experiment by clicking the three dots in the variant table. When ready, launch the experiment by clicking **Start** in the top-right corner. After starting, the experiment appears for end users and Statsig collects metrics. ### Advanced script setup Add these query string parameters to the Sidecar script URL for additional controls over Sidecar client behavior. - `&reduceflicker=0` disables the brief hiding of the `<body>` tag while the client initializes. ## Advanced configurations For more advanced Sidecar controls after the basic setup is working: - Go to [Advanced Configurations](https://docs.statsig.com/guides/sidecar-experiments/advanced-configurations-v3) for runtime settings, manual activation, prerun scripts, script URL tuning, consent, and identity configuration. - Go to [Measuring Experiments](https://docs.statsig.com/guides/sidecar-experiments/measuring-experiments#per-assignment-callback-for-outbound-integrations) for outbound analytics callbacks and other measurement patterns. ================================================================================ # Measuring Experiments URL: https://docs.statsig.com/guides/sidecar-experiments/measuring-experiments ================================================================================ # Measuring Experiments ## Using Autocapture Sidecar automatically tracks various web activities, letting you create simple and complex metrics in the Statsig console without writing code. Create a new metric in the Metrics tab on the Statsig console to get started. For a full list of automatically logged metrics, refer to [Autocapture on the Web](https://docs.statsig.com/webanalytics/autocapture). ## Using the tracking API You can track events manually for actions Autocapture doesn't capture. To track events to Statsig, call `StatsigSidecar.logEvent`, which accepts the same arguments as the Statsig JS SDK, as [Logging an event](https://docs.statsig.com/client/javascript-sdk#logging-an-event) documents. You can call this method before the init routine completes. ```js // example order event StatsigSidecar.logEvent('Order', null, { total: 54.66, units: 3, unitAvgCost: 18.22 }); ``` ## Per-assignment callback for outbound integrations You can bind a callback that Sidecar invokes each time it activates an experiment assignment, including experiments that prerun scripts activate later. Define this method before the Sidecar client script. ```js window.statsigSidecarConfig = { onExperimentEvaluation: function (event) { /** * add your own callback routine here * ie; annotating 3rd party analytics tools with assignment info */ window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: "statsig_experiment_evaluation", experiment_name: event.experimentName, experiment_group_name: event.groupName, }); } } ``` The callback payload includes the following fields: | Field | Description | | --- | --- | | `event.name` | Always `"experiment_evaluation"`. | | `event.experiment` | The full Statsig experiment object. | | `event.experimentName` | The Sidecar experiment name, or the Statsig experiment name as a fallback. | | `event.groupName` | The assigned group or variant, or `null` if unavailable. | ## Post-experiment callback for one-time readiness hooks You can bind `window.postExperimentCallback` to receive a callback after Sidecar finishes its initial run. This callback fires even when there are no experiments, but doesn't cover experiments that prerun scripts activate later. ```js window.postExperimentCallback = function(statsigClient, experimentIds) { // One-time initialization hook after Sidecar finishes the initial run } ``` ### Disabling all logging To disable all logging to Statsig (both autocapture events and experiment exposure logging), append the following query string parameter to the Sidecar script URL: `&autostart=0`. Disabling logging is useful for GDPR compliance. You can re-enable events later with `client.updateRuntimeOptions({disableLogging: false})`. ================================================================================ # Advanced Configurations URL: https://docs.statsig.com/guides/sidecar-experiments/advanced-configurations-v3 Updated: 2026-04-01 ================================================================================ # Advanced Configurations ## Runtime settings for SPAs and manual activation Visual Editor v3 includes runtime settings that let you control when an experiment starts running on the page. Configure these settings on the experiment setup page in the Statsig Console. - **Disable Auto Run** prevents Sidecar from automatically attempting to run the experiment on page load. - **Custom activation** lets you start the experiment manually with `StatsigSidecar.activateExperiment("experiment_name")`. - **Prerun Script** lets you define a custom script that runs once before the experiment starts when the targeting rules pass. Use the Prerun Script to bind listeners or evaluate custom logic before manually activating the experiment. ## Advanced targeting and segmentation This section describes how to set user identity and attributes for Sidecar to enable more advanced targeting and results segmentation. By default, Sidecar and Autocapture use `stableID` (an auto-generated device-level GUID stored in the user's localStorage) for tracking. To enrich autocapture events with known user identities and attributes, define the following object before autocapture or Sidecar loads. Watch this [video tutorial](https://tinyurl.com/sidecar-targeting) on how to configure more advanced targeting for your Sidecar experiments. ```js window.statsigUser = { userID: "<USER ID>", custom: { // optional attributes object isLoggedIn: false } } ``` ## Accessing the Statsig JS client To access the underlying Statsig js client instance, call `StatsigSidecar.getStatsigInstance()`. ## Configuring runtime options Use runtime options to handle consent management, GDPR compliance, and more. Sidecar fully supports all [StatsigOptions](https://docs.statsig.com/client/javascript-sdk/#statsig-options) that the JavaScript SDK provides. Pass them to Sidecar using: ```js window.statsigOptions = { // example of disabling logging for loggingEnabled: 'disabled' } ``` ## Managing consent Before the Sidecar script tag, configure these runtime options to disable browser storage and tracking: ```js window.statsigOptions = { loggingEnabled: "disabled", disableStorage: true } ``` After the user gives consent, re-enable storage and tracking: ```js __STATSIG__.instance().updateRuntimeOptions({loggingEnabled: "browser-only", disableStorage: false}); ``` ## Persisting stableID across subdomains Statsig uses `localStorage` as the preferred mechanism for storing the user's stableID. localStorage keys don't persist across origin boundaries, including subdomains. For example, a user visiting `https://example.com`, `https://show.example.com`, and `https://account.example.com` receives three distinct stableIDs. If you assign a user to a test on one subdomain and track behavior for metrics on a different subdomain, add the following solution. The solution ensures Statsig correctly attributes cross-origin behavior to the Test Group assignment from the initial experiment domain. Paste the following in your HEAD section. ```html <!-- cross domain id script --> <script>!function(){let t="STATSIG_LOCAL_STORAGE_STABLE_ID";function e(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();let t=()=>Math.floor(65536*Math.random()).toString(16).padStart(4,"0");return`$\{t()\}${t()}-$\{t()\}-4${t().substring(1)}-$\{t()\}-${t()}$\{t()\}${t()}`}let i=null,n=localStorage.getItem(t)||null;if(document.cookie.match(/statsiguuid=([\w-]+);?/)&&([,i]=document.cookie.match(/statsiguuid=([\w-]+);?/)),i&&n&&i===n);else if(i&&n&&i!==n)localStorage.setItem(t,i);else if(i&&!n)localStorage.setItem(t,i);else{let o=e();localStorage.setItem(t,o),function t(i){let n=new Date;n.setMonth(n.getMonth()+12);let o=window.location.host.split(".");o.length>2&&o.shift();let s=`.$\{o.join(".")\}`;document.cookie=`statsiguuid=${i||e()};Expires=$\{n\};Domain=${s};Path=/`}(o)}}();</script> <!-- Manually attach stableID from local storage --> <script> if(localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')) { window.statsigUser = { customIDs: {stableID: localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')} } } </script> <!-- sidecar script below --> <script src="https://cdn.jsdelivr.net/npm/statsig-sidecar/dist/index.min.js?apikey=[client-YOUR-STATSIG-CLIENT-KEY]"></script> ``` ================================================================================ # Setting up Sidecar URL: https://docs.statsig.com/guides/sidecar-experiments/setup ================================================================================ # Setting up Sidecar > **Info:** > > - This guide assumes you have an existing Statsig account. Go here to create a new free account if you don't already have one: https://statsig.com/signup > - You need to use the Google Chrome web browser for this exercise. ## Set up Sidecar Chrome extension ### Step 1: Install Chrome extension If you don't already have the Sidecar extension, visit the [Chrome Web Store](https://chromewebstore.google.com/detail/statsig-sidecar/blkgemeefnlkmicphlkodgdkhceibgcb) and select "Add to Chrome". ![Statsig Sidecar Extension in the Chrome Web Store](https://docs.statsig.com/images/guides/sidecar-experiments/setup/0fc7cf69-3668-4f1b-bdaf-c75a25ca96af.png) ### Step 2: Activate the extension Select the Extensions toolbar button and choose "Statsig Sidecar" to activate the Sidecar extension. ![Chrome extensions menu with Statsig Sidecar option](https://docs.statsig.com/images/guides/sidecar-experiments/setup/e069d1f2-c437-4398-a381-681b76663178.png) You now see an Experiment Config UI like this: ![Sidecar Empty Interface](https://docs.statsig.com/images/sidecarempty.png) ### Step 3: Update settings Update the API keys in the Settings dialog for the extension to work. Open the Settings dialog from the "Settings" link in the top header. ![Sidecar Settings Dialog](https://docs.statsig.com/images/sidecarsettings.png) Retrieve these keys from your Statsig project. Log in to the Statsig Console at https://console.statsig.com and navigate to Settings (https://console.statsig.com/settings). Select the "Keys & Environments" panel, then copy both the Console API Key and Client API Key and paste them into the Settings dialog. ![Statsig console Keys & Environments panel showing API keys](https://docs.statsig.com/images/guides/sidecar-experiments/setup/754cc245-1821-4f75-a87d-08b536422587.png) Select "OK" to save the API Keys. ## Install Sidecar on your website Add a single script tag within the `<head>` portion of your website, replacing with your own [Client SDK Key](https://docs.statsig.com/access-management/api-keys) as shown below. ```plaintext <script src="https://cdn.jsdelivr.net/npm/statsig-sidecar/dist/index.min.js?apikey=REPLACE_WITH_YOUR_CLIENT_SDK_KEY"></script> ``` > **Info:** > > Installing Sidecar JS through a Tag Manager can lead to flickering and other unpredictable behavior. Install Sidecar as a synchronous script tag instead. ### Additional options Add these query string parameters to the Sidecar script URL for additional controls over Sidecar client behavior - `&reduceflicker=0` disables the brief hiding of the `<body>` tag while the client initializes - `&autocapture=0` disables event autocapture Most website builders support adding script tags. Here are some common examples: [Webflow](https://university.webflow.com/lesson/custom-code-in-the-head-and-body-tags?topics=site-settings), [Wordpress](https://wordpress.com/go/website-building/how-to-properly-add-javascript-to-wordpress-3-top-methods/), [Wix](https://support.wix.com/en/article/embedding-custom-code-on-your-site), [Squarespace](https://support.squarespace.com/hc/en-us/articles/205815928-Adding-custom-code-to-your-site). You can copy the script code from within the Sidecar Chrome extension. ![Sidecar Script Code](https://docs.statsig.com/images/sidecargetscript.png) You're now ready to create your first experiment. ## Next up: [Creating Experiments](https://docs.statsig.com/guides/sidecar-experiments/creating-experiments) ================================================================================ # Creating Your First Experiment URL: https://docs.statsig.com/guides/sidecar-experiments/creating-experiments ================================================================================ # Creating Your First Experiment Sidecar lets you create and run A/B experiments without writing code or pushing code to production. This guide shows how to create an experiment and review results. > **Info:** > > This guide assumes you've followed the previous steps of installing Sidecar, creating a Statsig account, and setting up the API Keys correctly. Refer to [Setup](https://docs.statsig.com/guides/sidecar-experiments/setup) for those instructions. ## Step 1: Navigate to the web page Navigate to the web page you want to experiment on. ![Sidecar experiment interface showing the main dashboard](https://docs.statsig.com/images/sidecarfull.png) ## Step 2: New experiment Select the **New Experiment** button and fill out the details. Selecting **New Experiment** creates a local, unpublished experiment, so you can configure all the details and verify that everything works before publishing. ![New experiment creation form](https://docs.statsig.com/images/guides/sidecar-experiments/creating-experiments/d8cfc8bb-43e9-4a64-8ca8-002c579e7fff.png) ## Step 3 (Optional): Add URL filter You can select which pages the experiment runs on. Sidecar evaluates URL filters before any targeting rules configured on the experiment in the Statsig console. You can configure URL targeting using the following methods: - All Pages - anywhere you install the Sidecar client. - Contains - The page URL must contain the value as a substring. - Exact Match - The page URL must match the exact value you specify here. - Regex - Regular expressions, for example `(http|https):\/\/www.statsig.com\/pricing` matches pages `http://www.statsig.com/pricing` or `https://www.statsig.com/pricing`, and activates this experiment on those pages. ![URL targeting configuration interface with filter options](https://docs.statsig.com/images/sidecarurls.png) ## Step 4: Add actions Select the **Add Action** button to see a list of actions available for this experiment. Choose **Change content of an element** to run an A/B test that changes the content of an HTML element, such as headlines, descriptions, or CTAs. ![Add action selection menu with available experiment actions](https://docs.statsig.com/images/sidecaraddaction.png) ### Use the Redirect action for landing page and split URL experiments For Landing Page and Split URL experiments, add the "Redirect to another page" action for any test group and specify the destination URL. Sidecar preserves query string parameters and passes them to the destination URL. ![Redirect action configuration for landing page experiments](https://docs.statsig.com/images/sidecarredirect.png) ## Step 5: Select an element To run a content change experiment, you need two things: the element to test, and the content to change. Select the yellow **Target element path** text box to activate element selector mode. Move your mouse over the web page to see a red selection rectangle. Select the element you want. This example selects the main Headline. ![Element selection with red highlight showing target element](https://docs.statsig.com/images/sidecarselect.png) Sidecar now reflects the path of the selected element. ![Selected element path display in the configuration panel](https://docs.statsig.com/images/sidecarpath.png) ## Step 6: Update content Choose the two text values to A/B test. In the **Control content** text box, add your control text (for example, "Build Better Products"). In the **Test content** text box, add your test variant (for example, "Experiment Like a Pro"). You can validate these changes in real time by selecting the ▶ button above the text box for each variant. Selecting the button immediately changes the element's content so you can visually inspect the result before publishing. ![Content update interface with preview functionality](https://docs.statsig.com/images/sidecarupdatelt.png) ## Step 7: Add more actions You can add more actions within the same experiment to explore additional capabilities. ![Adding additional experiment actions to the same test](https://docs.statsig.com/images/sidecar2ndaction.png) You've created your first no-code experiment. ## Next up: [Measuring Experiments](https://docs.statsig.com/guides/sidecar-experiments/measuring-experiments) ================================================================================ # Advanced Configurations URL: https://docs.statsig.com/guides/sidecar-experiments/advanced-configurations ================================================================================ # Advanced Configurations ## Single Page App support Sidecar supports integration within Single Page Apps. Sidecar provides configuration tools and SDK methods for defining custom trigger points, giving you full flexibility to control when an experiment runs. - **Disable Auto Run**: When you select it, Sidecar doesn't automatically attempt to run the test on page load. - **Custom activation**: Use `StatsigSidecar.activateExperiment("<experiment_id>")` to activate an experiment manually. - **Prerun Script**: Define a custom script that runs only once per experiment if the URL filter passes. Use the Prerun Script to bind listeners or evaluate custom logic to control when to trigger the experiment using `activateExperiment`. ![Single Page App configuration settings in Sidecar](https://docs.statsig.com/images/sidecar-spa.png) ## Advanced targeting and segmentation This section describes how to set user identity and attributes for Sidecar to enable more advanced targeting and results segmentation. By default, Sidecar and Autocapture use `stableID` (an auto-generated device-level GUID stored in the user's localStorage) for tracking. To enrich autocapture events with known user identities and attributes, define the following object before autocapture or Sidecar loads. Watch this [video tutorial](https://tinyurl.com/sidecar-targeting) on how to configure more advanced targeting for your Sidecar experiments. ```js window.statsigUser = { userID: "<USER ID>", custom: { // optional attributes object isLoggedIn: false } } ``` ## Accessing the Statsig JS client To access the underlying Statsig js client instance, call `StatsigSidecar.getStatsigInstance()`. ## Configuring runtime options Use runtime options to handle consent management, GDPR compliance, and more. Sidecar fully supports all [StatsigOptions](https://docs.statsig.com/client/javascript-sdk/#statsig-options) that the JavaScript SDK provides. Pass them to Sidecar using: ```js window.statsigOptions = { // example of disabling logging for loggingEnabled: 'disabled' } ``` ## Managing consent Before the Sidecar script tag, configure these runtime options to disable browser storage and tracking: ```js window.statsigOptions = { loggingEnabled: "disabled", disableStorage: true } ``` After the user gives consent, re-enable storage and tracking: ```js __STATSIG__.instance().updateRuntimeOptions({loggingEnabled: "browser-only", disableStorage: false}); ``` ## Persisting stableID across subdomains Statsig uses `localStorage` as the preferred mechanism for storing the user's stableID. localStorage keys don't persist across origin boundaries, including subdomains. For example, a user visiting `https://example.com`, `https://show.example.com`, and `https://account.example.com` receives three distinct stableIDs. If you assign a user to a test on one subdomain and track behavior for metrics on a different subdomain, add the following solution. The solution ensures Statsig correctly attributes cross-origin behavior to the Test Group assignment from the initial experiment domain. Paste the following in your HEAD section. ```html <!-- cross domain id script --> <script>!function(){let t="STATSIG_LOCAL_STORAGE_STABLE_ID";function e(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();let t=()=>Math.floor(65536*Math.random()).toString(16).padStart(4,"0");return`$\{t()\}${t()}-$\{t()\}-4${t().substring(1)}-$\{t()\}-${t()}$\{t()\}${t()}`}let i=null,n=localStorage.getItem(t)||null;if(document.cookie.match(/statsiguuid=([\w-]+);?/)&&([,i]=document.cookie.match(/statsiguuid=([\w-]+);?/)),i&&n&&i===n);else if(i&&n&&i!==n)localStorage.setItem(t,i);else if(i&&!n)localStorage.setItem(t,i);else{let o=e();localStorage.setItem(t,o),function t(i){let n=new Date;n.setMonth(n.getMonth()+12);let o=window.location.host.split(".");o.length>2&&o.shift();let s=`.$\{o.join(".")\}`;document.cookie=`statsiguuid=${i||e()};Expires=$\{n\};Domain=${s};Path=/`}(o)}}();</script> <!-- Manually attach stableID from local storage --> <script> if(localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')) { window.statsigUser = { customIDs: {stableID: localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')} } } </script> <!-- sidecar script below --> <script src="https://cdn.jsdelivr.net/npm/statsig-sidecar/dist/index.min.js?apikey=[client-YOUR-STATSIG-CLIENT-KEY]"></script> ``` ================================================================================ # Taking your experiments to production URL: https://docs.statsig.com/guides/sidecar-experiments/publishing-experiments ================================================================================ # Taking your experiments to production Publish your Sidecar experiment to save its configuration to Statsig, QA it with a preview URL, then start it to serve variants to visitors. Publishing syncs your changes to the experiment console without starting the experiment, so you can set up metrics and targeting and test on your site first. > **Info:** > > This guide assumes you've followed the previous steps of creating an experiment in Sidecar. Refer to [Creating Experiments](https://docs.statsig.com/guides/sidecar-experiments/creating-experiments) for those instructions. ## Step 1: Publish the experiments When you're satisfied with the experiment configuration, select the blue **Publish** button. Selecting **Publish** saves all configurations to Statsig. To verify Statsig stored the changes successfully, select the `...` menu and choose **Go to Experiment Console**. Publishing changes doesn't start any experiments; it does the following: - Sync any unsaved changes to Statsig (making them accessible in _Console_ where you can configure metrics and other targeting conditions if applicable). - Include any configured tests in the Sidecar script installed on your website. - Allow you to QA experiments on your site while they're in an unstarted state. ![Statsig experiment console interface](https://docs.statsig.com/images/sidecarconsole.png) The experiment console lets you configure targeting, metrics, and advanced statistical settings. ![Statsig experiment setup tab with checklist and scorecard fields](https://docs.statsig.com/images/guides/sidecar-experiments/publishing-experiments/22f57816-6fdd-422c-87a9-90a5c08f36a5.png) ## Step 2: Preview and QA the experiment At this point, your experiment is in a pre-started state, meaning it isn't yet active to site visitors. To preview a specific variant, pass a query string to your test page URL using the `overrideuser` parameter. The override method uses the following convention to force a test and test group: `https://www.DOMAIN.com/?overrideuser=<EXPERIMENT_ID>_<TEST_GROUP_ID>` The image below shows where to find the experiment ID and each variation ID. Based on this example, force a preview of the Test Group by visiting: `https://www.DOMAIN.com/?overrideuser=name_color_test_1` ![Sidecar experiment QA and preview interface](https://docs.statsig.com/images/sidecarqa.png) > **Note:** > > The override method works best with the default test and control group names. If you change a group name, you must also update it in the Statsig Console by selecting "Manage Overrides". ## Step 3: Start the experiment Refresh the page in your browser with the script embedded. Sidecar automatically detects the published experiment and displays all experiment properties. Start the experiment by selecting the `...` menu and choosing **Start Experiment**. Sidecar then starts the experiment, serves the correct variants for control and test groups, and begins collecting metrics. ![Sidecar experiment start interface](https://docs.statsig.com/images/sidecarstartexp.png) You've successfully built and shipped an experiment. ================================================================================ # Integrating Sidecar with GTM for tracking URL: https://docs.statsig.com/guides/sidecar-experiments/integrating-gtm ================================================================================ # Integrating Sidecar with GTM for tracking > **Info:** > > This integration is for tracking purposes only. Avoid loading Sidecar itself through GTM, because doing so delays applying the changes and results in "flickering". ## How GTM integration works This integration automatically sends GTM-tagged events to Statsig. You don't need any additional coding or tagging after completing these steps. ![Statsig logstream showing GTM events flowing in](https://docs.statsig.com/images/gtm-logstream.png) _(statsig logstream showing gtm events flowing in)_ ## Step 1: Create new tag ![GTM create new tag interface for Statsig integration](https://docs.statsig.com/images/gtm-create-tag.png) ## Step 2: Choose tag type Choose "Custom HTML" for tag type, and paste [this GTM code](#gtm-code) (including script tag) ![GTM tag configuration screen with custom HTML setup](https://docs.statsig.com/images/gtm-tag-configuration.png) ## Step 3: Adjust fire options Under Advanced Settings under "Tag Firing options", select "Once per page" ![GTM tag firing options settings for once per page](https://docs.statsig.com/images/gtm-create-tag-options.png) ## Step 4: Set tag trigger Below the "Tag Configuration" section, set the Trigger to "Initialization - All Pages" Option. ![GTM tag trigger configuration for all pages initialization](https://docs.statsig.com/images/gtm-tag-trigger.png) ## Step 5: Save tag and test After saving and publishing your updated GTM tag, tracking runs automatically without any additional configuration. To debug the integration, set a local storage entry `debug_ss_gtm` with any value on your webpage. The `debug_ss_gtm` entry produces console log statements for each tracking call dispatched to Statsig. You can also inspect your browser's network traffic to see the events Statsig tracks. ## GTM code ```html <script type="text/javascript"> /* dataLayer helper */ (function(){ var f=/\[object (Boolean|Number|String|Function|Array|Date|RegExp|Arguments)\]/;function g(a){return null==a?String(a):(a=f.exec(Object.prototype.toString.call(Object(a))))?a[1].toLowerCase():"object"}function m(a,b){return Object.prototype.hasOwnProperty.call(Object(a),b)}function n(a){if(!a||"object"!=g(a)||a.nodeType||a==a.window)return!1;try{if(a.constructor&&!m(a,"constructor")&&!m(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}for(var b in a);return void 0===b||m(a,b)};function p(a,b){var c={},d=c;a=a.split(".");for(var e=0;e<a.length-1;e++)d=d[a[e]]={};d[a[a.length-1]]=b;return c}function q(a,b){var c=!a._clear,d;for(d in a)if(m(a,d)){var e=a[d];"array"===g(e)&&c?("array"===g(b[d])||(b[d]=[]),q(e,b[d])):n(e)&&c?(n(b[d])||(b[d]={}),q(e,b[d])):b[d]=e}delete b._clear}; function r(a,b,c){b=void 0===b?{}:b;"function"===typeof b?b={listener:b,listenToPast:void 0===c?!1:c,processNow:!0,commandProcessors:{}}:b={listener:b.listener||function(){},listenToPast:b.listenToPast||!1,processNow:void 0===b.processNow?!0:b.processNow,commandProcessors:b.commandProcessors||{}};this.a=a;this.l=b.listener;this.j=b.listenToPast;this.g=this.i=!1;this.c={};this.f=[];this.b=b.commandProcessors;this.h=u(this);var d=this.a.push,e=this;this.a.push=function(){var k=[].slice.call(arguments, 0),l=d.apply(e.a,k);v(e,k);return l};b.processNow&&this.process()}r.prototype.process=function(){this.registerProcessor("set",function(){var c={};1===arguments.length&&"object"===g(arguments[0])?c=arguments[0]:2===arguments.length&&"string"===g(arguments[0])&&(c=p(arguments[0],arguments[1]));return c});this.i=!0;for(var a=this.a.length,b=0;b<a;b++)v(this,[this.a[b]],!this.j)};r.prototype.get=function(a){var b=this.c;a=a.split(".");for(var c=0;c<a.length;c++){if(void 0===b[a[c]])return;b=b[a[c]]}return b}; r.prototype.flatten=function(){this.a.splice(0,this.a.length);this.a[0]={};q(this.c,this.a[0])};r.prototype.registerProcessor=function(a,b){a in this.b||(this.b[a]=[]);this.b[a].push(b)}; function v(a,b,c){c=void 0===c?!1:c;if(a.i&&(a.f.push.apply(a.f,b),!a.g))for(;0<a.f.length;){b=a.f.shift();if("array"===g(b))a:{var d=a.c;g(b[0]);for(var e=b[0].split("."),k=e.pop(),l=b.slice(1),h=0;h<e.length;h++){if(void 0===d[e[h]])break a;d=d[e[h]]}try{d[k].apply(d,l)}catch(w){}}else if("arguments"===g(b)){e=a;k=[];l=b[0];if(e.b[l])for(d=e.b[l].length,h=0;h<d;h++)k.push(e.b[l][h].apply(e.h,[].slice.call(b,1)));a.f.push.apply(a.f,k)}else if("function"==typeof b)try{b.call(a.h)}catch(w){}else if(n(b))for(var t in b)q(p(t, b[t]),a.c);else continue;c||(a.g=!0,a.l(a.c,b),a.g=!1)}}r.prototype.registerProcessor=r.prototype.registerProcessor;r.prototype.flatten=r.prototype.flatten;r.prototype.get=r.prototype.get;r.prototype.process=r.prototype.process;window.DataLayerHelper=r;function u(a){return{set:function(b,c){q(p(b,c),a.c)},get:function(b){return a.get(b)}}};})(); window.StatsigLogger = (function () { var statsigInstance, log = function () { if (typeof localStorage !== 'undefined' && typeof console !== 'undefined' && localStorage.getItem('debug_ss_gtm')) { console.log.apply(console, arguments); } }; var checkStatsigReady = function (callback) { // statsig has already loaded if(typeof StatsigSidecar !== 'undefined' && StatsigSidecar.getStatsigInstance()) { log('+++ Statsig:ready Already loaded'); callback(StatsigSidecar.getStatsigInstance()); } else { log('+++ Statsig:ready callback'); window.postExperimentCallback = function(statsigClient, expIds) { callback(statsigClient); } } }; var handleGTMMessage = function (model, message) { if (typeof message === 'object' && typeof message.event === 'string') { var metadata = {}; for (var prop in message) { if(!(message[prop] instanceof HTMLElement) && typeof(message[prop]) !== 'object') { metadata[prop] = message[prop]; } } log('++ handleGTMMessage', message.event, message.conversionValue || null, metadata); statsigInstance.logEvent(message.event, message.conversionValue || null, metadata); } else { log('++ handleGTMMessage / skip'); } } checkStatsigReady(function (statsigInstanceReady) { statsigInstance = statsigInstanceReady; // dataLayer will contain gtm events (~messages) that were fired pre statsig readiness new DataLayerHelper(dataLayer, { listener: handleGTMMessage, listenToPast: true, }); }); return { track: function() { try { statsigInstance.logEvent.apply(statsigInstance, arguments); } catch(err) { } } } })(); </script> ``` ================================================================================ # Running an A/A Test using Sidecar URL: https://docs.statsig.com/guides/aa-sidecar ================================================================================ # Running an A/A Test using Sidecar Statsig Sidecar runs an A/A test directly on your website: both variants apply the same change, so any difference in results points to a setup problem rather than a real effect. Run an A/A test to validate a new experimentation engine and confirm your metrics and exposures are configured correctly before your first real A/B test. This guide assumes you have successfully set up and configured Statsig Sidecar. For a step-by-step guide, go to [“Setting up Sidecar”](https://docs.statsig.com/guides/sidecar-experiments/setup). > **Note:** > > ## Why run an A/A test The most common reason to run an A/A test is to validate a new experimentation engine you're integrating with, such as Statsig. For new users, running an A/A test first provides a low-stakes environment. You can confirm that you set up your metrics correctly and that exposures are recorded as expected before you start your first real A/B test. ## How to run an A/A test ### Step 1: Create a new Experiment in Sidecar Navigate to the page on your website where you want to run an A/A Test. Open the Statsig Sidecar extension and select **New Experiment**. Fill in the title of your A/A test. ![Sidecar A/A test experiment setup interface](https://docs.statsig.com/images/sidecar_aa_setup.png) Then, determine the URI filter (for example, All Pages, contains). After you configure the URI, set up the variants. For the variant 'Control', choose an action. In this example, the action changes the content of an element: specifically the title 'Getting Started is Simple'. ![Sidecar A/A test variant configuration screen](https://docs.statsig.com/images/sidecar_aa_select.png) Repeat the Control configuration for the variant 'Test', using the exact same action. Your setup should match the following. ![Sidecar A/A test final configuration showing identical variants](https://docs.statsig.com/images/sidecar_aa_final.png) Select **Publish** to push the experiment to Statsig as a draft. ### Step 2: Configure experiment scorecard in Statsig console After Sidecar pushes the experiment to end users, edit the scorecard for your experiment in the console. Navigate to the console, select the **Experiments** tab, and open the experiment you just created. In the **Setup** tab, fill out the scorecard with the experiment hypothesis and any primary metrics you want to monitor. Statsig shows results for all your metrics, but these key metrics represent your hypothesis. When you establish a hypothesis upfront, the experiment improves your understanding of users rather than providing data points to support a predetermined decision. In the Allocation and Targeting section, for an A/A test, allocate 100% of users to the experiment while targeting everyone. Save and push your experiment. Your test is now ready to start measuring metrics associated with the A/A test. ### Step 3: Review A/A test results Within 24 hours of starting your experiment, cumulative exposures appear in the **Pulse Results** tab of your experiment. The Pulse Results tab shows a breakdown of your logged exposures and their distribution. If the distribution looks incorrect, check the **Diagnostics** tab for more granular, day-by-day exposure breakdowns at both the Checks and User level. In the **Scorecard** panel, you can see the full picture of how all your tagged metrics perform. ![pulse_results_empty](https://docs.statsig.com/images/experiments/types/aa-test/163248267-7bd7419a-59e0-4d58-b8e5-8ace95ed74d9.png) What to expect: - **Exposures**: Confirm that exposures are flowing through as expected from your product. If exposures are missing, use the **Diagnostics** tab and the **Exposure Stream** to debug. - **Pulse results**: About 5% of your metrics in Pulse should show a statistically significant change, because Statsig’s stats engine uses a 95% confidence interval. Run your A/A test long enough to reach most of your weekly active users, or at least one week. ================================================================================ # Session Replay Overview URL: https://docs.statsig.com/session-replay/overview ================================================================================ # Session Replay Overview Session Replay records users interacting with your website or product and lets you play back those sessions. Use it to understand how users navigate your service, diagnose problems, and uncover insights that improve conversion and the overall user experience. A session recording plays back like a video in the Statsig Console. It's a serialized representation of your website and all events and interactions that occurred during the session. Statsig captures recordings using the [rrweb open source recording library](https://github.com/rrweb-io/rrweb). This approach is performant and space-efficient, with options to apply privacy filters to on-screen content. ![Session replay interface in Statsig console](https://docs.statsig.com/images/session_replay/overall_ui.png) ================================================================================ # Install Statsig Session Replay URL: https://docs.statsig.com/session-replay/install ================================================================================ # Install Statsig Session Replay Statsig supports Session Replay on the Javascript and React SDKs for both desktop and mobile web users. Follow the instructions below to install the SDK and record user sessions. ## Option 1 - No code - Add Javascript snippet to your website ```html <script src="https://cdn.jsdelivr.net/npm/@statsig/js-client@3/build/statsig-js-client+session-replay+web-analytics.min.js?apikey=[YOUR_CLIENT_KEY]"></script> ``` Get YOUR\_CLIENT\_KEY from _Project Settings > Keys & Environments_. Reveal the Client API Key, copy, and paste it over the \[YOUR-API-KEY\] in the snippet above. This auto-initializes the SDK and starts recording sessions, no code required. > **Info:** > > To use your existing Statsig integration or customize further, refer to option 2 below. To use the script tag with customization, remove your key from the script URL and initialize using the JavaScript code below. ## Option 2 - Custom code - Install using a package manager #### Javascript #### npm ```bash npm install @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` #### yarn ```bash yarn add @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` #### React #### npm ```bash npm install @statsig/session-replay @statsig/web-analytics @statsig/react-bindings ``` #### yarn ```bash yarn add @statsig/session-replay @statsig/web-analytics @statsig/react-bindings ``` Statsig recommends Autocapture for getting started quickly. To skip automatic event logging, remove the `runStatsigAutoCapture` option from the JavaScript snippet or skip the `@statsig/web-analytics` package installation. Next, following the [instructions for the Statsig Javascript SDK](https://docs.statsig.com/client/javascript-sdk), initialize Statsig with your SDK key, [user](https://docs.statsig.com/sdks/user) and options: #### Javascript ```jsx import { StatsigClient } from "@statsig/js-client"; import { runStatsigSessionReplay } from "@statsig/session-replay"; import { runStatsigAutoCapture } from "@statsig/web-analytics"; const client = new StatsigClient( sdkKey, { userID: "some_user_id" }, { environment: { tier: "production" } } // optional, pass options here if needed ); runStatsigSessionReplay(client); runStatsigAutoCapture(client); await client.initializeAsync(); ``` #### React ```jsx import { StatsigProvider, useClientAsyncInit } from "@statsig/react-bindings"; import { StatsigSessionReplayPlugin } from "@statsig/session-replay"; import { StatsigAutoCapturePlugin } from "@statsig/web-analytics"; function App() { return ( <StatsigProvider sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} loadingComponent={<div>Loading...</div>} options={{ plugins: [ new StatsigSessionReplayPlugin(), new StatsigAutoCapturePlugin(), ], }} > <Content /> </StatsigProvider> ); } ``` > **Info:** > > To use Conditional Triggers, you must use `StatsigTriggeredSessionReplay`. Refer to Configure (next page) for more information. Continue to Configure to learn more about controlling who, what, and when you record sessions. ================================================================================ # Configure Statsig Session Replay URL: https://docs.statsig.com/session-replay/configure ================================================================================ # Configure Statsig Session Replay ## Conditional recording In the Statsig Console, you can configure your Session Replay settings under _Project Settings > Analytics & Session Replay_. You must be a project admin to modify these settings. ### Global targeting gate The Global Targeting Gate controls who is eligible for session recording. If a user doesn't pass this gate, Statsig never records their sessions. By default, the gate is set to Everyone, meaning there are no restrictions and Statsig can record anyone. This gate defines the upper bound of session recording eligibility. ### Global sampling rate The Global Sampling Rate determines what percentage of eligible sessions Statsig records from the start. By default, the rate is 100%, meaning Statsig records all eligible sessions. You can lower this value to limit session recordings while still capturing a consistent percentage of sessions. This rate applies only to sessions that begin at session start and doesn't affect conditional triggers. ### Conditional triggers: events and exposures Conditional triggers can start a session recording mid-session, even if recording didn't begin at session start. These triggers respect the Global Targeting Gate but operate independently of the Global Sampling Rate. When a trigger fires, the recording includes the last 30 seconds leading up to the event, if you enable the rolling window. Types of conditional triggers: - **Individual Gate Exposures**: Trigger based on exposure to a specific gate, optionally filtered by group (for example, Pass/Fail). - **All Gate Exposures**: Trigger based on exposure to any gate, optionally filtered by group (for example, Pass/Fail). Individual Gate Exposure triggers override All Gate configuration. - **Individual Experiment Exposures**: Trigger based on exposure to a specific experiment, optionally filtered by group (for example, Test/Control). - **All Experiment Exposures**: Trigger based on exposure to any experiment, filtered by groups Test/Control. Statsig doesn't support other group names. If an experiment includes additional groups, configure individual triggers for each one. Individual Experiment Exposure triggers override All Experiment configuration. - **Events**: Trigger based on a specific logged event, optionally filtered by event values (for example, "purchase\_event" with value "book"). For each trigger, you can define an individual sampling rate. Statsig evaluates this rate based on `session_id`, so the result (pass or fail) remains consistent for the same session, even if the trigger occurs multiple times. **All Gates** and **All Experiments** conditional triggers require `3.30.1` or higher. If a conditional trigger occurs while a session recording is already in progress, the recording continues uninterrupted. ![Session replay settings panel with targeting and sampling controls](https://docs.statsig.com/images/session_replay/settings.png) ![At initialization, Statsig checks the user against the targeting gate. Users who fail the gate are never recorded. Users who pass are checked against the sampling rate: those who pass it are recorded from the start of the session, and those who fail it buffer the last 30 seconds instead. During the session, a triggered event or exposure turns that buffer into an active recording.](https://docs.statsig.com/images/diagrams/session-replay-conditional-recording.svg) ![At initialization, Statsig checks the user against the targeting gate. Users who fail the gate are never recorded. Users who pass are checked against the sampling rate: those who pass it are recorded from the start of the session, and those who fail it buffer the last 30 seconds instead. During the session, a triggered event or exposure turns that buffer into an active recording.](https://docs.statsig.com/images/diagrams/session-replay-conditional-recording.dark.svg) ### Example walkthrough Suppose you have the following setup (refer to the image above): - The Global Targeting Gate `session_replay_global_targeting_gate` allows all US users and excludes everyone else. - The Global Sampling Rate is 25%, so Statsig records only 25% of eligible US user sessions from the start. - For the remaining 75% of eligible users, session recording can still begin mid-session if a conditional trigger occurs. Example Scenario: 1. A US user starts a session. They don't pass the 25% Global Sampling Rate, so Statsig doesn't record their session from the beginning. 2. Later, a `purchase_event` occurs with value `book`. You've set up this event as a conditional trigger with a 50% sampling rate. If this session fails the sampling rate check, recording doesn't start. 3. A minute later, the user encounters the `cool_new_feature` gate, and the recording begins. > **Note:** > > A trigger's sampling rate is consistent for the entire session based on session\_id. So if `purchase_event` fails the sampling rate once, future occurrences of the same event in that session also fail. ### Initialization: StatsigTriggeredSessionReplay #### Javascript ```jsx import { StatsigClient } from "@statsig/js-client"; import { runStatsigTriggeredSessionReplay } from "@statsig/session-replay"; import { runStatsigAutoCapture } from "@statsig/web-analytics"; const client = new StatsigClient( sdkKey, { userID: "some_user_id" }, { environment: { tier: "production" } } // optional, pass options here if needed ); runStatsigTriggeredSessionReplay(client, { autoStartRecording: true, keepRollingWindow: true, }); runStatsigAutoCapture(client); await client.initializeAsync(); ``` #### React ```jsx import { StatsigProvider, useClientAsyncInit } from "@statsig/react-bindings"; import { StatsigTriggeredSessionReplayPlugin } from "@statsig/session-replay"; import { StatsigAutoCapturePlugin } from "@statsig/web-analytics"; function App() { return ( <StatsigProvider sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} loadingComponent={<div>Loading...</div>} options={{ plugins: [ new StatsigTriggeredSessionReplayPlugin({ autoStartRecording: true, keepRollingWindow: true, }), new StatsigAutoCapturePlugin(), ], }} > <Content /> </StatsigProvider> ); } ``` #### Initialization options - `autoStartRecording` - `true`: Recording can start automatically after initialization. Statsig respects the global targeting gate and sample rate. - `false`: You must manually start recording using startRecording(). This is helpful if you want to start the recording after a set point and block any auto-recording before then. - `keepRollingWindow` - `true`: Statsig maintains a local rolling window of the last 30 seconds of the session, allowing recordings to include context leading up to a trigger. - `false`: If a conditional trigger occurs, recording begins from that moment onward, with no historical context. > **Warning:** > > If you use bootstrapping, contact the Statsig team to confirm your server SDK supports conditional recording. ## Advanced: forcing a recording on demand To manually start a recording, use the `startRecording` API, which begins recording immediately when called. - `startRecording`: Respects both the Global Targeting Gate and Global Sampling Rate. Use this if you want to start recordings after a certain point (for example, after login) while still applying the Global Sampling Rate. - `forceStartRecording`: Respects the Global Targeting Gate but ignores the Global Sampling Rate. Useful for debugging or when you want to bypass the Global Sampling Rate. - `stopRecording`: Stops the current recording, if one is in progress. Calling this method when no recording is active has no adverse effects. After you call stopRecording, conditional recording triggers don't automatically restart the recording. Only an explicit call to `startRecording` or `forceStartRecording` resumes recording. If you have access to your Session Replay client, you can call these functions directly on the client instance. ```plaintext const sessionReplayClient = new SessionReplay(client); … if (someCondition) { sessionReplayClient.startRecording(); } ``` If you don't have access to the client instance, you can import the function from `@Statsig/session-replay` and call it using your SDK key. ```plaintext import { startRecording } from '@Statsig/session-replay'; … startRecording(CLIENT_SDK_KEY) ``` ## Additional options These options come from the rrweb recorder (the open source recording tool Statsig uses internally) | key | default | description | | --- | --- | --- | | blockClass | 'rr-block' | Use a string or RegExp to configure which elements should be blocked | | blockSelector | null | Use a string to configure which selector should be blocked | | ignoreClass | 'rr-ignore' | Use a string or RegExp to configure which elements should be ignored | | ignoreSelector | null | Use a string to configure which selector should be ignored | | ignoreCSSAttributes | null | array of CSS attributes that should be ignored | | maskTextClass | 'rr-mask' | Use a string or RegExp to configure which elements should be masked | | maskTextSelector | null | Use a string to configure which selector should be masked | | maskAllInputs | false | mask all input content as \* | | maskInputOptions | `{ password: true }` | mask some kinds of input \*. Refer to the [list](https://github.com/rrweb-io/rrweb/blob/588164aa12f1d94576f89ae0210b98f6e971c895/packages/rrweb-snapshot/src/types.ts#L77-L95) | | maskInputFn | - | customize mask input content recording logic | | maskTextFn | - | customize mask text content recording logic | | slimDOMOptions | `{}` | remove unnecessary parts of the DOM. Refer to the [list](https://github.com/rrweb-io/rrweb/blob/588164aa12f1d94576f89ae0210b98f6e971c895/packages/rrweb-snapshot/src/types.ts#L97-L108) | | dataURLOptions | `{}` | Canvas image format and quality ,This parameter will be passed to the OffscreenCanvas.convertToBlob(),Using this parameter effectively reduces the size of the recorded data | | inlineStylesheet | true | whether to inline the stylesheet in the events | | hooks | `{}` | hooks for events. Refer to the [list](https://github.com/rrweb-io/rrweb/blob/9488deb6d54a5f04350c063d942da5e96ab74075/src/types.ts#L207) | | packFn | - | refer to the [storage optimization recipe](https://github.com/rrweb-io/rrweb/blob/master/docs/recipes/optimize-storage.md) | | sampling | - | refer to the [storage optimization recipe](https://github.com/rrweb-io/rrweb/blob/master/docs/recipes/optimize-storage.md) | | recordCanvas | false | Whether to record the canvas element. Available options: `false`, `true` | | recordCrossOriginIframes | false | Whether to record cross origin iframes. rrweb has to be injected in each child iframe for this to work. Available options: `false`, `true` | | recordAfter | 'load' | If the document is not ready, then the recorder will start recording after the specified event is fired. Available options: `DOMContentLoaded`, `load` | | inlineImages | false | whether to record the image content | | collectFonts | false | whether to collect fonts in the website | | userTriggeredOnInput | false | whether to add `userTriggered` on input events that indicates if this event was triggered directly by the user or not. [What is `userTriggered`?](https://github.com/rrweb-io/rrweb/pull/495) | | plugins | \[\] | load plugins to provide extended record functions. [What is plugins?](https://github.com/rrweb-io/rrweb/blob/master/docs/recipes/plugin.md) | | errorHandler | - | A callback that is called if something inside of rrweb throws an error. The callback receives the error as argument. | ## Limits ### 4 hours per session or 30 min inactive time Sessions end after four hours total or if the user returns from inactive time greater than 30 minutes later. ### Recording limits | Tier | Monthly Limit | Daily Limit | Hourly Limit | | --- | --- | --- | --- | | Free | 50,000 | 3,500 | 3,500 | | Pro | 100,000 | 7,000 | 7,000 | | Enterprise | 100,000 | 7,000 | 7,000 | After you reach this limit, the SDK automatically prevents new recordings from starting. You can monitor your session replay usage in your project settings. [Contact Statsig](https://statsig.com/contact/demo) for custom contracts. ### Replay availability time Statsig takes about 1 hour to process a recorded session before it appears in your console. ### Default 30 day retention Sessions have a default retention period of 30 days and Statsig automatically deletes them after that time. You can configure a shorter retention period in settings if needed. Reducing your retention period doesn't affect your monthly session replay limit, and you typically do this for privacy and compliance purposes. ================================================================================ # Privacy Options for Session Replay URL: https://docs.statsig.com/session-replay/privacy ================================================================================ # Privacy Options for Session Replay Statsig Session Replay gives you several ways to control replay privacy and protect PII, so recordings match your app’s and organization’s policies: - **Baseline privacy options**: Select from three preset privacy configurations. Each option applies a different level of text masking, helping you protect PII and sensitive data according to your app’s and users’ needs. - **Fine-grained privacy controls**: After choosing a baseline configuration, use CSS selector rules to mask, reveal, or block specific elements. - **Global Targeting Gate**: Use a feature gate to define which users are eligible for replays, ensuring you limit recordings to specific users or cohorts. In the Statsig Console, you can configure your privacy settings under _Project Settings > Analytics & Session Replay_. You must be a project admin to modify these settings. ### Baseline privacy options - **Passwords (Default)**: Statsig replaces only password inputs with asterisks (\*). All other text and inputs appear as-is. - **Inputs**: Statsig replaces all text in inputs with asterisks (\*). All other text appears as-is. - **Maximum**: Statsig replaces all text and inputs with asterisks (\*). ### Selector rules Use CSS selectors to precisely control how Statsig handles individual elements during session replay: masked, unmasked, or blocked. - **Masking** and **unmasking** apply only to text content. Statsig replaces masked text with asterisks (\*). - **Blocking** removes the element entirely from the replay and replaces it with a black placeholder of the same size. - **You can't unmask password inputs**, regardless of selector rules. Selector rules override the baseline privacy settings. When multiple selector rules apply to the same element, Statsig enforces the following precedence: **Block → Mask → Unmask** The examples below show how Statsig enforces precedence. ```js // Everything within the blocked class will // appear as a single black placeholder <div class="blocked"> <div id="masked">I will be part of the black placeholder</div> <button id="unmasked">I will be part of the black placeholder</button> </div> ``` ```js // The closest rule will apply <div> <div id="masked">Masked Text</div> <div id="masked"> <button id="unmasked">Unmasked Text</button> </div> </div> ``` ```js // With conflicting rules applied at the same level, // the higher precedence will apply <div> <button id="unmasked" className="masked"> Masked Text </button> </div> ``` ```js // With baseline privacy setting set to Maximum, all text is masked // by default but this can be overwritten by unmasking <div> <div>Masked Text</div> <div> <button id="unmasked">Unmasked Text</button> </div> </div> ``` All selectors must be valid CSS selectors. For details on supported selector syntax, refer to MDN’s list of CSS selectors. > **Warning:** > > Using selector rules or baseline privacy settings besides Passwords overwrites the `maskTextFn`, `maskInputFn`, `maskTextSelector`, `maskAllInputs`, `maskInputOptions`, and `blockSelector` options you passed in during initialization. ### Global targeting gate The Global Targeting Gate controls who is eligible for session recording. If a user doesn't pass this gate, Statsig never records their sessions. By default, the gate is set to Everyone, meaning there are no restrictions and Statsig can record anyone. This gate defines the upper bound of session recording eligibility. > **Warning:** > > If you're using bootstrapping, contact the Statsig team to confirm Statsig supports your server SDK. ================================================================================ # Debug Statsig Session Replay URL: https://docs.statsig.com/session-replay/debug ================================================================================ # Debug Statsig Session Replay ## Large session recording warning In the Console, you may encounter the warning: > "This session recording is too large to load." This warning appears when a session exceeds 50 MB in size. After Statsig records a session at this size, the console can't display the session, and you can't fix it retroactively. If you consistently see this warning, you can take the following steps to reduce session sizes: 1. **Disable Inline Stylesheets** When initializing the `SessionReplayClient`, set `inlineStylesheet` to `false`. Statsig generally recommends keeping `inlineStylesheet` set to `true`, because it ensures recordings accurately reflect your original CSS even if you later update your styles. However, this setting often causes sessions to grow very large and is the most common source of bloat. #### Javascript ```jsx runStatsigSessionReplay(client, { inlineStylesheet: false, }); ``` #### React ```jsx ... options={{ plugins: [ new StatsigSessionReplayPlugin({ inlineStylesheet: false, }), ], }} ... ``` 2. **Exclude Large Static Elements** If certain elements on your page are large but static (for example, background images or videos), you can exclude them from session capture by adding the `rr-block` class to their `className`. This prevents Statsig from recording those elements and can significantly reduce session size. 3. **Reach Out for Assistance** If you continue to experience large sessions, contact the team in [Slack Community](https://statsig.com/slack). A Statsig team member can review your session and provide recommendations for your setup. ================================================================================ # Watch Session Replays URL: https://docs.statsig.com/session-replay/watch ================================================================================ # Watch Session Replays Statsig Session Replay captures user sessions for playback in the console. Watch any recorded session, step through event timelines, and filter replays by event, user, Feature Gate exposure, or Experiment exposure. To find your replays, go to the _Users_ group in the Statsig console navigation panel. ![Session replay navigation in Statsig console](https://docs.statsig.com/images/session-replay/watch/2f9ca1b1-f8e0-403f-9d3f-898434f06266.png) The main interface has three sections. The leftmost column lists available replays and filter controls. The middle playback surface lets you play, pause, and skip to events of interest. Select the next button to jump to the next event, or select an event in the rightmost events panel to skip to that point in the replay timeline. ![Session replay interface with playback controls and events panel](https://docs.statsig.com/images/session-replay/watch/f810ceb5-b6fc-4312-8e5d-9acfec0809bb.png) For a more immersive replay experience you can hide the events panel: ![Session replay interface with hidden events panel](https://docs.statsig.com/images/session-replay/watch/d63fdf9e-cfc4-45e5-9365-d478504574c3.png) You can also enter full screen mode. ## Find a replay ![Session replay selection interface with replay cards](https://docs.statsig.com/images/session-replay/watch/45ce3a59-6847-43d6-bfc8-6d3cd5d45917.png) Select a replay from the list on the left to watch it. The replay card shows details such as URL, browser, country, and more, which you can use to scan for or filter to replays of interest. To narrow the set of replays, add filters. Filters let you scope to replays that contain a specific event, user, Feature Gate exposure (pass or fail), or Experiment group exposure. Exposure filters match a replay to an exposure on a shared identifier (`stableID` or `userID`) within the session's time window: - **Client-side exposures**: Exposures logged in the same browser session through a client SDK always correlate reliably because they share the recording's `stableID` directly. - **Server-side exposures**: Exposures logged server-side may not match a recording when they don't share a common identifier. A server-side exposure keyed only on `userID` won't match a recording keyed only on `stableID`. To filter reliably on a server-side experiment, identify the browser session with the same `userID` the server uses, or log the exposure client-side. ## Playlists Playlists let you organize related session recordings into curated collections focused on specific user behaviors, issues, or research questions. ## Key features - **Organized Collections**: Create named playlists to group related session recordings. This makes it easier to focus on specific user journeys, bug reports, or research topics without searching through large numbers of individual sessions. - **Collaborative Analysis**: Share playlists with team members to collaborate on user experience analysis. Team members can view the same curated set of recordings to discuss findings and insights. - **Persistent Organization**: Unlike temporary filters, playlists preserve your organizational structure, making it easy to return to specific sets of recordings for ongoing analysis or follow-up research. - **Integration**: Playlists work within the existing session replay interface. When you open a playlist, you can view all recordings using the same replay player and analysis tools. ================================================================================ # CLI Session Replay URL: https://docs.statsig.com/session-replay/cli-session-replay ================================================================================ # CLI Session Replay CLI Session Replay allows you to record terminal sessions in your Node.js CLI applications and replay them in the Statsig Console. Use it to understand how users interact with your command-line tools, diagnose issues, and improve the user experience. The plugin records terminal output and resize events. Statsig plans to record user input in a future version. Because user input is likely to contain sensitive information, Statsig releases it after introducing methods to pause, filter, or redact recordings. ## Installation Install the CLI session replay package for Node.js: #### npm ```bash npm install @statsig/js-client @statsig/cli-session-replay-node ``` #### yarn ```bash yarn add @statsig/js-client @statsig/cli-session-replay-node ``` #### pnpm ```bash pnpm add @statsig/js-client @statsig/cli-session-replay-node ``` ## Basic usage ```javascript import { StatsigClient } from '@statsig/js-client'; import { StatsigCliSessionReplayPlugin } from '@statsig/cli-session-replay-node'; const client = new StatsigClient( 'your-client-key', { userID: 'user-123' }, { loggingEnabled: 'always', // Required for CLI environments plugins: [new StatsigCliSessionReplayPlugin()], } ); // Recording starts here console.log('Hello from CLI!'); await client.initializeAsync(); // Your CLI application logic here console.log('Continue'); ``` > **Note:** > > **CLI logging requirement**: CLI applications must set `loggingEnabled: 'always'` when initializing the StatsigClient. By default, Statsig enables logging only in browser environments. CLI session replay requires you to enable logging in all environments to capture and send session data. ## Configuration options The `StatsigCliSessionReplayPlugin` accepts optional configuration: ```javascript import { StatsigCliSessionReplayPlugin } from '@statsig/cli-session-replay-node'; const plugin = new StatsigCliSessionReplayPlugin({ // Override the start timestamp (in milliseconds) startTimestamp: Date.now(), // Custom Asciicast header properties asciicastHeader: { title: 'My CLI App Session', command: 'my-cli-tool --verbose', env: { TERM: 'xterm-256color', SHELL: '/bin/bash' }, } }); ``` ### Configuration properties - **`startTimestamp`** (optional): Override the recording start time in milliseconds. Defaults to `Date.now()`. - **`asciicastHeader`** (optional): Custom properties for the Asciicast header. For details, refer to the [Asciicast v2 File Format page](https://docs.asciinema.org/manual/asciicast/v2/#header). Common fields include: - `title`: Human-readable title for the recording - `command`: The command that ran - `env`: Environment variables relevant to the session - `theme`: Terminal color theme object ## Recording limits - **Duration**: Sessions automatically end after 4 hours. - **Size**: Recording stops if session data exceeds 1 MB. ## Viewing recordings CLI session recordings appear in the Statsig Console alongside web session replays. Each recording shows exactly what happened in the terminal, including: - All terminal output - Terminal resize events - Timing information for each interaction - Session metadata and environment details ## Manual recording control You can access the recording instance for manual control: ```javascript import { CliRecording } from '@statsig/cli-session-replay-node'; // Check if currently recording if (CliRecording.isRecording()) { console.log('Session is being recorded'); } // Get current recording instance const recording = CliRecording.currentRecording; // Manually finish recording CliRecording.finish(); ``` ## Platform support CLI Session Replay supports: - Node.js applications - Linux, macOS, and Windows terminals - Any terminal that supports standard input/output streams ================================================================================ # Overview URL: https://docs.statsig.com/integrations/mcp/overview ================================================================================ # Overview ## MCP configuration guides ### [Codex](https://docs.statsig.com/integrations/mcp/codex) Set up Statsig MCP using Codex Desktop App, CLI, or IDE extension. ### [ChatGPT Connector](https://docs.statsig.com/integrations/mcp/chatgpt-connector) Talk to your Statsig projects from within ChatGPT. ### [Cursor](https://docs.statsig.com/integrations/mcp/cursor) Configure Statsig MCP in Cursor IDE. ### [Claude Code](https://docs.statsig.com/integrations/mcp/claude-code) Set up Statsig MCP in Claude Code. ### [Manual setup](https://docs.statsig.com/integrations/mcp/manual-setup) Manual configuration for any MCP-compatible tool. ### [Enterprise-managed auth](https://docs.statsig.com/integrations/mcp/enterprise-managed-auth) Connect Claude through your identity provider. ## Enterprise-managed authorization Admins can configure Claude's connection to Statsig centrally instead of asking each member to authenticate. Claude acts as the person already signed in, and Statsig applies that person's project permissions and review requirements. Statsig supports two identity modes: Claude-issued identity, which works without Statsig SSO, and Okta OIDC Cross App Access, which reuses your existing Statsig SSO configuration. Both modes need the target project's Tenant ID. To set either one up, go to [Enterprise-managed authorization for Statsig MCP](https://docs.statsig.com/integrations/mcp/enterprise-managed-auth). ## Reference and automation ### [Tool reference](https://docs.statsig.com/integrations/mcp/tool-reference) Look up MCP tools, actions, and inputs. ### [Automation examples](https://docs.statsig.com/integrations/mcp/automation-examples) Call the V3 server from scheduled and CI jobs. ## Current MCP capabilities Statsig MCP exposes 18 default tools. Tool visibility depends on your permissions and the server configuration. | Tool group | What it does | | --- | --- | | Context and search | `get_context` returns your project, permissions, and review settings. `search` and `fetch` find and retrieve Statsig resources. | | Read tools | `gate_read`, `experiment_read`, `dynamic_config_read`, `metric_read`, and `log_read` list and inspect gates, experiments, dynamic configs, metrics, metric sources, audit logs, and Logs Explorer data. Each takes an `action`. | | Create tools | `gate_create`, `experiment_create`, and `dynamic_config_create` create new resources. These tools require write access. | | Update tools | `gate_update`, `experiment_update`, and `dynamic_config_update` replace an existing resource. These tools require write access and a `confirmation`. | | Discovery tools | `discover_tools` finds other operations, including layers, segments, Parameter Stores, Autotunes, holdouts, prompts, tags, dashboards, reviews, and partial updates. `api_read`, `api_write`, and `api_destructive` run the operation you discover. | Clients that use expanded tool exposure also show typed tools for layers, segments, Parameter Stores, and Autotunes. Your agent can find and run any operation that Statsig exposes through discovery, without a dedicated tool. For the inputs each tool accepts, go to the [tool reference](https://docs.statsig.com/integrations/mcp/tool-reference). #### Safety and confirmation - Update tools and `api_destructive` operations require a `confirmation`. Review each change before your agent supplies a `confirmation`. - `api_destructive` covers sensitive updates and review actions, not only deletion. - Project permissions and review policies still apply. Approving a review doesn't commit its changes. #### Legacy V1 resources Existing V1 connections remain supported. To update an existing connection, go to [Migrate to Statsig MCP V3](https://docs.statsig.com/integrations/mcp/migrate-to-v3). For the legacy tools, go to the [V1 tool reference](https://docs.statsig.com/integrations/mcp/v1-tool-reference). ## Use cases The Statsig MCP server supports both `GET` and `POST` requests. Read-only users can connect and use all read tools. Write tools require an API key with write permissions. The Statsig MCP server is especially useful for: - Repetitive tasks like cleaning up stale gates - Summarizing console information in your IDE workflows - Bulk creating or deleting gates, and making the necessary changes in your code ### Example prompt for stale gate cleanup ```text You are an expert, diligent Software engineer with the sole goal of reducing the amount of tech debt in the code base. This code base, making use of best practices, leverages feature gates liberally using Statsig. As gates complete their lifecycle in Statsig, they may end up "stale" which means that they're enabled, but no longer checked. Your job is to find these gates, and refactor the codebase to no longer check the gate (instead, changing the check to a constant value). You should follow coding best practices: - You should not simply replace gate calls with "True" or "False" but instead carefully trace the logic through to where it is used and change the behavior that way - adjusting the code in minor ways to make the default behavior what the value is that the gate was returning - You should always strive to write minimal code - readable but terse, never longer than it needs to be - You should never write comments or debug statements. You should use the statsig-local MCP to list feature gates, then look for gates that are marked as stale. You should then grep the codebase for that feature flag name, and do a minimal rewrite of the code to no longer use Statsig, removing the checkGate call or similar. When you use the MCP, list gates with type="STALE" and limit=10. Call gate_read with the get_list_of_gates action and the parameters query_type and query_limit. You should select only one gate to do this with, before stopping. If you cannot find the gate after a grep, try the next one you found using the MCP. Once you successfully remove a gate, return. ``` ================================================================================ # Statsig MCP with Codex URL: https://docs.statsig.com/integrations/mcp/codex ================================================================================ # Statsig MCP with Codex ## Installation and authentication with OAuth > **Note:** > > MCP OAuth only supports Personal Console API Keys. Ensure your Statsig org owner has enabled Personal Console API Keys creation for your role in [organization settings](https://console.statsig.com/settings?tab=organization). On Codex, use OAuth and the HTTP transport directly. Codex saves authentication for future sessions. #### Codex Desktop In Codex Desktop, navigate to _Settings > MCP servers_ and add a new custom server. Select Streamable HTTP and set the URL to `https://api.statsig.com/v3/mcp`: ![Set up Statsig MCP in the Codex Desktop App](https://docs.statsig.com/images/integrations/mcp/statsig-codex-desktop-app-setup.png) ![Set up Statsig MCP in the Codex Desktop App](https://docs.statsig.com/images/integrations/mcp/statsig-codex-desktop-app-setup.dark.png) Upon saving, you should see statsig turned on under custom servers. #### Codex CLI and IDE extension If you're working in Codex CLI or IDE extension, run the below command to add the Statsig MCP server into your `~/.codex/config.toml` file and restart Codex. ```bash codex mcp add statsig --url https://api.statsig.com/v3/mcp ``` This command opens a browser window for you to sign in to your Statsig account and authorize access to your Statsig project. After signing in, restart Codex and run `/mcp` in CLI to confirm the Statsig MCP appears as an available MCP server. Make sure the status is enabled: ![Statsig MCP in the Codex CLI MCP Servers List](https://docs.statsig.com/images/integrations/mcp/statsig-codex-cli-complete.png) #### Using API key instead of OAuth ```toml [mcp_servers.statsig] url = "https://api.statsig.com/v3/mcp" command = "npx" args = ["--yes", "mcp-remote", "https://api.statsig.com/v3/mcp", "--header", "statsig-api-key: console-YOUR-CONSOLE-API-KEY"] trust_level = "trusted" enabled = true ``` Replace `console-YOUR-CONSOLE-API-KEY` with your actual Statsig Console API key, which you can retrieve from the [API keys page](https://console.statsig.com/api_keys). Ensure your API key has the right permissions: read-only keys can view data, while write keys can make changes to your project. ## Using Statsig MCP with Codex With Statsig MCP configured in any Codex environment, you can: - **Explore Experiments**: "List all my active experiments" - **Manage Gates**: "What gates are currently stale?" - **Configure Dynamic Configs**: "Show me the configuration for the dynamic config 'dynamic-config'" - **Get Insights**: "Show me details about the experiment called 'new-checkout-flow'" ================================================================================ # Statsig ChatGPT App URL: https://docs.statsig.com/integrations/mcp/chatgpt-connector ================================================================================ # Statsig ChatGPT App ## How the Statsig ChatGPT app works The ChatGPT App builds on the Statsig MCP server. After setup, you can query experiments, manage feature flags, and explore analytics directly within OpenAI's ChatGPT conversational interface. ## Installation 1. Navigate to the Statsig App in the ChatGPT Apps Directory [here](https://chatgpt.com/apps/statsig/asdk_app_6967f065ac9481918969c660ff7686e9). 2. Click "Connect" and "Continue" to complete OAuth for your Statsig project. > **Note:** > > ChatGPT App OAuth only supports Personal Console API Keys. Ensure your Statsig org owner has enabled Personal Console API Keys creation for your role in [organization settings](https://console.statsig.com/settings?tab=organization). ![Statsig listing in the ChatGPT Apps Directory](https://docs.statsig.com/images/integrations/mcp/statsig-chatgpt-app-listing.png) ## Using Statsig MCP within ChatGPT With Statsig MCP configured in ChatGPT, you can: - **Explore Experiments**: "List all my active experiments" - **Manage Gates**: "What gates are currently stale?" - **Configure Dynamic Configs**: "Show me the configuration for the dynamic config 'dynamic-config'" - **Get Insights**: "Show me details about the experiment called 'new-checkout-flow'" ## What you can do after installation - List experiments, gates, and dynamic configs - Create and update experiments, gates, and configs - Access your Statsig data directly from ChatGPT For available MCP capabilities, go to the [MCP capabilities](https://docs.statsig.com/integrations/mcp/overview#current-mcp-capabilities) section. ================================================================================ # Connect Statsig to Claude URL: https://docs.statsig.com/integrations/mcp/claude-connector ================================================================================ # Connect Statsig to Claude Connect the Statsig MCP server to Claude to inspect your project's experiments, feature gates, dynamic configs, and metrics from a conversation. Authorize write access to create resources and apply permitted changes. This guide covers Claude on the web and Claude Desktop. For command-line setup, follow the [Claude Code guide](https://docs.statsig.com/integrations/mcp/claude-code). ## Prerequisites - A Claude account with permission to add a custom connector. Your Claude organization can restrict connector installation. - A Statsig account with access to the project you want to connect. - Permission to create Personal Console API Keys. Your Statsig organization owner controls this permission in [organization settings](https://console.statsig.com/settings?tab=organization). ## Add the Statsig connector 1. In Claude, open _Customize > Connectors_. 2. Select **Add**, then choose _Custom > Web_. 3. Enter `Statsig` as the connector name and this remote server URL: ```text https://api.statsig.com/v3/mcp ``` 4. Continue to the authentication settings. Choose OAuth sign-in and **Use Claude's published identity** for the OAuth client. 5. Connect and sign in to Statsig. Select the project and access level you want to authorize. 6. Return to Claude and enable the Statsig connector in a conversation. Claude stores the connection for future conversations. If your organization manages connector installation, ask your Claude administrator to add Statsig. ## Verify your project and access Ask Claude: ```text Which Statsig project am I connected to, and what permissions do I have? ``` Check that the project matches your intended workspace before requesting changes. Then try a read: ```text List up to five feature gates in this project, then explain the targeting rules for one gate I select. ``` You can also ask Claude to list experiments, retrieve available experiment results, or inspect a dynamic config. ## Make configuration changes Read-only access supports inspection. Write access enables permitted create and update operations. Statsig applies your project permissions and review policies to connector calls. For example, ask Claude to create a disabled gate in a test project. If the project requires a Target App, include its name in your request. Before an update, ask Claude to read the existing configuration and show the proposed change. Review the change before confirming it. Update tools can replace a resource's definition, so preserve fields you want to keep. ## Troubleshoot the connection - **Sign-in fails**: Check that your role can create Personal Console API Keys and that you have access to the selected project. - **The project is incorrect**: Reconnect Statsig and authorize the intended project before making changes. - **Write tools are missing**: Check the access level you granted and your Statsig project permissions. - **Claude asks to approve a tool again**: Review the tool's current description and arguments. A changed tool definition can require approval again. - **The connector loads no tools**: Verify that the server URL is `https://api.statsig.com/v3/mcp`, then reconnect. ================================================================================ # Statsig MCP with Cursor URL: https://docs.statsig.com/integrations/mcp/cursor ================================================================================ # Statsig MCP with Cursor ## Installation and authentication with OAuth > **Note:** > > MCP OAuth only supports Personal Console API Keys. Ensure your Statsig org owner has enabled Personal Console API Keys creation for your role in [organization settings](https://console.statsig.com/settings?tab=organization). You can add the Statsig MCP with OAuth to Cursor in two ways: ### Option 1: Quick install (recommended) Use the [install link](cursor://anysphere.cursor-deeplink/mcp/install?name=statsig&config=eyJ1cmwiOiJodHRwczovL2FwaS5zdGF0c2lnLmNvbS92My9tY3AifQ%3D%3D) to automatically add the Statsig MCP to Cursor. ### Option 2: Manual configuration 1. Open Cursor settings. 2. Navigate to _Settings > Cursor Settings > Tools & Integrations_. 3. Find the MCP servers section. 4. Add the following configuration to `~/.cursor/mcp.json`: ```json { "mcpServers": { "statsig": { "url": "https://api.statsig.com/v3/mcp" } } } ``` Cursor automatically handles OAuth authentication when you first use the Statsig MCP. Cursor prompts you to: 1. Sign in to your Statsig account. 2. Authorize the MCP server to access your Statsig project. 3. Restart Cursor to apply the changes. 4. Navigate to _Settings > Cursor Settings > Tools & Integrations_ and verify that the Statsig MCP server appears and is active. Cursor saves the authentication for future sessions. #### Using API key instead of OAuth OAuth is the recommended setup, but you can also authenticate with your Console API key. Use the [quick install link](cursor://anysphere.cursor-deeplink/mcp/install?name=statsig&config=eyJjb21tYW5kIjoibnB4IG1jcC1yZW1vdGUgaHR0cHM6Ly9hcGkuc3RhdHNpZy5jb20vdjMvbWNwIC0taGVhZGVyIHN0YXRzaWctYXBpLWtleToke0FVVEhfVE9LRU59IiwiZW52Ijp7IkFVVEhfVE9LRU4iOiJpbnNlcnQteW91ci1hcGkta2V5LWhlcmUifX0%3D), or configure it manually: 1. Open Cursor settings. 2. Navigate to _Settings > Cursor Settings > Tools & Integrations_. 3. Find the MCP servers section. 4. Add the following configuration to `~/.cursor/mcp.json`. ```json { "mcpServers": { "statsig": { "command": "npx mcp-remote https://api.statsig.com/v3/mcp --header statsig-api-key:${AUTH_TOKEN}", "env": { "AUTH_TOKEN": "console-YOUR-CONSOLE-API-KEY" } } } } ``` Replace `console-YOUR-CONSOLE-API-KEY` with your actual Statsig Console API key, which you can retrieve from the [API keys page](https://console.statsig.com/api_keys). Ensure your API key has the right permissions: read-only keys can view data, while write keys can make changes to your project. ## Using Statsig MCP with Cursor After configuration, you can use Statsig MCP commands in Cursor's chat interface: - **Query Experiments**: "What experiments are currently running?" - **Manage Gates**: "List all my feature flags" - **Get Details**: "Show me the configuration for gate 'new-feature'" - **Create Entities**: "Create a new experiment called 'checkout-test'" ## Troubleshooting If the MCP server doesn't appear: - Make sure you've restarted Cursor after adding the configuration. - Check that the `mcp.json` file is in the correct location: `~/.cursor/mcp.json`. - Verify your Statsig account has the necessary permissions. ================================================================================ # Statsig MCP with Claude Code URL: https://docs.statsig.com/integrations/mcp/claude-code ================================================================================ # Statsig MCP with Claude Code ## Installation and authentication with OAuth > **Note:** > > MCP OAuth only supports Personal Console API Keys. Ensure your Statsig org owner has enabled Personal Console API Key creation for your role in [organization settings](https://console.statsig.com/settings?tab=organization). On Claude Code, use OAuth and the HTTP transport directly. Run this command: ```bash claude mcp add --transport http statsig https://api.statsig.com/v3/mcp ``` This command: - Adds the Statsig MCP server to your Claude Code configuration. - Configures it to use HTTP transport with OAuth authentication. - Sets up the connection to Statsig's MCP endpoint. To authenticate with OAuth, run `/mcp` in Claude Code and follow the setup instructions: 1. Claude Code opens a browser window. 2. Sign in to your Statsig account. 3. Authorize the MCP server to access your Statsig project. 4. Claude Code saves the authentication for future sessions. #### Using API key instead of OAuth OAuth is the recommended setup, but you can also authenticate with your Console API key. Run this command on the command line: ```bash claude mcp add --transport http statsig-local https://api.statsig.com/v3/mcp \ --header "statsig-api-key: console-YOUR-CONSOLE-API-KEY" ``` Replace `console-YOUR-CONSOLE-API-KEY` with your actual Statsig Console API key, which you can find on the [API keys page](https://console.statsig.com/api_keys). Ensure your API key has the required permissions: read-only keys can view data, while write keys can make changes to your project. ## Verify the connection After installation, verify the connection: 1. Open Claude Code. 2. Ask Claude to list your Statsig experiments or gates. 3. Confirm that Claude can access your Statsig data. ## Using Statsig MCP with Claude Code After configuration, you can interact with your Statsig data through Claude Code: - **Query Experiments**: "What experiments are currently running?" - **Manage Gates**: "List all my feature flags" - **Get Details**: "Show me the configuration for gate 'new-feature'" - **Create Entities**: "Create a new experiment called 'checkout-test'" ## Troubleshooting If you encounter issues: - Make sure you have the latest version of Claude Code. - Verify your Statsig account has the necessary API permissions. - Check that the MCP server URL is `https://api.statsig.com/v3/mcp`. - Try re-running the installation command. ================================================================================ # Statsig MCP with Other MCP-Compatible Clients URL: https://docs.statsig.com/integrations/mcp/manual-setup ================================================================================ # Statsig MCP with Other MCP-Compatible Clients If your tool doesn't have a specific setup guide, you can manually configure the Statsig MCP server. This guide covers the general configuration steps that work with any MCP-compatible client. ## Prerequisites - A Statsig account (sign up at [console.statsig.com](https://console.statsig.com)) - An MCP-compatible tool or client that supports Streamable HTTP - Access to your tool's configuration files ## Configuration Add the following configuration to your MCP client's configuration file: ```json { "mcpServers": { "statsig": { "url": "https://api.statsig.com/v3/mcp" } } } ``` This installs the Statsig MCP server with OAuth. When you first use the MCP server: 1. Your tool prompts you to authenticate. 2. Statsig redirects you to its OAuth page. 3. Sign in and authorize the MCP server. 4. Your tool stores the authentication token automatically. > **Note:** > > MCP OAuth only supports Personal Console API Keys. Ensure your Statsig org owner has enabled Personal Console API Keys creation for your role in [organization settings](https://console.statsig.com/settings?tab=organization). #### Using API key instead of OAuth OAuth is the recommended setup, but you can also authenticate with your Console API key. Add the following configuration to your MCP client's configuration file: ```json { "mcpServers": { "statsig": { "command": "npx mcp-remote https://api.statsig.com/v3/mcp --header statsig-api-key:${AUTH_TOKEN}", "env": { "AUTH_TOKEN": "console-YOUR-CONSOLE-API-KEY" } } } } ``` Replace `console-YOUR-CONSOLE-API-KEY` with your actual Statsig Console API key, which you can retrieve from the [API keys page](https://console.statsig.com/api_keys). Ensure your API key has the right permissions: read-only keys can view data, while write keys can make changes to your project. ## Verification After adding the configuration: 1. Restart your tool to apply the changes. 2. Check your tool's MCP server list to verify Statsig appears. 3. Try using a Statsig MCP command to test the connection. ## Testing the connection You can test the connection by asking your tool to: - **Check the project**: "Which Statsig project am I connected to, and what permissions do I have?" - **List experiments**: "Get list of experiments" - **List gates**: "Get list of gates" - **Get details**: "Get details for experiment \[experiment-id\]" ================================================================================ # Enterprise-Managed Authorization for Statsig MCP URL: https://docs.statsig.com/integrations/mcp/enterprise-managed-auth ================================================================================ # Enterprise-Managed Authorization for Statsig MCP Enterprise-managed authorization (EMA) lets an admin configure Claude's connection to Statsig MCP centrally. Members don't supply a personal Console API key or approve the connection themselves. Claude acts as the person already signed in, and Statsig still applies that person's organization membership, project permissions, and review requirements. Use enterprise-managed authorization when your identity provider decides who can open Claude against Statsig. Use the [standard MCP setup](https://docs.statsig.com/integrations/mcp/manual-setup) when each person authenticates their own connection. Statsig supports two identity modes, and you pick one per organization: | Identity mode | Trusted issuer you enter in Statsig | Statsig SSO required | | --- | --- | --- | | Claude-issued identity | The organization-specific issuer Claude shows during setup, such as `https://identity.anthropic.com/issuers/<tenant>` | No | | Okta / OIDC Cross App Access | The exact Okta issuer your Statsig OIDC SSO configuration already uses | Yes, though `Strict SSO` remains optional | You configure issuer trust once for a Statsig organization. Each Claude connection then targets a single Statsig project, which you identify with that project's Tenant ID. ## Prerequisites - You have the `Owner` or `Admin` role in the Statsig organization you're configuring, and you can manage connectors in Claude. Okta mode also needs an Okta administrator. - Your projects belong to a Statsig organization. Organizations are an Enterprise feature, and EMA is an organization setting. - Each member has a Statsig account with a verified email and access to the target project. EMA doesn't provision Statsig users, and the email your identity provider asserts must match the member's verified Statsig email. - For Okta mode only, your organization already has OIDC SSO configured with [Okta](https://docs.statsig.com/access-management/sso/okta_sso). The issuer you enter for EMA must match that configuration exactly. ## Find your Tenant ID Both identity modes need the target project's Statsig project ID, which Claude calls the Tenant ID. Copy it before you start: 1. In the Statsig console, open the project you want Claude to connect to. 2. Go to _Settings > Info > Organization_, which holds the organization name, SSO configuration, and access management settings. 3. Under _Access Management > MCP Enterprise Managed Auth_, select **Enable** (Click **Configure** if you're already Enabled) and then turn on **Enable enterprise managed auth** and then click **Save**. You must first enable EMA before you can access the Tenant ID, issuer, and access fields. 4. Click **Configure** again and then, in the Connect Statsig section, copy the **Tenant ID (project ID)** value and the MCP URL, `https://api.statsig.com/v3/mcp`. Statsig shows **Configure** whether or not SSO is enabled, because Claude-issued identity doesn't require SSO. Only the Okta option stays disabled until you configure SSO. > **Warning:** > > The Tenant ID must be the target Statsig project ID. A Statsig organization ID, an Okta client ID, or a Claude tenant ID doesn't resolve, and a blank field breaks the connection. Confirm that the dialog names the organization you intend to configure before you save. ## Set up Claude-issued identity Claude-issued identity works without Statsig SSO, so it's the shorter path. 1. In Claude's organization connector settings, add or select the Statsig connector and open its managed-authorization setup. To add a custom connector, use `https://api.statsig.com/v3/mcp`. 2. Select **Claude-issued identity**, then copy the exact issuer Claude shows for your Claude organization. A generic `https://claude.ai` URL or another organization's issuer doesn't work. 3. In Statsig, go to _Settings > Info > Organization_, select **Claude-issued identity**, and copy/paste the issuer into **Trusted issuer URL**. 4. Set **Maximum MCP access** to either **Read only** or **Read and write**. 5. Turn on **Enable enterprise managed auth**, then click **Save**. 6. Re-open the MCP enterprise managed auth modal, find the Connect Statsig section, and copy the **Tenant ID**. 7. Back in Claude, paste the Statsig project's Tenant ID into the **Tenant ID** field, select the roles and scopes you want to permit, then run the connection test. 8. Finish setup after the test passes, then confirm the connection resolves to the right project. If Claude doesn't offer Claude-issued identity, ask your Claude administrator to enable it before you continue. ## Set up Okta / OIDC Cross App Access Okta mode reuses the identity provider your members already sign in with. It requires an existing Statsig OIDC SSO configuration, but it doesn't require `Strict SSO`, the setting that forces every member except the `Owner` to sign in through your provider. Four values look similar and cause most setup failures when they're interchanged: | Field | Value | | --- | --- | | Statsig **Trusted issuer URL** | Your exact Okta SSO issuer, using the org authorization server | | Okta resource app **Issuer URL** | The Statsig authorization-server issuer from the connector's discovery information | | Okta resource app **Audience/tenant ID** | Your Statsig project ID, copied from the EMA dialog | | Agent/client registration | Claude's registration details, not Statsig's login-app credentials | 1. Configure OIDC SSO for the Statsig organization with the [Okta SSO guide](https://docs.statsig.com/access-management/sso/okta_sso), and record its exact issuer. 2. In Okta, register and activate Claude's AI agent against the app your members use to sign in to Claude, following the setup guide Claude supplies. A Claude SAML login can take part in this flow, but it doesn't replace Statsig's separate OIDC SSO prerequisite. 3. Configure the Statsig resource app for Cross App Access, then connect the Claude AI agent to it with the scope policy you want. For the Okta-side steps, refer to [Okta's Cross App Access guide](https://developer.okta.com/docs/guides/xaa-agent-to-app/main/). 4. In Statsig, go to _Settings > Info > Organization_, select **Okta / OIDC Cross App Access**, enter the matching Okta issuer, set **Maximum MCP access**, turn on **Enable enterprise managed auth**, then save. The signed assertion must contain the user's email. 5. Re-open the MCP enterprise managed auth modal, find the Connect Statsig section, and copy the **Tenant ID**. 6. In Claude, paste the Statsig project's Tenant ID into the **Tenant ID** field, select the permitted roles and scopes, sign in through the linked Okta app, then run the connection test. 7. Finish setup after the test passes, then confirm the connection resolves to the right project. Keep the Claude requesting app and the Statsig login and resource apps separate. Don't reuse a shared app's credentials or change an existing SSO integration to make a test pass. ## Set read-only or read/write access Three controls decide what Claude can do: Statsig's maximum MCP access, the scopes and roles you select in Claude, and, for Okta mode, the resource app and agent connection policy. Align all three. | Intended access | Statsig maximum | Claude scope selection | Okta policy | | --- | --- | --- | --- | | Read only | Read only | `personal_read_only` only | Allow `personal_read_only` | | Read and write | Read and write | Include `personal_read_write` | Allow `personal_read_write` and every other scope Claude requests | The scopes the server advertises are the capabilities it supports, not the permissions every organization grants. Write access still depends on each member's existing Statsig permissions: selecting read and write doesn't elevate a role or bypass a review. If Claude requests both scopes while your identity provider allows only read-only, Okta returns `invalid_scope`. Continue through setup to reach Claude's scope controls, remove the write scope, then rerun the test. Check that the requested scopes contain only what you intend. Don't widen the identity provider policy to pass a read-only test. ## Verify the connection A successful setup completes discovery, identity assertion, access-token exchange, and the connector probe. Test labels vary by Claude version. To confirm the connection resolved to the right project, ask Claude: > Use the Statsig connector to show the connected project name and my access level. Do not make any changes. Check that Claude names the project and organization you configured. A read-only connection reports `personal_read_only` and no write access. Test writes separately, in a dedicated test project, with an authorized user. ## Troubleshooting | Problem | What to check | | --- | --- | | The Okta option is disabled in Statsig | Configure OIDC SSO for the organization the dialog names. `Strict SSO` is optional. | | `invalid_scope` when requesting identity | Compare the scopes Claude requests against the scopes Okta allows, and narrow Claude's selection for a read-only policy. | | `invalid_subject_token_no_delegation_link` | Confirm the active agent links to the app used for Claude SSO and has the intended resource connection, then reauthenticate. | | Identity succeeds, but the exchange returns `invalid_grant` | Check that EMA is enabled for the organization, the issuer matches exactly, the Tenant ID is the target project ID, and the member has a verified email and project access. Read the server error before assuming one cause. | | The exchange returns `503 server_error` | Investigate authorization-server health. A `503` isn't evidence that scopes or SSO settings need to change. | | The login redirect doesn't match | Check which console environment and callback the login app allows. Diagnose a redirect mismatch separately from EMA token exchange. | ================================================================================ # Statsig MCP V3 tool reference URL: https://docs.statsig.com/integrations/mcp/tool-reference ================================================================================ # Statsig MCP V3 tool reference Statsig MCP V3 exposes 18 default tools. Clients that use expanded tool exposure show 9 more tools. Tool visibility depends on your permissions and the server configuration. Use the live tool schemas for full nested fields and valid values. ## Start with these steps 1. Call `get_context` to check your project and permissions. 2. Use the direct tools for common tasks. Use `discover_tools` for other operations, reviews, and partial updates. 3. Confirm changes before you supply `confirmation`. Project permissions and review policies still apply. ## Request shapes | Tool type | Request shape | | --- | --- | | Grouped read | `action` and `arguments.params` | | Create | `params["application/json"]` | | Update and `autotune_create` | `arguments.params` and `confirmation` | | Discovered operation | `operationHandle` and `arguments`. Add `confirmation` for `api_destructive`. | A `confirmation` looks like this: ```json { "acknowledged": true, "reason": "Describe the intended change" } ``` ## Context and search | Tool | Purpose | Inputs | | --- | --- | --- | | `get_context` | Get bounded project, permission, review, and product context. | Optional: `scope`, `fields`, `limit`. `scope` is `session` (default), `project`, or `all`. `fields` selects `organization`, `project`, `environment`, `permissions`, `reviewSettings`, `accessibleProducts`, `environments`, `eventSources`, `metrics`, `defaultTimezone`, or `links`. `limit` is 1-50 (default 20). | | `search` | Search Statsig resources after you identify a resource type or target. If a request is underspecified, such as "the rollout" with no gate or config name, ask a clarifying question first. | Required: `query` (1-1024 characters). Optional: `limit` (1-100). | | `fetch` | Fetch a resource you selected from a search result. | Required: `id`, the identifier `search` returned (at least 3 characters). | ## Read tools Read tools are read-only. Supply `action` and `arguments.params`, and include `params` even when no fields are required. ### gate\_read List, get, and inspect feature gates and their history. | Action | Required | Optional | | --- | --- | --- | | `get_gate_details_by_id` | `path_id` | None | | `get_gate_results` | `path_id`, `path_ruleID` | `query_cuped`, `query_confidence` | | `get_gate_version_history` | `path_id` | `query_limit`, `query_page` | | `get_list_of_gates` | None | `query_type`, `query_creatorName`, `query_tags`, `query_limit`, `query_page` | ### experiment\_read List, get, inspect, and retrieve results for experiments. | Action | Required | Optional | | --- | --- | --- | | `get_experiment_details_by_id` | `path_id` | `query_fields` | | `get_experiment_metric_dimension_results` | `path_id`, `query_control`, `query_test`, `query_metricID` | `query_cuped`, `query_confidence`, `query_date` | | `get_experiment_overall_results` | `path_id`, `query_control`, `query_test` | `query_cuped`, `query_confidence`, `query_date` | | `get_experiment_version_history` | `path_id` | `query_limit`, `query_page` | | `get_list_of_experiments` | None | `query_status`, `query_creatorName`, `query_tags`, `query_stale`, `query_teamID`, `query_createdStartDate`, `query_createdEndDate`, `query_ids`, `query_fields`, `query_limit`, `query_page` | | `get_experiment_summary_charts` | `path_id` | `query_control`, `query_test` | Use `query_fields` to return only the fields you need and reduce context consumption. ### dynamic\_config\_read List, get, and inspect dynamic configs and their history. | Action | Required | Optional | | --- | --- | --- | | `get_dynamic_config_details_by_id` | `path_id` | None | | `get_dynamic_config_version_history` | `path_id` | `query_limit`, `query_page` | | `get_list_of_dynamic_configs` | None | `query_creatorName`, `query_tags`, `query_limit`, `query_page` | ### metric\_read List and inspect metrics and metric sources. | Action | Required | Optional | | --- | --- | --- | | `get_list_of_metric_sources` | None | `query_limit`, `query_page` | | `get_list_of_metrics` | None | `query_showHiddenMetrics`, `query_tags`, `query_filters`, `query_limit`, `query_page` | | `get_metric_definition_by_id` | `path_id` | None | ### log\_read Query Logs Explorer and inspect project audit and change history. | Action | Required | Optional | | --- | --- | --- | | `get_audit_logs` | None | `query_id`, `query_sortKey`, `query_sortOrder`, `query_tags`, `query_actionTypes`, `query_startDate`, `query_endDate`, `query_limit`, `query_page` | | `query_logs_explorer` | None | `query_query`, `query_source`, `query_columns`, `query_start_ts`, `query_end_ts`, `query_limit`, `query_after` | ### Expanded read tools These tools appear when your client uses expanded tool exposure. | Tool | Action | Required | Optional | | --- | --- | --- | --- | | `layer_read` | `get_layer_details_by_id` | `path_id` | None | | `layer_read` | `get_layer_experiments` | `path_id` | `query_limit`, `query_page` | | `layer_read` | `get_layer_overrides` | `path_id` | None | | `layer_read` | `get_list_of_layers` | None | `query_limit`, `query_page` | | `segment_read` | `get_list_of_segments` | None | `query_limit`, `query_page` | | `segment_read` | `get_segment_by_id` | `path_id` | None | | `param_store_read` | `get_list_of_param_stores` | None | `query_limit`, `query_page` | | `param_store_read` | `get_param_store_details_by_id` | `path_id` | None | ## Create tools Create tools take the body in `params["application/json"]`. The exception is `autotune_create`, which requires `arguments.params` and `confirmation`. The fields in the table describe the body. | Tool | Availability | Required | Optional | | --- | --- | --- | --- | | `gate_create` | Default, write access | None | `name`, `rules`, `tags`, `idType`, `targetApps`, `team`, `id` | | `experiment_create` | Default, write access | `name` | `description`, `idType`, `secondaryIDType`, `identifierMappingMode`, `allocation`, `layerID`, `targetingGateID`, `hypothesis`, `links`, `groups`, `primaryMetrics`, `secondaryMetrics`, `targetApps`, `tags`, `assignmentSourceName`, `assignmentSourceExperimentName`, `isAnalysisOnly`, `scheduledReloadHour`, `scheduledReloadType`, `scheduledReloadDays`, `turboMode`, `enabledNonProdEnvironments`, `team`, `id` | | `dynamic_config_create` | Default, write access | `name` | `rules`, `defaultValue`, `idType`, `targetApps`, `team`, `tags`, `id` | | `layer_create` | Expanded, write access | `name`, `idType` | `description`, `targetApps`, `team` | | `segment_create` | Expanded, write access | `name`, `type` | `id`, `description`, `idType`, `tags`, `team`, `teamID`, `rules` | | `param_store_create` | Expanded, write access | `name`, `description`, `displayName` | `targetAppIDs`, `tags`, `team` | | `autotune_create` | Expanded, confirmation required | `variants`, `successEvent`, `explorationWindow`, `attributionWindow`, `winnerThreshold`, `name` | `description`, `successEventValue`, `attributionWindowUnit`, `explorationWindowRate`, `longtermExplorationAllocation`, `metadataField`, `higherIsBetter`, `isContextual`, `metricSourceID`, `linkedExperimentName`, `goalRichText`, `optimizationParameter`, `valueColumn`, `featureList`, `excludedFeatureList`, `idType` | In projects that use Target Apps, `gate_create` requires `targetApps` to contain at least one Target App name, not an internal database record ID. ## Update tools Update tools require write access, `arguments.params`, and `confirmation`. Supply the resource identifier in `arguments.params.path_id` and the body in `arguments.params["application/json"]`. Most update tools replace the whole resource. Read the current state first and preserve any field you don't intend to change. For a partial edit, such as adding a tag, use `discover_tools` to find the matching operation. | Tool | Availability | Required | Optional | | --- | --- | --- | --- | | `gate_update` | Default | `isEnabled`, `description`, `rules` | `name`, `tags`, `idType`, `team`, `gradual_rollout_strategy` | | `experiment_update` | Default | `description`, `idType`, `hypothesis`, `groups`, `allocation`, `targetingGateID`, `bonferroniCorrection`, `defaultConfidenceInterval`, `status` | `name`, `secondaryIDType`, `identifierMappingMode`, `links`, `primaryMetrics`, `secondaryMetrics`, `tags`, `scheduledReloadHour`, `scheduledReloadType`, `scheduledReloadDays`, `turboMode`, `enabledNonProdEnvironments`, `team`, `targetApps`, `duration` | | `dynamic_config_update` | Default | `isEnabled`, `description`, `rules` | `name`, `defaultValue`, `idType`, `targetApps`, `team`, `tags` | | `segment_update` | Expanded | `path_id`, `application/json` | `query_operation` | | `param_store_update` | Expanded | None | `description`, `parameters` | For `segment_update`, the request body depends on the selected operation and segment type. Read the live schema for the matching body variant. For `param_store_update`, use `path_id` for the Parameter Store identifier. Don't use `path_name`. ## Discover additional operations `discover_tools` is read-only. Start with `resolve` when you know the task. Omit filters you're unsure about, especially `lane`, because updates and review actions can use `api_destructive`. | Action | Required | Optional | Behavior | | --- | --- | --- | --- | | `resolve` | `query` | `category`, `lane`, `operationAction` | A confident match returns the contract and handle. An ambiguous match returns alternatives. | | `resolve_many` | `requests` (1-5 independent queries) | Each request accepts `query` and optionally `category`, `lane`, `operationAction`. | Resolves operations only. Execution stays separate. | | `list` | None | `query`, `category`, `lane`, `operationAction`, `limit` (1-10, default 5) | Use `get` to retrieve the chosen contract before you run it. | | `get` | `operationId` | None | Returns the selected operation contract. | ### Run a discovered operation 1. Read the returned input schema, lane, and confirmation requirements. 2. Call the returned execution tool with its `operationHandle` and arguments that match the schema. 3. Retrieve a fresh handle when the current one expires. | Execution tool | Access | Required inputs | | --- | --- | --- | | `api_read` | Read-only | `operationHandle`, `arguments` | | `api_write` | Write access. The tool schema doesn't require confirmation. | `operationHandle`, `arguments` | | `api_destructive` | Write access. Confirmation required. | `operationHandle`, `arguments`, `confirmation` | Discovered arguments use `path`, `query`, and `body`. The `params` wrapper that direct tools use doesn't apply. `api_destructive` covers sensitive updates and review actions, not only deletion. A confirmation requirement is separate from a project review. Approving a review doesn't commit its changes. ## Check responses - Check `isError` before you read `structuredContent` data. - Follow the selected operation's pagination. - An empty result doesn't establish that a resource is safe to delete. ================================================================================ # Automate Statsig MCP in scheduled and CI jobs URL: https://docs.statsig.com/integrations/mcp/automation-examples ================================================================================ # Automate Statsig MCP in scheduled and CI jobs Use a scheduled job or CI workflow to retrieve the references for a gate before you plan cleanup. This read-only example discovers the operation, then calls it directly, so it needs no LLM. ## Prerequisites - A Console API key with access to the project, stored as `STATSIG_API_KEY` in your runner's secret store - The ID of an existing gate in that project, set as `STATSIG_GATE_ID` - Python with the `mcp` package, or Node.js 22 or later with the MCP JavaScript SDK ## Check gate references #### Python 1. Install the SDK: ```bash python -m pip install mcp==1.30.0 ``` 2. Save the following script as `gate_references.py`: ```python import asyncio import json import os import httpx from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client URL = "https://api.statsig.com/v3/mcp" async def main(): headers = {"statsig-api-key": os.environ["STATSIG_API_KEY"]} async with httpx.AsyncClient(headers=headers) as http: async with streamable_http_client(URL, http_client=http) as streams: async with ClientSession(streams[0], streams[1]) as session: await session.initialize() discovery = await session.call_tool("discover_tools", { "action": "get", "operationId": "feature_gates.list.list_gate_references", }) if discovery.isError: raise RuntimeError("Gate discovery failed") operation = discovery.structuredContent["data"] if operation["lane"] != "api_read": raise RuntimeError("Expected a read-only operation") result = await session.call_tool(operation["lane"], { "operationHandle": operation["handle"], "arguments": {"path": {"id": os.environ["STATSIG_GATE_ID"]}}, }) if result.isError: raise RuntimeError("Gate reference lookup failed") print(json.dumps(result.structuredContent["data"], indent=2)) asyncio.run(main()) ``` 3. Run the script: ```bash python gate_references.py ``` #### JavaScript 1. Install the SDK: ```bash npm install @modelcontextprotocol/sdk@1.30.0 ``` 2. Save the following script as `gate_references.mjs`: ```javascript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; const key = process.env.STATSIG_API_KEY; const gateId = process.env.STATSIG_GATE_ID; if (!key || !gateId) { throw new Error("Set STATSIG_API_KEY and STATSIG_GATE_ID"); } const client = new Client({ name: "gate-reference-job", version: "1.0.0" }); const transport = new StreamableHTTPClientTransport( new URL("https://api.statsig.com/v3/mcp"), { requestInit: { headers: { "statsig-api-key": key } } } ); try { await client.connect(transport); const discovery = await client.callTool({ name: "discover_tools", arguments: { action: "get", operationId: "feature_gates.list.list_gate_references", }, }); if (discovery.isError) throw new Error("Gate discovery failed"); const operation = discovery.structuredContent.data; if (operation.lane !== "api_read") { throw new Error("Expected a read-only operation"); } const result = await client.callTool({ name: operation.lane, arguments: { operationHandle: operation.handle, arguments: { path: { id: gateId } }, }, }); if (result.isError) throw new Error("Gate reference lookup failed"); console.log(JSON.stringify(result.structuredContent.data, null, 2)); } finally { await client.close(); } ``` 3. Run the script: ```bash node gate_references.mjs ``` The script prints the API response for one page of gate references. To get more pages, follow the returned pagination with `arguments.query.page`. An empty result doesn't prove that a gate is safe to delete. ## Production practices - Retrieve a fresh operation handle on every run. Handles expire, so don't store them. - Check `isError` before you read `structuredContent`. - Confirm the returned `lane` is the one you expect before you call it, as the examples do with `api_read`. - Use a read-only API key for jobs that only read. ================================================================================ # Migrate to Statsig MCP V3 URL: https://docs.statsig.com/integrations/mcp/migrate-to-v3 ================================================================================ # Migrate to Statsig MCP V3 Statsig MCP V3 replaces the 93 individual tools on the V1 server with 18 default tools and a discovery layer. Statsig recommends V3, but V1 remains supported, so you can migrate when you're ready. Use this page to find the V3 replacement for each V1 tool you use and update your prompts, scripts, and automation. ## Prerequisites - An existing Statsig MCP connection that uses the V1 server URL (`https://api.statsig.com/v1/mcp`) - A V3 connection (`https://api.statsig.com/v3/mcp`). Follow the [manual setup](https://docs.statsig.com/integrations/mcp/manual-setup) or your client's setup guide. ## How the mapping works Each V1 tool maps to one of two V3 calls. **Direct call**: Call the named V3 tool. - For grouped read tools such as `gate_read`, set `action` to the listed action and put the V1 argument object under `arguments.params`. - Create tools take the body in `params["application/json"]`. - Update tools require `arguments.params` and `confirmation`. - `get_context`, `search`, `fetch`, and `discover_tools` use their own schemas. **Discovery call**: Rows that start with "Discovery" take two steps: 1. Call `discover_tools` with `action` set to `get` and the listed operation ID. 2. Call the execution tool the response returns (`api_read`, `api_write`, or `api_destructive`) with its `operationHandle` and arguments that match the returned schema. Include `confirmation` when the schema requires it. An `operationHandle` expires, so retrieve a new one when you need it instead of hardcoding it. `api_destructive` also covers some updates and review actions, not only deletion. Your project permissions and review policies still apply. ### Example: read a gate To replace `Get_Gate_Details_by_ID`, call `gate_read`: ```json { "action": "get_gate_details_by_id", "arguments": { "params": { "path_id": "your_gate_id" } } } ``` ## Before you migrate - Check the server's current tool and discovery schemas for required fields and available operations. - For Parameter Store lookup, update, and delete, use `params.path_id` instead of `params.path_name`. - V3 returns `structuredContent` alongside text. Check any response parsing in your automation. - If you keep both versions connected while you test, disable the version you aren't testing to avoid duplicate tools. The tool mapping covers the default V3 connection. Clients that use expanded tool exposure might also show typed tools for some discovery operations. Refer to the [Statsig MCP tool reference](https://docs.statsig.com/integrations/mcp/tool-reference). ## Tool mapping ### Context, search, and discovery | V1 tool | V3 replacement | | --- | --- | | `fetch` | `fetch` | | `Get_Context` | `get_context` | | `Get_Tool_Schema` | `discover_tools`, action `get`, with the discovered operation ID | | `Invoke_Tool` | Discovery, then `api_read`, `api_write`, or `api_destructive`, based on the returned lane, handle, and schema | | `search` | `search` | | `Search_Tools` | `discover_tools`, action `list` or `resolve` | ### Feature gates | V1 tool | V3 replacement | | --- | --- | | `Approve_Gate_Review` | Discovery: `feature_gates.approve.approve_gate_review` with `api_destructive` | | `Cancel_Gate_Review` | Discovery: `feature_gates.cancel.cancel_gate_review` with `api_destructive` | | `Commit_Gate_Review` | Discovery: `feature_gates.commit.commit_gate_review` with `api_destructive` | | `Create_Gate` | `gate_create`, input `params` | | `Create_Gate_Review` | Discovery: `feature_gates.create.create_gate_review` with `api_write` | | `Edit_Gate_Review` | Discovery: `feature_gates.edit.edit_gate_review` with `api_destructive` | | `Get_Gate_Details_by_ID` | `gate_read`, action `get_gate_details_by_id` | | `Get_Gate_Eligible_Reviewers` | Discovery: `feature_gates.list.get_gate_eligible_reviewers` with `api_read` | | `Get_Gate_Results` | `gate_read`, action `get_gate_results` | | `Get_Gate_Review_by_ID` | Discovery: `feature_gates.get.get_gate_review_by_id` with `api_read` | | `Get_Gate_Version_History` | `gate_read`, action `get_gate_version_history` | | `Get_List_of_Gate_Reviews` | Discovery: `feature_gates.list.get_list_of_gate_reviews` with `api_read` | | `Get_List_of_Gates` | `gate_read`, action `get_list_of_gates` | | `Reject_Gate_Review` | Discovery: `feature_gates.reject.reject_gate_review` with `api_destructive` | | `Start_Gate_Code_Cleanup` | Discovery: `feature_gates.start_cleanup.start_gate_code_cleanup` with `api_destructive` | | `Update_Gate_Entirely` | `gate_update`, input `arguments` and `confirmation` | ### Experiments | V1 tool | V3 replacement | | --- | --- | | `Approve_Experiment_Review` | Discovery: `experiments.approve.approve_experiment_review` with `api_destructive` | | `Cancel_Experiment_Review` | Discovery: `experiments.cancel.cancel_experiment_review` with `api_destructive` | | `Commit_Experiment_Review` | Discovery: `experiments.commit.commit_experiment_review` with `api_destructive` | | `Create_Experiment` | `experiment_create`, input `params` | | `Create_Experiment_Review` | Discovery: `experiments.create.create_experiment_review` with `api_write` | | `Delete_Experiment` | Discovery: `experiments.delete.delete_experiment` with `api_destructive` | | `Edit_Experiment_Review` | Discovery: `experiments.edit.edit_experiment_review` with `api_destructive` | | `Get_Experiment_Details_by_ID` | `experiment_read`, action `get_experiment_details_by_id` | | `Get_Experiment_Eligible_Reviewers` | Discovery: `experiments.list.get_experiment_eligible_reviewers` with `api_read` | | `Get_Experiment_Metric_Dimension_Results` | `experiment_read`, action `get_experiment_metric_dimension_results` | | `Get_Experiment_Overall_Results` | `experiment_read`, action `get_experiment_overall_results` | | `Get_Experiment_Review_by_ID` | Discovery: `experiments.get.get_experiment_review_by_id` with `api_read` | | `Get_Experiment_Version_History` | `experiment_read`, action `get_experiment_version_history` | | `Get_List_of_Experiment_Reviews` | Discovery: `experiments.list.get_list_of_experiment_reviews` with `api_read` | | `Get_List_of_Experiments` | `experiment_read`, action `get_list_of_experiments` | | `GetExperimentSummaryCharts` | `experiment_read`, action `get_experiment_summary_charts` | | `Reject_Experiment_Review` | Discovery: `experiments.reject.reject_experiment_review` with `api_destructive` | | `Start_Experiment_Code_Cleanup` | Discovery: `experiments.start_cleanup.start_experiment_code_cleanup` with `api_destructive` | | `Update_Experiment_Entirely` | `experiment_update`, input `arguments` and `confirmation` | ### Dynamic configs | V1 tool | V3 replacement | | --- | --- | | `Approve_Dynamic_Config_Review` | Discovery: `dynamic_configs.approve.approve_dynamic_config_review` with `api_destructive` | | `Cancel_Dynamic_Config_Review` | Discovery: `dynamic_configs.cancel.cancel_dynamic_config_review` with `api_destructive` | | `Commit_Dynamic_Config_Review` | Discovery: `dynamic_configs.commit.commit_dynamic_config_review` with `api_destructive` | | `Create_Dynamic_Config` | `dynamic_config_create`, input `params` | | `Create_Dynamic_Config_Review` | Discovery: `dynamic_configs.create.create_dynamic_config_review` with `api_write` | | `Edit_Dynamic_Config_Review` | Discovery: `dynamic_configs.edit.edit_dynamic_config_review` with `api_destructive` | | `Get_Dynamic_Config_Details_by_ID` | `dynamic_config_read`, action `get_dynamic_config_details_by_id` | | `Get_Dynamic_Config_Eligible_Reviewers` | Discovery: `dynamic_configs.list.get_dynamic_config_eligible_reviewers` with `api_read` | | `Get_Dynamic_Config_Review_by_ID` | Discovery: `dynamic_configs.get.get_dynamic_config_review_by_id` with `api_read` | | `Get_Dynamic_Config_Version_History` | `dynamic_config_read`, action `get_dynamic_config_version_history` | | `Get_List_of_Dynamic_Config_Reviews` | Discovery: `dynamic_configs.list.get_list_of_dynamic_config_reviews` with `api_read` | | `Get_List_of_Dynamic_Configs` | `dynamic_config_read`, action `get_list_of_dynamic_configs` | | `Reject_Dynamic_Config_Review` | Discovery: `dynamic_configs.reject.reject_dynamic_config_review` with `api_destructive` | | `Update_Dynamic_Config_Entirely` | `dynamic_config_update`, input `arguments` and `confirmation` | ### Autotunes | V1 tool | V3 replacement | | --- | --- | | `Approve_Autotune_Review` | Discovery: `autotunes.approve.approve_autotune_review` with `api_destructive` | | `Cancel_Autotune_Review` | Discovery: `autotunes.cancel.cancel_autotune_review` with `api_destructive` | | `Commit_Autotune_Review` | Discovery: `autotunes.commit.commit_autotune_review` with `api_destructive` | | `Create_Autotune` | Discovery: `autotunes.create.create_autotune` with `api_destructive` | | `Create_Autotune_Review` | Discovery: `autotunes.create.create_autotune_review` with `api_write` | | `Edit_Autotune_Review` | Discovery: `autotunes.edit.edit_autotune_review` with `api_destructive` | | `Get_Autotune_Eligible_Reviewers` | Discovery: `autotunes.list.get_autotune_eligible_reviewers` with `api_read` | | `Get_Autotune_Review_by_ID` | Discovery: `autotunes.get.get_autotune_review_by_id` with `api_read` | | `Get_List_of_Autotune_Reviews` | Discovery: `autotunes.list.get_list_of_autotune_reviews` with `api_read` | | `Reject_Autotune_Review` | Discovery: `autotunes.reject.reject_autotune_review` with `api_destructive` | ### Layers | V1 tool | V3 replacement | | --- | --- | | `Create_Layer` | Discovery: `layers.create.create_layer` with `api_write` | | `Get_Layer_Details_by_ID` | Discovery: `layers.get.get_layer_details_by_id` with `api_read` | | `Get_Layer_Experiments` | Discovery: `layers.list.get_layer_experiments` with `api_read` | | `Get_Layer_Overrides` | Discovery: `layers.list.get_layer_overrides` with `api_read` | | `Get_List_of_Layers` | Discovery: `layers.list.get_list_of_layers` with `api_read` | | `Update_Layer_Entirely` | Discovery: `layers.update.update_layer_entirely` with `api_destructive` | ### Metrics and logs | V1 tool | V3 replacement | | --- | --- | | `Cluster_Log_Patterns` | Discovery: `logs.analyze.cluster_log_patterns` with `api_read` | | `Get_Audit_Logs` | `log_read`, action `get_audit_logs` | | `Get_List_of_Metric_Sources` | `metric_read`, action `get_list_of_metric_sources` | | `Get_List_of_Metrics` | `metric_read`, action `get_list_of_metrics` | | `Get_Metric_Definition_by_ID` | `metric_read`, action `get_metric_definition_by_id` | | `Query_Logs_Explorer` | `log_read`, action `query_logs_explorer` | ### Parameter stores | V1 tool | V3 replacement | | --- | --- | | `Create_Param_Store` | Discovery: `param_stores.create.create_param_store` with `api_write` | | `Delete_Param_Store` | Discovery: `param_stores.delete.delete_param_store` with `api_destructive` | | `Get_List_of_Param_Stores` | Discovery: `param_stores.list.get_list_of_param_stores` with `api_read` | | `Get_Param_Store_Details_by_Id` | Discovery: `param_stores.get.get_param_store_details_by_id` with `api_read` | | `Update_Param_Store` | Discovery: `param_stores.update.update_param_store` with `api_destructive` | ### Prompts | V1 tool | V3 replacement | | --- | --- | | `Create_Prompt` | Discovery: `prompts.create.create_prompt` with `api_write` | | `Create_Prompt_Version` | Discovery: `prompts.create.create_prompt_version` with `api_write` | | `Get_List_of_Prompts` | Discovery: `prompts.list.get_list_of_prompts` with `api_read` | | `Get_Prompt_Details_by_ID` | Discovery: `prompts.get.get_prompt_details_by_id` with `api_read` | | `Start_Prompt_Version_Evals` | Discovery: `prompts.analyze.start_prompt_version_evals` with `api_write` | | `Update_Prompt` | Discovery: `prompts.update.update_prompt` with `api_write` | ### Segments and tags | V1 tool | V3 replacement | | --- | --- | | `Create_Segment` | Discovery: `segments.create.create_segment` with `api_write` | | `Get_List_of_Segments` | Discovery: `segments.list.get_list_of_segments` with `api_read` | | `Get_List_of_Tags` | Discovery: `tags.list.get_list_of_tags` with `api_read` | | `Get_Segment_by_ID` | Discovery: `segments.get.get_segment_by_id` with `api_read` | | `Update_Segment` | Discovery: `segments.update.update_segment` with `api_destructive` | ================================================================================ # Statsig MCP V1 tool reference URL: https://docs.statsig.com/integrations/mcp/v1-tool-reference ================================================================================ # Statsig MCP V1 tool reference This page lists the tools on the Statsig MCP V1 server (`https://api.statsig.com/v1/mcp`). V1 remains supported. For new setups, Statsig recommends [V3](https://docs.statsig.com/integrations/mcp/tool-reference). To move an existing setup, go to [Migrate to Statsig MCP V3](https://docs.statsig.com/integrations/mcp/migrate-to-v3). #### Audit Logs | Tool | Description | | --- | --- | | Get\_Audit\_Logs | List audit logs in the project. Filter by:- `id` - `sortKey` - `sortOrder` - `tags` - `startDate` - `endDate` | #### Dynamic Configs | Tool | Description | | --- | --- | | Create\_Dynamic\_Config | Create new config | | Get\_Dynamic\_Config\_Details\_by\_ID | Retrieve detailed config information | | Get\_List\_of\_Dynamic\_Configs | List all dynamic config objects in the project. Filter by:- `creatorName` - `tags` | | Update\_Dynamic\_Config\_Entirely | Replace entire dynamic config with new targeting and values | | Get\_Dynamic\_Config\_Version\_History | Retrieve the version history for a dynamic config | #### Experiments (A/B Tests) | Tool | Description | | --- | --- | | Create\_Experiment | Create a new experiment. Accepts these optional fields:- `secondaryIDType`: a secondary unit type for the experiment. - `identifierMappingMode`: how Statsig maps identifiers across ID types. - `enabledNonProdEnvironments`: the non-production environments where the experiment runs. - `links`: reference links to attach to the experiment. - `secondaryMetrics`: secondary metrics to track alongside the primary metrics. Set them when you create the experiment, without a separate update call. | | Get\_Experiment\_Details\_by\_ID | Get experiment details. Optionally trim the response to only the fields you need:- `fields`: comma-separated list of field names to return (for example, `hypothesis,primaryMetrics`); omit to return all fields. Reduces context consumption by up to 95–99%. | | Get\_Experiment\_Overall\_Results | Retrieve experiment results/pulse data for a specific experiment. Analyze by:- `date` - `cuped` - `confidence` | | Get\_Experiment\_Metric\_Dimension\_Results | Retrieve metric results for one experiment metric with dimensional breakdowns. Analyze by:- `date` - `cuped` - `confidence` | | Get\_List\_of\_Experiments | List all experiments in the project. Filter by:- `status` - `creatorName` - `tags` - `stale` | | Update\_Experiment\_Entirely | Replace the entire experiment configuration (Statsig removes any excluded data). Accepts the same optional fields as `Create_Experiment`, which keep their current value when you omit them:- `secondaryIDType`: a secondary unit type for the experiment. Pass `null` or an empty string (`""`) to clear it. - `identifierMappingMode`: how Statsig maps identifiers across ID types. - `enabledNonProdEnvironments`: the non-production environments where the experiment runs. - `links`: reference links to attach to the experiment. - `secondaryMetrics`: secondary metrics to track alongside the primary metrics. | | GetExperimentSummaryCharts | Retrieve summary charts for a specific experiment | | Get\_Experiment\_Version\_History | Retrieve the version history for an experiment | | Start\_Experiment\_Code\_Cleanup | Start the code cleanup process for an experiment after it has concluded | #### Autotunes **Create\_Autotune**: Create a new Autotune (multi-armed bandit) experiment. Describe the arms, success event, exploration/attribution windows, and winner threshold; the agent builds and creates the Autotune. Creates in draft by default; start the Autotune from the console to allocate traffic. Prompts for confirmation before creating. #### Gates (Feature Flags) | Tool | Description | | --- | --- | | Create\_Gate | Create new gate/flag | | Get\_Gate\_Details\_by\_ID | Get complete gate configuration details | | Get\_Gate\_Results | Retrieve pulse/results for a specific gate rule.- `cuped` - `confidence` | | Get\_List\_of\_Gates | List all gates/flags. Filter by:- `type` - `creatorName` - `tags` | | Update\_Gate\_Entirely | Replace entire gate setup with new rules and settings (Statsig removes any excluded data) | | Get\_Gate\_Version\_History | Retrieve the version history for a gate | | Start\_Gate\_Code\_Cleanup | Start the code cleanup process for a gate after it has concluded | #### Layers | Tool | Description | | --- | --- | | Create\_Layer | Create a new layer | | Get\_Layer\_Details\_by\_ID | Retrieve layer details, including parameters and metadata | | Get\_List\_of\_Layers | List all layers in the project | | Update\_Layer\_Entirely | Replace the full layer configuration | #### Metrics and Metric Sources | Tool | Description | | --- | --- | | Get\_List\_of\_Metric\_Sources | List all metric sources in the project | | Get\_List\_of\_Metrics | List all metrics in the project. Filter by:- `showHiddenMetrics` - `tags` - `filters` | | Get\_Metric\_Definition\_by\_ID | Get the full definition for a metric, including its type, source, and configuration details | #### Parameter Stores | Tool | Description | | --- | --- | | Get\_List\_of\_Param\_Stores | List all Parameter Stores in the project | | Get\_Param\_Store\_Details\_by\_Id | Retrieve details for a specific Parameter Store by ID | | Create\_Param\_Store | Create a new Parameter Store and its parameters | | Update\_Param\_Store | Update an existing Parameter Store, including adding or changing parameters | | Delete\_Param\_Store | Delete a Parameter Store | #### Segments | Tool | Description | | --- | --- | | Create\_Segment | Create a new segment. Supports `id_list`, `rule_based`, `analysis_list`, and `user_store_id_list` segment types | | Get\_List\_of\_Segments | List all segments in the project | | Get\_Segment\_by\_ID | Retrieve segment details | | Update\_Segment | Update an existing segment. Specifically:- Update rules for conditional segment types - Add IDs to user stores and ID lists | #### Reviews | Tool | Description | | --- | --- | | Create\_Gate\_Review | Create a review request for a gate change | | Edit\_Gate\_Review | Edit an existing gate review request | | Approve\_Gate\_Review | Approve a gate review request | | Reject\_Gate\_Review | Reject a gate review request | | Commit\_Gate\_Review | Commit an approved gate review, applying the change | | Cancel\_Gate\_Review | Cancel a gate review request | | Get\_Gate\_Review\_by\_ID | Retrieve a specific gate review by ID | | Get\_List\_of\_Gate\_Reviews | List all reviews for a gate | | Get\_Gate\_Eligible\_Reviewers | List users eligible to review a gate change | | Create\_Experiment\_Review | Create a review request for an experiment change | | Edit\_Experiment\_Review | Edit an existing experiment review request | | Approve\_Experiment\_Review | Approve an experiment review request | | Reject\_Experiment\_Review | Reject an experiment review request | | Commit\_Experiment\_Review | Commit an approved experiment review, applying the change | | Cancel\_Experiment\_Review | Cancel an experiment review request | | Get\_Experiment\_Review\_by\_ID | Retrieve a specific experiment review by ID | | Get\_List\_of\_Experiment\_Reviews | List all reviews for an experiment | | Get\_Experiment\_Eligible\_Reviewers | List users eligible to review an experiment change | | Create\_Autotune\_Review | Create a review request for an Autotune change | | Edit\_Autotune\_Review | Edit an existing Autotune review request | | Approve\_Autotune\_Review | Approve an Autotune review request | | Reject\_Autotune\_Review | Reject an Autotune review request | | Commit\_Autotune\_Review | Commit an approved Autotune review, applying the change | | Cancel\_Autotune\_Review | Cancel an Autotune review request | | Get\_Autotune\_Review\_by\_ID | Retrieve a specific Autotune review by ID | | Get\_List\_of\_Autotune\_Reviews | List all reviews for an Autotune | | Get\_Autotune\_Eligible\_Reviewers | List users eligible to review an Autotune change | #### Logs and Observability | Tool | Description | | --- | --- | | Query\_Logs\_Explorer | Query the Logs Explorer for raw event data | | Cluster\_Log\_Patterns | Cluster and summarize log patterns to surface recurring events and anomalies | Need other functions? Statsig considers additions by request. Reach out in Slack. ================================================================================ # Docs MCP server URL: https://docs.statsig.com/integrations/mcp/docs-mcp-server ================================================================================ # Docs MCP server Use the Statsig Docs MCP server to let supported AI clients read public Statsig documentation directly from `/api/mcp`. The server is read-only and serves English documentation from this site, so your AI tools answer Statsig questions with current, accurate docs content. This server is separate from the authenticated [Statsig MCP server](https://docs.statsig.com/integrations/mcp/overview), which connects to your project data. The Docs MCP server reads documentation only and needs no API key. ## Supported clients Use a client that supports remote MCP servers over Streamable HTTP and accepts a direct URL. Claude Code, Cursor, and Codex CLI all work. Older MCP clients that only support the deprecated HTTP+SSE transport can't connect to this endpoint. ## Add the server Many MCP clients read a JSON config: ```json { "mcpServers": { "statsig-docs": { "url": "/api/mcp", "transport": "streamable-http" } } } ``` If your client supports command-line setup, add the same URL as a remote HTTP MCP server: ```bash claude mcp add --transport http statsig-docs /api/mcp ``` ## Available tools The server exposes three read-only tools: - `get_page`: Retrieve the full markdown content of a Statsig documentation page. - `list_pages`: List all available documentation pages with their titles and slugs. - `search_docs`: Search documentation pages by keyword. Each tool accepts an optional `rationale` string (max 500 characters) so the model can explain why it called the tool. That value may appear in server usage telemetry when enabled. ## Optional correlation headers MCP clients may send these HTTP headers on each request. The server copies them into usage telemetry when present: - `x-agent-trace-id` - `x-agent-session-id` - `x-mcp-client` (for example, `cursor` or `claude-code`) ## Limitations > **Note:** > > The Docs MCP server is public, read-only, and serves English documentation only. It doesn't require authentication, doesn't expose MCP prompts or resources, and supports Streamable HTTP only. The server rate-limits requests per client. For authenticated access to your project data, like experiments, gates, and metrics, use the [Statsig MCP server](https://docs.statsig.com/integrations/mcp/overview) instead. ## Troubleshooting - If your client reports an unsupported transport, update it to a version that supports remote MCP servers over Streamable HTTP. - If setup fails, confirm that you used the exact endpoint URL: `/api/mcp`. - If you need project data or write access, this server isn't the right endpoint. Use the authenticated [Statsig MCP server](https://docs.statsig.com/integrations/mcp/overview). ================================================================================ # Agent Skills Repository URL: https://docs.statsig.com/integrations/agent-skills ================================================================================ # Agent Skills Repository The [statsig-io/agent-skills](https://github.com/statsig-io/agent-skills) repository contains reusable skill packs for coding agents. Skills are packaged, shareable workflows for repeated tasks, built on the Statsig MCP tools and Console API. These skills build on the open [Agent Skills standard](https://agentskills.io/). ## Available skills | Name | Description | | --- | --- | | `statsig` | Manage Statsig experiments, gates, dynamic configs, segments, layers, and audit logs through the Statsig MCP. | | `statsig-create-cloud-metric` | Draft or execute Statsig Cloud metric creation requests through the Statsig Console API. | | `statsig-dashboard` | Create, read, and update your Statsig dashboards. | ## Install from the repository Install a skill from this repo using the Vercel `skills` CLI: ```bash npx skills add statsig-io/agent-skills ``` You can also: - List installable skills: `npx skills add statsig-io/agent-skills --list` - Install a skill globally for your user: `npx skills add -g statsig-io/agent-skills --skill statsig-dashboard` - Install every skill in this repo: `npx skills add statsig-io/agent-skills --all` After installation, compatible agents can discover each skill from its metadata. ## Requirements - `STATSIG_CONSOLE_API_KEY` for Statsig Console API access - Python 3 if you want to run bundled helper scripts directly ================================================================================ # AI Development with Statsig URL: https://docs.statsig.com/integrations/ai_development_with_statsig ================================================================================ # AI Development with Statsig ## How Statsig supports AI development Developers increasingly use AI agents for small-to-midsized tasks. For small feature additions, such work is low risk but can still introduce bugs or low-quality user experiences. When an agent is aware of Statsig, the agent can automatically add logging for potential errors and add feature gates to new features, or confirm the features are behind existing gates. Feature gates let you manage rollouts safely and measure any degradation. This capability becomes significant given the high velocity individuals can now achieve with AI assistance, including the ability to develop within codebases they have less context in. ## Recommended approach Use an `AGENTS.md` file (or an equivalent file such as `CLAUDE.md`) to provide instructions you can tailor to your workflow. The critical behaviors are: - Adding gates to new features or codepaths, and tuning how aggressively to do so - Automatically adding your user ID, and any test IDs your agent may log in as, to those gates for testing in development - Adding critical logs for errors and user behaviors - Adding these to tracking is manual now, but Statsig has plans to make this automatable through MCP for event count metrics. ### Boilerplate `Agents.md` file Fill in your Statsig ID, and follow the [MCP guide](https://docs.statsig.com/integrations/mcp/overview) to set up the MCP server. Consider updating naming conventions and logic around when to ask. Use a limited-access console API key to reduce the risk of an agent deleting entities in Statsig. ```plaintext # Statsig Development Guidelines It is important that we selectively killswitch new features or any new, risky codepaths using Statsig Feature Gates so that we can turn them off if they cause issues. ## When To Use Gates - We should consider adding a gate whenever we make significant changes to product features that have any risk of causing issues. - It is possible for this to be spammy, so clarify with users during planning what should be killswitched. - Start by assuming atomic, session-level features will be killswitched - e.g. "A new modal" would be, but not a copy change within a modal, or a bugfix. - Sometimes, adding a gate is just as dangerous as the feature itself. - Identify situations where this could occur - usually when adding the gate adds a large amount of complexity - and flag the risk to the user when asking if they want to create a gate. Always ask the user if they want to gate the feature. Often, users will want to include the feature behind an existing gate, so ask in this way, when appropriate: "This seems like a feature that you might want to be able to turn off remotely. Would you like to gate this feature, add it to an existing gate, or proceed without using gates?" Look for gates already being used for this feature type - often in the same file or nearby in the file tree for client code. Don't spend a bunch of time investigating code before asking, since it leads to a lot of hang time. This should be an early step in the process. Quickly check in with the user on gating before you do a deep codebase scan - though you might want to use a quick context check to identify risk. ## How to Use Gates - Create a new gate, if requested, using the statsig-local MCP server. If this server does not exist, ignore the above. - After creation, use that gate in code, following the local codebase patterns for accessing statsig. - This will normally be Statsig.useGate() or similar, but they may have an internal wrapper or use a general feature flag library which wraps Statsig. - When creating the gate, start it with a default-fail rules. The user, or we, can add rules later to release the gate. - Add a rule called "Development" which passes the user's ID, specified below. Make sure this is the first evaluated rule. ## Override instructions - The user's ID is the string "" - Use a custom ID gate condition, with the userID field set to that ID ## Naming Conventions - For these features, create a feature gate which is a 3-4 word description separated by dashes. - Do not use the word killswitch. Propose the name of the gate before creating it, allowing the user to update it if desired. Do not include your name (e.g. codex, claude, cursor) in the gate name. ## Logging - We would like to measure our gate changes as we roll out features. - If there's key interactions in the code which are not logged to Statsig, consider logging those events to statsig - Include critical metadata (e.g. information about what happened, key numeric values) Propose these logging changes to the user and see what they say, and only if they're very clearly needed. Similar to the gate checks, pattern match to what is in the repo already, e.g. Statsig.logEvent or a wrapper like LoggingContext.log() ## Statsig Implementation Instructions [left empty - fill with specific instructions about your Statsig implementation if it exists, such as specific calling patterns or gotchas] ## Guardrails and Critical Rules - In this context, only use this MCP server to create gates - Never run deletions or other destructive tools without explicit instructions from the user ``` ================================================================================ # Github AI Integration URL: https://docs.statsig.com/integrations/github-ai-integration ================================================================================ # Github AI Integration ## How the GitHub AI integration works > **Info:** > > This feature might have rough edges. If you have feedback, share it with the Statsig team. The Statsig GitHub integration links your organization's code repository directly to your Statsig project. Statsig analyzes your codebase and creates a private Knowledge Graph that maps relationships between your codebase and Statsig services such as Feature Gates, Experiments, and Metrics. This integration connects your software development with measurable business impact, delivering contextual insights within Statsig. ![Knowledge Graph diagram showing relationships between codebase and Statsig services](https://docs.statsig.com/images/Knowledge-graph-diagram.png) ### Key features Integrate your code repository to unlock these capabilities: - Locate specific lines of code where you implement a Feature Gate or Experiment - Automatically generate PRs (Pull Requests) to remove stale flags from your code ![An example of Remove from Code in a stale gate banner](https://docs.statsig.com/images/ai-remove-from-code.png) - Understand the intent behind metrics and experiments based on code implementation ![An example of AI description in the right rail of a config](https://docs.statsig.com/images/ai-contextual-description.png) - Write natural language queries to create charts to answer business questions (Coming Soon) ## Why connect your codebase In modern product development, there's often a disconnect between the code you write (hosted on GitHub) and its impact and business outcomes (data in Statsig). The Knowledge Graph bridges this gap by analyzing your connected repositories to provide the context behind every feature. - Context: The Knowledge Graph knows when you log an event or expose a feature to a user. - Intent: The Knowledge Graph understands the purpose and meaning of that event and feature. - Freshness: The Knowledge Graph ensures insights in Statsig reflect the current state of your main branch. ## Installation guide Before you begin, confirm you have Admin permissions in both your Statsig Project and the target GitHub Organization. ### Prerequisites If your organization uses IP restrictions to limit access to your GitHub resources, you must allowlist the IP addresses that Statsig services use to connect to GitHub. Follow the steps in this [GitHub doc](https://docs.github.com/en/enterprise-cloud@latest/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization/managing-allowed-ip-addresses-for-your-organization) to allowlist IP addresses for your organization. ![Configuring IP addresses in your Github Org](https://docs.statsig.com/images/IP-address-github-app.png) If you choose to manually add IP addresses, go to [Statsig IP ranges](https://docs.statsig.com/infrastructure/statsig_ip_ranges#statsig-ip-ranges). ### First-time installation If you're connecting GitHub to Statsig for the first time: 1. Navigate to **Settings** → **Integrations** in the Statsig console. 2. Locate and select the **Statsig GitHub App** card. 3. Select **Enable Connection**. 4. Statsig redirects you to GitHub. Authenticate and select the target Organization and Repositories. 5. After authorization, Statsig redirects you back to confirm the connection. > **Info:** > > You can install the app on specific repositories or your entire organization. For the best results with Knowledge Graph, select all relevant repositories containing feature code. ### Connecting additional projects GitHub allows you to install a specific GitHub App only once per GitHub Organization. If you have multiple Statsig Projects (for example, "Project 1" and "Project 2") that need access to the same GitHub Org, they share the underlying connection. To link a new project to an existing GitHub connection: 1. Navigate to **Settings** → **Integrations** in the Statsig console. 2. Locate and select the **Statsig GitHub App** card. Statsig indicates if an existing connection exists for any other project. 3. Select the Statsig Project you want to inherit the connection from. 4. Confirm the link. ### Migrating from legacy (PAT) integration If you're using the older Personal Access Token (PAT) integration, upgrade to the GitHub App for improved security and functionality. 1. Navigate to **Settings** → **Integrations** in the Statsig console. 2. Locate and select the **Statsig GitHub App** card. 3. A banner on the GitHub integration card prompts you to upgrade from the PAT-based connection. 4. Follow the flow to install the GitHub App on your repositories. 5. After you install the app, the system automatically deprecates the old PAT connection. ## Statsig GitHub integration FAQs 1. **Does Statsig use my data to train LLM models?** Statsig doesn't use your data to train LLM models, and neither do its sub-processors. Statsig secures your data to your organization and uses it to improve the services it provides to you. 2. **Does Statsig store my source code?** Statsig doesn't permanently store your source code. Statsig temporarily processes code to extract metadata and embeddings to create the Knowledge Graph, then discards it when no longer necessary. 3. **How long does it take for the code insights to appear in Statsig?** Setting up the integration can take up to a few hours depending on the size of the repository. After the initial setup, Statsig indexes new data every 7 days. 4. **What security controls apply?** Go to [Statsig security practices](https://www.statsig.com/trust/security) for security information. Go to [AI governance](https://docs.statsig.com/compliance/ai_governance_security_privacy) for AI governance information. ================================================================================ # Control Panel URL: https://docs.statsig.com/control-panel/overview ================================================================================ # Control Panel Control Panel is a surface for tracking and managing the features you and your teams deploy with Statsig, similar to the standard gate and experiment tables. From Control Panel you switch between filters on configs, experiments, and gates; measure results; make or review ship decisions; and manage development flows such as overrides. ## Using Control Panel - Configure sections in the left column to specify different filters and display settings, such as "My Changes" or "My Team's Changes". - View results inline. Configs and experiments show a summary of metric movements. Hover to see a table of all observed metric movements. You can open Gates and Dynamic Configs to see results per rule. - Manage configs. View or set your override status from Control Panel, and end features if unexpected behavior occurs. ================================================================================ # Metrics User Guide URL: https://docs.statsig.com/metrics/introduction ================================================================================ # Metrics User Guide ## Metrics user guide Statsig combines data from your existing data sources to give you a complete view of your product metrics and the impact new features and experiments have on those metrics. Statsig automatically creates metrics from the **raw events** that you log from your application, as well as raw and transformed events you send to Statsig through a data collector. Statsig can also reuse your existing **precomputed metrics** by natively integrating and pulling data from your cloud data warehouse. You can also ingest metrics into Statsig using an HTTP endpoint or Azure Blob storage. ![Data integration architecture diagram](https://docs.statsig.com/images/metrics/introduction/200041707-e6cc4f1e-7ec4-4044-8afe-e877964eb2dc.png) The **Metrics User Guide** consists of [Metrics 101](https://docs.statsig.com/metrics/101), [201](https://docs.statsig.com/metrics/201), and [301](https://docs.statsig.com/metrics/301) level guides that step through basic concepts to real-time analytics in Statsig. ## Metrics 101 - An overview - [Introduction](https://docs.statsig.com/metrics/101) - [Raw Events](https://docs.statsig.com/metrics/raw-events) - [Raw Event Metrics](https://docs.statsig.com/metrics/raw-event-metrics) - [Custom Metrics](https://docs.statsig.com/metrics/custom-metrics) - [Precomputed Metrics](https://docs.statsig.com/metrics/precomputed-metrics) - [Pulse Metrics](https://docs.statsig.com/metrics/pulse) - [Metric Dimensions](https://docs.statsig.com/metrics/metric-dimensions) ## Metrics 201 - Diving deeper - [Introduction](https://docs.statsig.com/metrics/201) - [Creating Metrics](https://docs.statsig.com/metrics/create) - [Tagging Metrics](https://docs.statsig.com/metrics/create-metric-tags) - [User Metrics](https://docs.statsig.com/metrics/user) - [Assignment ID != Analysis ID](https://docs.statsig.com/metrics/different-id) ## Metrics 301 - Advanced topics - [Introduction](https://docs.statsig.com/metrics/301) - [Metrics Explorer](https://docs.statsig.com/product-analytics/overview) - [User Funnels](https://docs.statsig.com/metrics/create-user-funnels) - [User Flows](https://docs.statsig.com/metrics/create-user-flows) Statsig combines product experimentation with real-time analytics to support **product observability**. ![Product observability dashboard overview](https://docs.statsig.com/images/metrics/introduction/182259790-b898161f-6657-4d52-8367-f3bdeb8d6037.png) To get started, go to [Metrics 101](https://docs.statsig.com/metrics/101). ================================================================================ # Metrics Overview URL: https://docs.statsig.com/metrics/101 ================================================================================ # Metrics Overview > **Info:** > > **Warehouse Native users**: You're viewing the Cloud docs for this page. Metrics and experiments behave differently in Warehouse Native. Read more in [Data & Semantic Layer in Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/configuration/data-and-semantic-layer). Statsig metrics measure how users interact with your product and form the basis for experiment analysis. Set up your essential product metrics by working through these core concepts: 1. [How Metrics Work on Statsig](https://docs.statsig.com/metrics/how-metrics-work) 2. [Raw Events](https://docs.statsig.com/metrics/raw-events) - [Types of Raw Events](https://docs.statsig.com/metrics/raw-events#types-of-raw-events) - [Unit Identifiers](https://docs.statsig.com/metrics/raw-events#unit-identifiers) required for raw events - [ID Mapping Considerations](https://docs.statsig.com/experiments/create-new#id-mapping-capabilities) for cross-ID analysis - [Ingesting Raw Events](https://docs.statsig.com/metrics/raw-events#ingesting-raw-events) - [Seeing Raw Events in the Statsig Console](https://docs.statsig.com/metrics/raw-events#raw-events-in-console) 3. [Auto-generated Events](https://docs.statsig.com/metrics/raw-event-metrics) - [Event Count](https://docs.statsig.com/metrics/raw-event-metrics#event-count-metric) and [Event DAU](https://docs.statsig.com/metrics/raw-event-metrics#event-dau-metric) metrics - [User Accounting](https://docs.statsig.com/metrics/raw-event-metrics#user-accounting-metrics) 4. [Custom Metrics](https://docs.statsig.com/metrics/custom-metrics) 5. [Importing Precomputed Metrics](https://docs.statsig.com/metrics/precomputed-metrics) 6. [Pulse Metrics](https://docs.statsig.com/metrics/pulse) > **Info:** > > **Ask for Help**: Join the [Statsig Slack channel](https://statsig.com/slack) if you have any questions or want to validate the best path to import your metrics. ================================================================================ # How Metrics Work on Statsig URL: https://docs.statsig.com/metrics/how-metrics-work ================================================================================ # How Metrics Work on Statsig ## How metrics work on Statsig A metric in Statsig is a numeric value that Statsig tracks for each user on a given day. You aggregate this value across your entire user base or a subset, such as the test or control group of an experiment, to measure how your product performs. Statsig's Stats Engine joins these metrics with your exposure events to compute experiment results and analytics. > **Info:** > > **Warehouse Native users** > > : You're viewing the Cloud docs for this page. Metrics and experiments behave differently in Warehouse Native. Read more in [About Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction#how-warehouse-native-works). For example, say one user made two purchases on September 1st, and another made only one. You can aggregate these values across multiple users to calculate the total number of purchases across all users on September 1st. By default, Statsig computes metrics from logged raw events in the production environment. When testing experiments in lower environments (such as development or staging) with **Enable for Environments**, you can track cumulative exposures and metric results from those environments. Tracking lower-environment data lets you validate your experiment setup before launching to production. Statsig prioritizes production data for final _Pulse_ result analyses. ## Sources of Statsig metrics There are two fundamental sources of metrics in Statsig: 1. **Raw Events** - Statsig [auto-generates certain metrics](https://docs.statsig.com/metrics/raw-event-metrics) such as **event\_count** and user accounting metrics from these events. - You can also define [custom metrics](https://docs.statsig.com/metrics/create) using your logged raw events. 2. **Precomputed Metrics**: You can provide these pre-computed values to Statsig. Statsig's Stats Engine joins these metrics with your exposure events from feature gates and experiments to compute experiment results and analytics. ![Statsig data flow architecture diagram](https://docs.statsig.com/images/data_flow_cloud.png) > **Info:** > > **How does Statsig bill events and metrics?** > > Statsig bills each event (or a row when importing from your data warehouse) once, regardless of how many experiments use the event. ## Delayed and backfilled data Statsig Cloud computes metrics once per day, using the raw events ingested by the time that day's computation runs. If events for a given day arrive after that day's computation has already run, Statsig doesn't automatically include them in the already-computed metric value. Statsig doesn't update the stored metric for that day to reflect late-arriving data. > **Warning:** > > **Send events on the day they occur** > > Statsig computes metrics once per day. Events that arrive after that day's computation has already run are not included in the metric for that day. To ensure events are picked up by metric computation, send them on the same calendar day they occur. To get the most accurate metric results, send events as close to when they occur as possible. Use timestamps that reflect the actual event time. Don't stamp events with a past date or time when ingesting them. Reprocessing or backfilling delayed data isn't a standard Cloud capability. Enterprise customers using specific import-based ingestion setups have more flexibility to retrigger computation for affected days. Contact your account team to learn whether this applies to your setup. This behavior applies to Statsig Cloud. Warehouse Native handles data timing differently; refer to [About Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/introduction#how-warehouse-native-works) for details. ================================================================================ # Raw Events URL: https://docs.statsig.com/metrics/raw-events ================================================================================ # Raw Events Statsig uses the raw events emitted by your application to compute a wide range of product metrics. These events contain the context needed to understand user behavior and infer user intentions. ## Types of raw events Statsig records two types of raw events from your application: 1. **Exposure events** track which users Statsig assigns to control and test groups. This exposure data allows Statsig to generate test results so you can evaluate the impact of new features and experiments. Exposure events also allow Statsig to assess the health of an experiment so you can make key decisions based on trustworthy data. Statsig requires exposure events at a minimum to generate experiment results. 2. **Custom events** track user actions and any events triggered during use of your application, including events that capture performance (for example, latency) or analytics data (for example, session start). These events allow Statsig to assess overall user engagement in your application, such as daily active users and weekly stickiness. These events also reveal changes in user behavior as you roll out new features and experiments. > **Note:** > > When logging custom events, avoid using dot (.) notation in metadata keys. Statsig interprets keys containing dots as nested paths during JSON parsing (e.g., by JSON\_VALUE), which can cause the values to parse as NULL. ## Unit identifiers You must include at least one unit identifier when you record any raw events with Statsig. Statsig requires the unit identifier for two reasons: 1. To ensure that your users receive a consistent application experience when allocated to control or test groups in an experiment 2. To join exposure events with all custom events triggered by a given user to compute experiment results ## Ingesting raw events You can send raw events into Statsig in three ways. ![Raw events ingestion methods diagram](https://docs.statsig.com/images/metrics/raw-events/182466148-a40ad007-a60a-47b8-9cd3-9b27d0af82ed.png) 1. Integrate with Statsig's [client](https://docs.statsig.com/client/introduction) or [server](https://docs.statsig.com/server/introduction) SDKs or [HTTP](https://docs.statsig.com/http-api/overview) API 2. Set up Statsig as a destination in a data connector such as [Segment](https://docs.statsig.com/integrations/data-connectors/segment#configuring-incoming-events), [mParticle](https://docs.statsig.com/integrations/data-connectors/mparticle#configuring-incoming-events), [RudderStack](https://docs.statsig.com/integrations/data-connectors/rudderstack#configuring-incoming-events) and [Census](https://docs.statsig.com/integrations/data-connectors/census#configuring-incoming-events) 3. Import from your data warehouse such as [Snowflake](https://docs.statsig.com/integrations/data-imports/snowflake#direct-ingestion-from-snowflake), [BigQuery](https://docs.statsig.com/integrations/data-imports/bigquery), and [Redshift](https://docs.statsig.com/integrations/data-imports/redshift#direct-ingestion). > **Note:** > > When processing events, Statsig drops event names that contain this regex/character set: > > `"\\[\]{}<>#=;&$%|\u0000\n\r` ## Raw events in console As you ingest custom events, they appear in the _Metrics_ section under the **Events** tab in the Statsig console. ![Events tab list view showing recent custom events](https://docs.statsig.com/images/metrics/console/172451019-fc450842-a546-4ea0-94a9-d54df8279ed2.png) You can toggle between a list view or chart view of your events to view the trend line over time. ![Chart view of events showing trend line over time](https://docs.statsig.com/images/metrics/console/172461387-a3d42641-2c2c-4128-aabc-fc2b5dba2ed9.png) Statsig provides two unit identifiers by default: **User ID** and **Stable ID**. Select a unit identifier from the dropdown to view all events that include that unit identifier. Go to the [guide to create custom ID types](https://docs.statsig.com/guides/experiment-on-custom-id-types#step-1---add-companyid-as-a-new-id-type-in-your-project-settings) to create additional unit identifiers for your project. ![Unit identifier dropdown for filtering events by user or stable ID](https://docs.statsig.com/images/metrics/console/172450890-4a4c95eb-a362-49a6-90ad-68f3460a933f.png) ## Billing Statsig bills for the two types of raw events described above. Statsig bills only for production environment events. 1. Statsig records an **Exposure Event** for billing when you check a user for assignment in a Feature Gate or Experiment, or check for a value using a Dynamic Config. Statsig doesn't bill the following checks: - Statsig doesn't bill you for duplicate checks for the same user on the same Feature Gate, Experiment, or Dynamic Config within an hour. - Statsig doesn't bill you for checks against Features Gates that are disabled. - Statsig also doesn't bill you for checks for users who are in not participating in an experiment due to the allocation or targeting you have configured. 2. Statsig records a **Custom Event** for billing when you log an event using the Statsig SDK (or import from your data warehouse, or ingest from your data collector). Each event may contain multiple unit identifiers and can appear in multiple experiments. - Statsig bills custom events only once, regardless of how many experiments use them. ================================================================================ # Auto-generated Metrics URL: https://docs.statsig.com/metrics/raw-event-metrics ================================================================================ # Auto-generated Metrics Auto-generated metrics are metrics that Statsig creates automatically from the events you log, with no configuration required. They track the health and usage of your product and the impact of new features and experiments. Statsig automatically generates an "event\_count" metric for each uniquely named **custom event** that you log. Statsig creates auto-generated metrics from production environment events, and creates an event\_count metric for any newly logged custom event within 24 hours of the first logged events. When testing experiments in lower environments (such as development or staging) with **Enable for Environments**, you can track cumulative exposures and metric results collected from those environments. Tracking these results lets you validate your experiment setup before launching to production. Statsig prioritizes production data for final Pulse result analyses. This auto-generated metric consists of three elements: 1. **Roll-up Window** - Statsig computes metrics from custom events aggregated over a 24-hour day, with the hours depending on your company's setting. These hours don't change with daylight saving time. This prevents some days from having 23 and 25 hours which can cause a +/-4% change to some metrics on a biannual basis. 2. **Unit Identifier** - You can record custom events with or without a unique user identifier. However, Statsig requires a unit identifier (usually a user\_id) to track a user across multiple events and sessions, which supports Experiments, Pulse (experiment results), and Autotune. If you don't have access to a user\_id when logging a custom event, create a temporary identifier to track users at a session or device-level. 3. **Metric Value** - Statsig automatically computes values for **event\_count**, which measures the number of times an event is triggered. Through October 16, 2024, Statsig also auto-computed values for an **event\_dau** metric that measures the number of unique users who triggered the event. Statsig no longer auto-computes an **event\_dau** metric for every logged event. You can create metrics that function like **event\_dau** through [Custom Metrics](https://docs.statsig.com/metrics/custom-dau). Go to the [event\_dau deprecation details](https://docs.statsig.com/metrics/deprecate-event-dau) for more information. | Metric | Automatic | Dimensions | Possible Values | Description | Example | | --- | --- | --- | --- | --- | --- | | event\_count | Yes | Yes | 0, 1, 2,... | Counts the number of events triggered on a given day | Number of page views | | event\_dau (Legacy support as of October 16, 2024) | Yes | Yes | 0, 1 | Marks each user as 1 or 0 based on whether they triggered the event or not | Unique users who viewed a page | When you select an event type in the **Events** tab, a detailed view of the event appears, including any metrics linked to that event. Select a metric to go to its detail page. ![Event metrics dashboard view](https://docs.statsig.com/images/metrics/raw-event-metrics/e4967643-33b4-46b6-9fca-5cee83f8f0a6.png) ## Event count metric Event count is the simplest metric in your Statsig project. For every event recorded, Statsig automatically creates an **event\_count** metric based on the number of times Statsig receives that event each day. In experiments, Statsig calculates this value for each user. Each user can have values of 0, 1, 2, and so on. You can find an **event\_count** metric for each event type that you record in the Statsig console. The metric name matches the name of the raw event, and Statsig marks the metric type as **event\_count**. ![Event count metric configuration interface](https://docs.statsig.com/images/metrics/raw-event-metrics/4b7b30d6-d14d-4430-81a5-4fc467d466d2.png) ## User accounting metrics Statsig automatically derives **User Accounting** metrics based on qualifying events logged by the Statsig SDK for a user on a given day. **User Accounting** metrics start with a definition of a daily active user (DAU). By default, Statsig considers a user a DAU if the Statsig SDK logs any qualifying event for them on a given day. Qualifying events are custom log events and Statsig SDK autocapture events. Gate checks and experiment checks (exposure events) are not counted toward DAU. Project Admins can narrow or widen the set of qualifying log events under **Project Settings > Active User Definition**. | Metric | Automatic | Dimensions | Possible Values | Description | Example | | --- | --- | --- | --- | --- | --- | | user | Yes | No | Depends on specific metric | Counts users that have at least one qualifying custom or autocapture event on a given day | Daily Active Users | Like the **event\_dau** metric (deprecated as of October 16, 2024), Statsig computes **User Accounting Metrics** for each unit ID you define in your Statsig project. For example, given User IDs, DAU counts the number of distinct users that triggered the event. Given Stable IDs, DAU counts the number of distinct devices running your application. Go to [User Accounting Metrics](https://docs.statsig.com/metrics/user) for the full list of user accounting metrics and information about customizing the DAU definition. Statsig's default day starts at GMT-8 (Pacific Standard Time), and doesn't follow daylight savings time. > **Note:** > > Auto-generated **User Accounting Metrics** aren't supported for data warehouse ingestions. ## Metrics catalog The **Metrics Catalog** tab allows you to search and tag your metrics. Tags organize metrics into collections. For example, you can tag metrics focused on a product area, business function, or business objective. You can also create a guardrail metrics collection that teams add to every experiment to confirm there are no unexpected effects in other parts of the business. After you create a tagged collection, you can filter to that set when viewing experiment results. ![Metrics catalog interface](https://docs.statsig.com/images/metrics/raw-event-metrics/d22ff8d2-5aea-42b4-86e0-126c25678e15.png) ## Event DAU metric (legacy support only) > **Warning:** > > Refer to the deprecation notice above. Like **event\_count**, Statsig formerly created an **event\_dau** metric that measures the number of unique users who trigger a specific event on a given day. Each user receives a value of 1 (active) or 0 (inactive) based on whether they triggered an event on that day. An **event\_dau** metric produces a single value per user per day. When Statsig aggregates the **event\_dau** metric across users for the duration of an experiment, the result is the "Event Participation Rate," which represents the probability that a unit is DAU for that event. **event\_dau** metrics are always between 0 and 1 for a user, because Statsig computes them as "# Days with the Event" / "# Days Being Considered". > **Info:** > > **Tip** > > : Sometimes you might want a metric similar to **event\_dau** but not normalized by a number of days. If you're looking for a metric that measures if the user has an event over the entire duration of the experiment, try a custom metric set to metric type "Unit Count" with "One-Time Event" rollup mode. This metric works well in experimentation as it minimizes outliers, has tighter confidence intervals, and enables a simple measure to describe a user's breadth of activity across different events. Statsig computes the **event\_dau** for each unit ID you define in your Statsig project. For example, given User IDs, **event\_dau** counts the number of distinct users that triggered the event. Given Stable IDs, **event\_dau** counts the number of distinct devices using your application. You can find an **event\_dau** metric for each event type that you record with Statsig. The metric name matches the name of the raw event, and Statsig marks the metric type as **event\_dau**. ![Event DAU metric configuration interface](https://docs.statsig.com/images/metrics/raw-event-metrics/008034e9-cce8-4e6f-bce1-84a789ac4a19.png) ================================================================================ # Deprecating Event_dau Metric URL: https://docs.statsig.com/metrics/deprecate-event-dau ================================================================================ # Deprecating Event_dau Metric ### Deprecation details From Wednesday, October 16, 2024, Statsig stopped auto-generating new event\_dau metrics for incoming events. Statsig continues to auto-generate an event\_count metric for each logged event. > **Note:** > > This change only affects Statsig Cloud customers. This change doesn't affect Warehouse Native customers. - This change doesn't affect any existing event\_dau metrics that you have used in a gate, experiment, dashboard, or other Custom Metrics. - Existing event\_dau metrics that you archived or never used in another config no longer exist. To retain these metrics, refer to the Next steps section below. - Going forward, you must create new event\_dau metrics manually as a Custom Metric. Refer to [this guide](https://docs.statsig.com/metrics/custom-dau) to learn how to create a DAU metric. Contact Statsig support if you have questions or concerns about this change. ### Motivation for this change Historically, Statsig auto-generated an event\_count and event\_dau metric for every incoming event. Auto-generating two metrics for every event causes confusion and clutter inside projects. The deprecation produces a cleaner Metrics Catalog and faster Console performance, while retaining the ability to create event\_dau metrics for specific events. ### Next steps To keep any unused event\_dau metrics, mark them as active by performing any of the actions below: - Adding a Tag (RECOMMENDED) - Adding a description - Referencing in a gate/experiment/dashboard These actions mark your unused metric as active, indicating that Statsig shouldn't deprecate the metric. ================================================================================ # Custom Metrics URL: https://docs.statsig.com/metrics/custom-metrics ================================================================================ # Custom Metrics ## Custom metrics You can create **Custom Metrics** using the custom events you ingest by filtering or aggregating events based on event metadata. Include metadata along with the custom events when you log these events with Statsig. For example, you might track overall **event\_count** for all events of type _purchase\_event_. You might also filter these metrics to only the events where users purchase a specific product category. Statsig supports six types of custom metrics: | Metric Type | Description | Examples | | --- | --- | --- | | Event Count | **Total count of events** filtered by the _Value_, _Metadata_, or _User_ properties of an event type | **Add to Cart** event filtered by category type | | User Count | **Number of unique users** that trigger events filtered by the _Value_, _Metadata_, or _User_ properties of an event type | **Active Users** based on their views of a product category | | Aggregation | **Sum or Average** of the _Value_, _Metadata_, or _User_ property of an event type | **Total Revenue** | | Ratio | **Rates** (e.g. cart conversion rate, purchase rate), **Normalized Values** (e.g. sessions per user, items per cart) | **Cart Conversion Rate**, **Sessions per User** | | Funnel | **Funnels**- funnel of multiple events with conversion tracking | **Sign-up Funnel**, **Checkout Funnel** | | Count Distinct | **Count Distinct**- Number of unique values for a given field, often approximated with sketches | **Unique Songs** listened per user | > **Info:** > > Sketch-based count distinct metrics are in Early Access. Reach out to Statsig Support to request access. The "average" in aggregation is the average of event value (average revenue per purchase per user), not the average of exposed units (average revenue per user). Sum defines the average revenue per user. Refer to the **Metrics 201** topic, [Creating Custom Metrics](https://docs.statsig.com/metrics/create), to learn how to create custom metrics for your product. ================================================================================ # Precomputed Metrics URL: https://docs.statsig.com/metrics/precomputed-metrics ================================================================================ # Precomputed Metrics ## Importing precomputed metrics ### Importing precomputed metrics from your data warehouse Statsig integrates natively with cloud data warehouses such as [Snowflake](https://docs.statsig.com/data-warehouse-ingestion/snowflake), [BigQuery](https://docs.statsig.com/data-warehouse-ingestion/bigquery), and [Redshift](https://docs.statsig.com/data-warehouse-ingestion/redshift) to ingest your existing metrics for computing experiment results. Go to [Data Warehouse Ingestion](https://docs.statsig.com/data-warehouse-ingestion/introduction) to get started. ## Debugging precomputed metrics Statsig creates a metric detail page for all precomputed metrics imported from your data warehouse. These metric detail pages take a few hours to generate after import or ingestion. The fastest way to start viewing and debugging your precomputed metrics is through the **Metrics Logstream** in the **Metrics Catalog** tab within **Metrics**. ![Metrics logstream showing imported precomputed metrics](https://docs.statsig.com/images/metrics/ingest/178854882-730ef0d5-8eb2-4344-88ab-33111301e712.png) The **Metrics Stream** surfaces all ingested, precomputed metrics in real time, enabling you to check metric name, metric value, unit identifier, ID type, and ingestion date. > **Info:** > > **Tip** > > : A common issue is ensuring that precomputed metrics have the correct ID type. Pay extra attention to this column. The **Metrics Stream** only appears if you're actively ingesting precomputed metrics. If it doesn't appear at the bottom of your **Metrics Catalog**, Statsig likely isn't receiving your precomputed metrics due to a connection issue or an invalid schema. ================================================================================ # User Property URL: https://docs.statsig.com/metrics/user-property ================================================================================ # User Property You can break down Pulse results by user properties, such as Free vs Paid or OS type, to slice your data by those properties. You set user properties when you create the User object used with the Statsig SDK. Statsig freezes these properties when it first exposes a user to a feature gate or experiment, because the experiment may change those properties (for example, converting a Free user to Paid). ![User property configuration interface](https://docs.statsig.com/images/metrics/user-property/226679274-01705500-48ee-44d4-8a5c-cbc49d97d0b2.png) You can run custom queries on your Pulse results in the **Explore** tab to group by or filter by user properties. ![Pulse results custom query interface](https://docs.statsig.com/images/metrics/user-property/226679816-5c7d393f-80e2-4670-8978-fc607b5fbe1a.png) ================================================================================ # Event Property URL: https://docs.statsig.com/metrics/metric-dimensions ================================================================================ # Event Property Statsig enables you to break down metrics into a single set of non-overlapping dimensions for detailed analysis. For example, you can break down an event such as **add-to-cart** into product categories such as _sports_, _toys_, _appliances_, _electronics_. To do this, log **add-to-cart** events and provide the product category in the event's **value** field. Refer to the [Statsig SDK reference guide](https://docs.statsig.com/client/javascript-sdk#event-logging) to learn more. Statsig enables you to define up to four custom dimensions for an event (one through the **value** field and three through **metadata** fields). If you need additional metadata fields, contact your account team. To configure these custom event fields, go to _Metrics > Events_, select the event you want to configure, and then go to the **Setup** tab for that event. ![Event property configuration](https://docs.statsig.com/images/metrics/metric-dimensions/209886245-c26f569b-a4d4-4882-9d9c-f65f3c1ba43b.png) When you provide custom dimensions with logged events, you can break down the impact on the total **add-to-cart** events by category in Pulse. This breakdown lets you identify the category most impacted by your experiment. ![Pulse results breakdown by product category](https://docs.statsig.com/images/metrics/metric-dimensions/162332284-259ea614-8cb6-4c9d-aebd-3e41f9092a64.png) Statsig recommends keeping the number of distinct dimensions in your logging below 8. Tracking dimensions involves additional computational and storage resources, so Statsig prioritizes notable dimensions that make up a significant portion of your traffic. Statsig tracks dimensions that make up more than 5% of your total event volume. Lower-frequency dimensions generally have more statistical noise and wider confidence intervals, and Statsig buckets these as "Other". Statsig also supports metric dimensions for custom metrics that are **Aggregations**. To set this up, log your dimension as a **value** and the number to tally as a metadata field. This is the old metric dimension page. Statsig renamed it to Event Property. ================================================================================ # Ingesting Metrics URL: https://docs.statsig.com/metrics/ingest ================================================================================ # Ingesting Metrics Statsig can ingest your precomputed product and business metrics using the data warehouse connector (Metrics Imports). Statsig supports integrations with [Snowflake](https://docs.statsig.com/integrations/data-imports/snowflake), [BigQuery](https://docs.statsig.com/integrations/data-imports/bigquery), and [Redshift](https://docs.statsig.com/integrations/data-imports/redshift). Statsig doesn't automatically process these metrics until you mark them as ready, because you might load data out of order. After you finish loading data for a period, mark the data as ready by calling the `mark_data_ready` API. ```plaintext curl --location --request POST ‘https://api.statsig.com/v1/mark_data_ready’ \ --header ‘statsig-api-key: {your statsig server secret}’ \ --header ‘Content-Type: application/json’ \ --data-raw ‘{ “timestamp”: 1647975283, “type”: “metrics” } ``` The timestamp provided should be: - A unix timestamp - The latest point in time for which you've uploaded all metrics Any future calls to this API with an earlier timestamp are invalid. Statsig doesn't guarantee correct behavior if you provide metrics with an earlier timestamp after calling this API. Statsig processes metrics as a full day in the PST timezone, and waits until you mark a full day as ready before processing that day. ## Debugging precomputed metrics All precomputed metrics generate Metric Detail View pages. These Detail View pages take a few hours to generate after ingestion. The fastest way to start viewing and debugging your precomputed metrics is through the **Metrics Logstream** on the **Metrics Catalog** tab within **Metrics**. ![Metrics catalog displaying logstream entries for ingested metrics](https://docs.statsig.com/images/metrics/ingest/178854882-730ef0d5-8eb2-4344-88ab-33111301e712.png) The **Metrics Logstream** surfaces all ingested, precomputed metrics in real time, enabling you to check metric name, value, ID, ID type, and ingestion date. A common issue is ensuring precomputed metrics have the correct ID type, so pay extra attention to this column. You can also include test metrics tagged with **isTest**, which you can toggle on or off for debugging in the **Metrics Logstream**. The **isTest** flag works only for precomputed metrics ingested through Statsig's APIs. Support for this flag through integrations with Snowflake, BigQuery, and Redshift is coming soon. To mark a batch of metrics as test metrics, set the `isTest` parameter to `true` in the request data, as shown below. ```bash curl \ “https://events.statsigapi.net/v1/log_custom_metric” \ --header “statsig-api-key: <YOUR-SDK-KEY>” \ --header “Content-Type: application/json” \ --request POST \ --data “{"isTest": true, “metrics": [{"user_id": "1237", "metric_name": "test_metric", "id_type": "user_id", "metric_value": 90}, {"user_id": "4568", "metric_name": "ratio", "id_type": "stable_id", "numerator": 3, "denominator": 15}]}” ``` ![Metrics logstream UI showing isTest flag toggle](https://docs.statsig.com/images/metrics/ingest/179048336-ebdde45b-17e7-47ad-bb81-01f8f032b978.png) The **Metrics Logstream** only appears if you're actively ingesting precomputed metrics. If it doesn't appear at the bottom of your **Metrics Catalog**, a connection or schema issue may be preventing Statsig from receiving your precomputed metrics. ================================================================================ # Pulse Metrics URL: https://docs.statsig.com/metrics/pulse ================================================================================ # Pulse Metrics Experiments with Statsig use **Pulse** to compute and communicate results. The metric type affects how Statsig computes and interprets the final result. Statsig aggregates most metric types across all users in the group. For metric types that use ratios, Statsig aggregates only across [participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) (users that have a non-null value for that metric). This article covers the metric types available in experiments and how to interpret their Pulse results. ## Pulse statistics by metric type | Metric Type | Total | Mean | Units | | --- | --- | --- | --- | | event\_count | Sum of events (99.9% winsorization applied) | Average events per user (99.9% winsorization applied) | All users | | event\_dau | Sum of event DAU (distinct user-day pairs) | Average event\_dau value per user per day. Statsig calls this the "Event Participation Rate" because it represents the probability a user is DAU for that event. | All users | | sum | Total sum of values (99.9% winsorization) | Average value per user (99.9% winsorization) | All users | | mean | Overall mean value | Overall mean value | [Participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) | | event\_user | Count of distinct users that have had the event. | Average metric value per user per day. Depending on Rollup Mode, can be a one-time event or daily participation rate. | All users | | ratio | Not shown | Overall ratio: sum(numerator values)/sum(denominator values) | [Participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) | | funnel | Not shown | Overall ratio: sum(numerator values)/sum(denominator values) | [Participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) | | user: dau, wau, mau\_28day | Not shown | Average metric value per user per day. The probability that a user is xAU | All users | | user: new\_dau, new\_wau, new\_mau\_28day | Count of distinct users that are new xAU at some point in the experiment | Fraction of users that are new xAU | All users | | user: retention metrics | Overall average retention rate | Overall average retention rate | [Participating users](https://docs.statsig.com/experiments/interpreting-results/participating-units) | | user: L7, L14, L28 | Not shown | Average L-ness value per user per day | All users | | count\_distinct | Total number of unique values | Average number of unique values per user | All users | **Some example metric breakdowns in Pulse:** ![pulse 1](https://docs.statsig.com/images/metrics/pulse/aa7e1063-6473-4e4e-9ca4-7074f5a0c450.png) ![pulse 2](https://docs.statsig.com/images/metrics/pulse/7b0b1d99-c720-480e-8671-f5f696485500.png) ## Event count and event DAU in Pulse > **Warning:** > > **event\_dau Legacy Support** > > : event\_dau metrics are now in legacy support only, and Statsig no longer creates them for new events. Existing event\_dau metrics remain available for any of your new experiments, and Statsig continues to compute them daily. For all new events, you should create an event\_user metric to measure daily active users. From [Metrics 101](https://docs.statsig.com/metrics/101) and [Auto-generated Metrics](https://docs.statsig.com/metrics/raw-event-metrics), - [**event\_count**](https://docs.statsig.com/metrics/raw-event-metrics#event-count-metric) measures the volume of the activity based on count of events triggered - [**event\_dau**](https://docs.statsig.com/metrics/raw-event-metrics#event-dau-metric) measures unique daily users who triggered a given event For example, the table below shows the **event\_count** and **event\_dau** metrics for two event types, _Page Views_ and _Add to Cart_, for three users over three days. ![Event count and event DAU metrics table](https://docs.statsig.com/images/metrics/pulse/187719553-c7e5c186-5dfe-4521-8bfb-1bb4b8cdb38d.png) Over the duration of an experiment, Pulse results measure the change in: - the **mean** event\_count, or the average event count per user - the **mean** event\_dau, or average active days per user: Statsig calls this the **Daily Event Participation Rate** For example, the table below shows the **Total event\_count**, **Total Units**, and **Mean event\_count** over the same three days as above, now in the context of an experiment. ![Experiment metrics table showing total event count and mean values](https://docs.statsig.com/images/metrics/pulse/187721781-3240ebc6-43ae-4fd8-ac44-c3493308e127.png) The table below shows the **Total event\_dau**, **Total Units**, and **Mean event\_dau** over the same three days of the experiment. Alice was active on three days for the _Page View_ event and on one day for the _Add to Cart_ event. Alice's average event\_dau is 3/3 for the _Page View_ event and 1/3 for the _Add to Cart_ event. Alice's **daily participation rate** is 1.00 for the _Page View_ event and 0.33 for the _Add to Cart_ event. Statsig aggregates the average event\_dau for each user in the experiment, with each user weighted equally. ![Event DAU metrics table showing daily participation rates](https://docs.statsig.com/images/metrics/pulse/187721834-b8e94f15-f3ee-4584-924b-96e424ddcd0c.png) To measure engagement changes for a call-to-action link or button, use two metrics. Use event\_count to measure the change in average clicks per user, and use event\_dau to measure the change in the daily participation rate for the click. > **Info:** > > **Event Count and Event DAU in Custom Metrics** > > : When creating a custom ratio metric, use event\_count to include all events (counting all events triggered by the same user). Use event\_user (or event\_dau, if available) to count unique active users on a given day (all events triggered by the same user are counted as one). ## Winsorization To reduce the impact of outliers, Statsig caps _event\_count_ and _sum_ metric types at the 99.9th percentile by default. The cap reduces the risk that bots and extreme values skew experiment results. Statsig computes the 99.9th percentile threshold using all non-zero and non-null metric values. Statsig replaces all values exceeding this limit with the threshold value. Warehouse Native (WHN) allows for more customization of winsorization by metric and by percentile. ## Frequently asked questions **1. Can a ratio metric move in the opposite direction from both the numerator and denominator metrics?** Yes, the ratio can rise while both the numerator and denominator metrics decline. This happens when the denominator falls more than the numerator. Statsig recommends tracking the numerator and denominator as independent metrics when monitoring a ratio metric. Ratio metrics are often subject to statistical noise and can be difficult to use for obtaining a statistically significant result. **2. For ratio metrics, how does Statsig determine _participating users_?** Statsig computes ratio metrics only for users with a non-zero value in the denominator. A user must trigger the denominator event on a given day to appear in the daily ratio. Statsig excludes users who don't trigger the denominator event during an experiment from the test vs. control comparison. **3. What is the difference between One-Time Event and Daily Participation Rate?** This distinction is relevant only in the context of an experiment. Daily participation rate counts the number of _days_ a user has that event, divided by the number of _days_ the user has been in the experiment. One-time event is a binary metric that checks whether the user has that event _at least once_ during the experiment. ================================================================================ # Local Metrics URL: https://docs.statsig.com/metrics/local-metrics ================================================================================ # Local Metrics ## How Local Metrics work Local Metrics are metrics scoped to an individual config (a specific experiment or gate). Statsig creates them within that config to capture how the metric trends in that context, without adding the metric to the project-wide Metrics Catalog. ## Creating a Local Metric You can create a Local Metric from two places within your config: 1. **Setup**: While setting up your gate or experiment and adding Primary, Secondary, or Monitoring metrics, you can add a metric that doesn't yet exist to your Scorecard. Select **+ Create New Local Metric** to enter the Local Metric creation flow. ![Setup tab showing + Create New Local Metric button](https://docs.statsig.com/images/metrics/local-metrics/2a249684-56a9-4c63-b2b2-7870efd89b76.png) 2. **Pulse**: After you start your gate or experiment rollout, you can still create and add a new Local Metric to your scorecard. From your Scorecard in Pulse, select **Edit Primary Metrics** (or Secondary or Monitoring metrics, depending on where you want to add your new Local Metric). Then select **+ Create New Local Metric**. ![Pulse scorecard with Edit Primary Metrics and Create New Local Metric options](https://docs.statsig.com/images/metrics/local-metrics/b718c3b7-9696-4af0-bbc5-48fef3cfa1d3.png) When you enter the Local Metric creation flow from either entry point, the Local Metric creation wizard starts. The wizard lets you select events, add filters, and preview the output values. ![Local metric creation wizard with event selection and filters](https://docs.statsig.com/images/metrics/local-metrics/452d9efe-2706-4d47-aee6-48c8f6288e8f.png) When you're ready to save your Local Metric, you can save it to one of two places. Choose the Primary/Secondary Metrics section of your Scorecard (for experiments), or the Monitoring Metrics section of your feature gate rollout. ![Local metric placement selector for primary scorecard](https://docs.statsig.com/images/metrics/local-metrics/50bc5742-2f2a-4147-9cb3-70658d6391da.png) ![Monitoring metrics section showing new local metric entry](https://docs.statsig.com/images/metrics/local-metrics/ae3932df-f81b-4fed-9d23-b2b196ac83bc.png) After you create a Local Metric, you can select it in your Scorecard to view its configuration in the Local Metric wizard. ## Types of Local Metrics The types of Local Metrics you can create are similar to Custom Metrics (accessible through the _Metrics_ tab), with a few exceptions. Here are the supported types of Local Metrics: | Metric Type | Description | Examples | | --- | --- | --- | | Event Count | **Total count of events** filtered by the _value_ and _metadata_ properties of an event type | **Add to Cart** event filtered by category type | | User Count | **Number of unique users** that trigger events filtered by the _value_ and _metadata_ of an event type | **Active Users** based on their views of a product category | | Aggregation | **Sum or Average** of the _value_ of an event type | **Total Revenue** | | Ratio | **Rates** (e.g. cart conversion rate, purchase rate), **Normalized Values** (e.g. sessions per user, items per cart) | **Cart Conversion Rate**, **Sessions per User** | The one type of Custom Metric that you can't (yet) create as a Local Metric are funnels. ## Lifecycle of Local Metrics By default, Local Metrics are scoped to the config you create them in and exist only for the lifecycle of that config. After you make a decision on your experiment or launch your feature gate, Statsig no longer computes the Local Metric. Local Metrics don't appear in your _Project Metrics Catalog_ and aren't searchable in top-line search. Statsig doesn't yet support converting a Local Metric into a Metrics Catalog metric, but this conversion flow is coming soon. In the meantime, you can recreate the same metric definition as a Custom Metric in the _Metrics Catalog_. Recreate it if you want the metric to exist outside the scope of your gate or experiment. ================================================================================ # Metrics Dashboard URL: https://docs.statsig.com/metrics/console ================================================================================ # Metrics Dashboard The Statsig console lets you explore and visualize every event and metric in your project. Statsig makes metrics available for all unit types enabled in the project. Statsig provides User ID and Stable ID by default; you can add others following [these steps](https://docs.statsig.com/guides/experiment-on-custom-id-types#step-1---add-companyid-as-a-new-id-type-in-your-project-settings). Select a unit type from the dropdown to view event DAU and user accounting metrics calculated for that unit type. ![Metrics unit type selection](https://docs.statsig.com/images/metrics/console/172450890-4a4c95eb-a362-49a6-90ad-68f3460a933f.png) ## Events The Metrics console lets you visualize all the events that you have logged in Statsig. The **Events** tab shows all the events, including a real-time stream of events as they come in. ![Events tab view](https://docs.statsig.com/images/metrics/console/172451019-fc450842-a546-4ea0-94a9-d54df8279ed2.png) You can toggle between a list view or chart view of your events to view the trend line over time. ![Events chart view](https://docs.statsig.com/images/metrics/console/172461387-a3d42641-2c2c-4128-aabc-fc2b5dba2ed9.png) From the Events tab, you can drill into each event to see a detailed view of the logs, broken down by each unique value you logged. ![Event detailed view](https://docs.statsig.com/images/metrics/console/172462231-ff2f3063-0c4e-49fd-af17-7147bd09d3d1.png) ## Metrics Catalog The **Metrics Catalog** tab lets you search and tag your metrics, as well as [create custom metrics](https://docs.statsig.com/metrics/create). Tags let you organize metrics and create collections grouped by product area, business function, business objective, or any other common attribute. You can also create a collection of guardrail metrics that teams check in every experiment to detect unexpected effects in other parts of the business. After you create a tagged collection, you can filter your experiment results to that collection and focus on the metrics that matter. ![Metrics catalog](https://docs.statsig.com/images/metrics/console/172462680-68a6de4e-17bf-4b11-920d-6d7830551012.png) Similar to the **Events** tab, you can toggle between a list view or chart view of your metrics to view the trend line over time. ![Metrics chart view](https://docs.statsig.com/images/metrics/console/172462947-877bbcc7-46b3-45cd-ac57-d0dc2c949d7d.png) ================================================================================ # Metrics 201 - Creating Custom Metrics URL: https://docs.statsig.com/metrics/201 ================================================================================ # Metrics 201 - Creating Custom Metrics Create your own metrics in Statsig and organize them as your project grows. You can also customize the definition of your daily active users (DAU). 1. [Creating Custom Metrics](https://docs.statsig.com/metrics/create) for your product in the Statsig console 2. [Creating Metric Tags](https://docs.statsig.com/metrics/create-metric-tags) to organize the metrics in your Statsig Project 3. [Customizing the DAU Definition](https://docs.statsig.com/metrics/user) that Statsig uses to compute [User Accounting](https://docs.statsig.com/metrics/raw-event-metrics#user-accounting-metrics) metrics ================================================================================ # Creating Custom Metrics URL: https://docs.statsig.com/metrics/create ================================================================================ # Creating Custom Metrics Statsig computes custom metrics from your raw events. To create custom metrics, navigate to **Metrics** from the left-hand navigation panel, then to the **Metrics Catalog** tab. Select the **Create** button. ![Create custom metrics interface](https://docs.statsig.com/images/create-metric.png) Statsig supports six types of custom metrics: | Metric Type | Description | Examples | | --- | --- | --- | | Event Count | **Total count of events** filtered by the _Value_, _Metadata_, or _User Object_ properties of an event type | **Add to Cart** event filtered by category type | | User Count | **Number of unique users** that trigger events filtered by the _Value_, _Metadata_, or _User Object_ of an event type | **Active Users** based on their views of a product category | | Aggregation | **Sum or Average** of the _Value_, _Metadata_, and _User Object_ property of an event type | **Total Revenue** | | Ratio | **Rates** (e.g. cart conversion rate, purchase rate), **Normalized Values** (e.g. sessions per user, items per cart) | **Cart Conversion Rate**, **Sessions per User** | | Funnel | **Funnels**- funnel of multiple events with conversion tracking | **Sign-up Funnel**, **Checkout Funnel** | | Count Distinct | **Count Distinct**- Number of unique values for a given field, often approximated with sketches | **Unique Songs** listened per user | Statsig computes custom metrics daily for your **Metrics** dashboard, and rolls them up for the duration of the experiment in **Pulse Results** for your Feature Gates and Experiments. After you create a custom metric, it doesn't populate until the next day and doesn't backfill to previous days. Statsig calculates the metric only from the creation date forward. Statsig lets you set a daily **max cap** for specific metrics. You can define maximum caps for various unit types associated with a metric. Statsig automatically adjusts any value exceeding the cap down to match it. For example, if purchases over $10,000 per day on your e-commerce platform shouldn't skew analysis, Statsig adjusts any transaction above that threshold down to the limit. Statsig supports capped metrics for event count and aggregation (sum) metric types. When creating a custom metric, you can preview the metric’s value at the bottom of the page. Select **View Output Preview** to see what the metric would have looked like based on its component values over the last 7 days, in both chart and table form. ![Aggregation metric setup screen with output preview chart and table](https://docs.statsig.com/images/metrics/create/0869e1bf-8fea-407e-8a5f-8b97860b3867.png) ## Examples ### 1. Event count metrics This example sets up a custom event metric to count the **number of add\_to\_cart events** filtered by a metadata property called _value_, which carries the price of the item added to the cart. Because you set the ID Type to _userID_, Statsig computes this metric as part of the test group that Statsig assigns the corresponding user to in an experiment. ![Event count metric filtering add_to_cart events with value greater than 100](https://docs.statsig.com/images/metrics/create/95489e9b-36f2-4704-9970-da675a8a3d2e.png) If you select the ID Type as _stableID_, Statsig computes this metric in the test group that Statsig assigns the corresponding device to in an experiment. When you select more than one ID Type, Statsig computes this metric for each ID Type you specify. ### 2. User count metrics The example below creates a metric to count the **number of unique users** who viewed a product in the _toys_ category priced under $10. ![User count metric configuration counting viewers of toys category under ten dollars](https://docs.statsig.com/images/metrics/create/ae270d11-d3de-4f34-85e5-a67ad9c7cd9e.png) #### Time window Statsig offers three time window options for user count metrics: - **Daily Participation Rate**: Counts the total number of days a user has the selected event, divided by the number of days the user is in the experiment. The result is a value between 0 and 1, representing the probability of a user having the event on any given day. Works best for events expected to occur repeatedly for a given user. - **One Time Event**: Checks if a user has the selected event at least once during their time in the experiment. The result is a binary metric with value 0 or 1 for each user. Ideal for events expected to occur only once per user, such as sign-up events. - **Custom Attribution Window**: Lets you define a custom window after exposure to count an event toward a metric calculation. ### 3. Aggregation metrics The example below shows a **Total Revenue** metric that sums the _value_ associated with all purchase events. ![Sum aggregation configuration for Total Revenue metric](https://docs.statsig.com/images/metrics/create/f0d4d21b-08ae-405d-a156-4d29f96ab298.png) **\[Early Access\] Currency Sum** eCommerce customers often span multiple currency types and log payments in the currency the user actually pays. Currency sums convert payments recorded in different currencies to a single common currency. You must log two metadata fields in your event: a currency code and a value. Example metadata: `_{"currency_code": "USD", "currency_value": 123.45}_` Statsig supports currency sums upon request. Ask in [Slack](https://statsig.com/slack). ### 4. Ratio metrics The example below shows creating a **Cart Conversion Rate** metric. Statsig uses unique users who triggered the _purchase event_ as the numerator, and unique users who triggered the _add to cart_ event as the denominator. When calculating the numerator, Statsig includes only users who also had the denominator event on the same day. A user who has only a _purchase event_ on a given day without an _add to cart_ on that same day doesn't count toward the numerator. ![Ratio metric setup for cart conversion rate](https://docs.statsig.com/images/metrics/create/9f8a671e-ac1f-4e2f-92cb-d154e0daecac.png) This pattern also applies to **click-through rates (CTR)** in any part of a step-wise product journey (funnels). Statsig recommends using unique users in both the numerator and denominator for these metrics. For example, a user who reloads a page multiple times but clicks only once corresponds to a 100% CTR (1 out of 1). A user who loads a page once but clicks a button multiple times also counts as 1 out of 1. This approach handles cases where users see a key button, such as "Sign-up," multiple times a day, and Statsig counts a single click as a success. The example below shows creating an **Items per Cart** metric. You can track the number of unique items added to a cart by logging an _add\_to\_cart_ event for each item. For the numerator, select total event count. For the denominator, select unique users. Because Statsig computes this metric daily and only for users with a non-zero denominator, it can generate ratios such as 1/1, 2/1, and 5/1 for individual users. When Statsig aggregates them, this translates to an average such as 10/4 = 2.5 items per cart per day. ![Items per cart metric configuration using event counts](https://docs.statsig.com/images/metrics/create/cf6e6777-a154-4eeb-9a2d-81893810a31d.png) > **Info:** > > **A Word of Caution** > > : In experimentation, ratio metrics are a frequent source of misleading information. It's possible to see an increase in > > **click through rate** > > alongside a net > > _decrease_ > > in total clicks (the opposite may also happen). This situation can occur if the number of unique users viewing a button (denominator) decreases. As a best practice, Statsig recommends tracking the numerator and denominator as independent metrics when monitoring ratio indicator. Ratio metrics are often subject to statistical noise and can be tricky to use for obtaining a statistically significant result. In addition, for the numerator in ratios, Statsig excludes units that don't have a denominator value. ### 5. Funnel metrics You can create a custom funnel metric from either the Custom Metrics Creation wizard in the Metrics Catalog or through the **Charts** tab. ![Funnel metric creation wizard](https://docs.statsig.com/images/metrics/create/86914826-b8ce-4b4b-9514-39f31d05687a.png) > **Info:** > > **Important Note** > > : Statsig handles funnel metrics differently between the Cloud and Warehouse Native platforms. Funnel metrics using the Cloud platform are > > _always_ > > unordered, meaning that a user can complete funnel steps in any order, and they have a time window of > > _one day_ > > . This means that for the metric to record a completion, a user must trigger all steps within 24 hours. In contrast, funnel metrics on Warehouse Native offer the option of strict ordering and custom time windows. ### Components of funnel metrics Funnel metrics have a few components: 1. **Lineage**: Surfaces the events used to generate the funnel 2. **Metric Value**: Metric value represents the overall funnel conversion rate, or the percentage of users who complete a funnel (trigger the end event) relative to all users who start the funnel (trigger the starting event). 3. **Conversion rate between stages**: This set of metrics track the percentage of users who triggered an event N relative to all users that triggered event N-1 in the funnel. ![Funnel lineage and stage conversion breakdown view](https://docs.statsig.com/images/metrics/create-user-funnels/172446711-5511e394-b353-4d38-97f1-1b681b67042b.png) After Statsig creates and populates funnels, you can view your funnel metric like any other metric in Pulse. You can also expand the funnel metric to view Pulse performance at each step in the funnel. In the example below, the **Square** variant shows a lift in the **overall funnel conversion rate**. When you expand the metrics to examine the entire funnel, two key insights appear: - Both the **Square** and **Circle** variants show a lift in top-of-funnel DAU (_Land Page View Start DAU_). However, only the **Square** variant shows statistically significant increase in end-of-funnel DAU (_Purchase Event End DAU_). - The overall funnel conversion rate improvement for **Square** is primarily due to the higher conversion from _Checkout Event_ to _Purchase Event_ stages in the funnel. ![Funnel experiment results showing Square variant performance](https://docs.statsig.com/images/metrics/create-user-funnels/148440643-8e8a24bd-934d-4100-a15a-abcbcc4bb11c.png) ### 6. Count distinct metrics > **Info:** > > Sketch-based count distinct metrics are in Early Access. Reach out to Statsig Support if you want Statsig to enable this. - **What it is**: A high-performance way to estimate the number of distinct values using compact sketch data structures. Example use cases include unique songs per user or unique products purchased per user. - **Benefit**: Much faster to compute and uses significantly less memory compared to exact distinct counting, especially at high cardinality. ### Custom metrics and dimensions For custom metrics composed of a single event (event count, event DAU, aggregation, and so on), Statsig automatically includes the dimensions of the source event in the custom metric and exposes them as dimensions of that metric. If your custom metric consists of two or more different events, Statsig doesn't include the dimensions of those source events in the custom metric, and they aren't queryable through the "Explore" tab in Pulse Results. ================================================================================ # Custom DAU Metric Creation Guide URL: https://docs.statsig.com/metrics/custom-dau ================================================================================ # Custom DAU Metric Creation Guide ## Custom DAU metric creation guide A custom DAU metric counts the unique users who trigger a specific event each day, such as Add to Cart. Create one in the Metrics Catalog as a Unit Count metric when you want daily-active-user tracking for an event Statsig doesn't generate automatically. ### Step 1: Navigate to the metrics catalog Go to the _Metrics Catalog_ in the left navigation bar and select **Create**. ![Picture1.png](https://docs.statsig.com/images/custom-metrics/Picture1.png) ![Picture2.png](https://docs.statsig.com/images/custom-metrics/Picture2.png) ### Step 2: Name your metric Enter a name for your metric. For example: "Add to Cart DAU". ![Picture3.png](https://docs.statsig.com/images/custom-metrics/Picture3.png) ### Step 3: Choose the metric type To create a DAU metric, select **Unit Count** as the metric type. ![Picture4.png](https://docs.statsig.com/images/custom-metrics/Picture4.png) ### Step 4: Select the ID type Select the ID type to count. For example, select **User ID**, which is the most common ID type for DAU metrics. ![Picture5.png](https://docs.statsig.com/images/custom-metrics/Picture5.png) ### Step 5: Choose the event Select the event to use for your metric. For example, select the **Add to Cart** event. ![Picture6.png](https://docs.statsig.com/images/custom-metrics/Picture6.png) ### Step 6: Submit the metric Submit the metric. Statsig now creates your custom DAU metric. ![Picture7.png](https://docs.statsig.com/images/custom-metrics/Picture7.png) ================================================================================ # Archiving and Deleting Metrics URL: https://docs.statsig.com/metrics/archiving-metrics ================================================================================ # Archiving and Deleting Metrics Statsig offers two ways to manage the end of life of a metric: - **Archiving a metric**: Statsig stops including the metric in new analyses but keeps its definition and history. You can unarchive it later. Archive a metric when it's no longer relevant but you want to keep its record, for example an older version of a metric that continues to evolve. - **Deleting a metric**: Statsig removes the metric and its history. Delete a metric when you made a mistake, logged or imported an irrelevant metric, or created a more accurate replacement, for example a metric with an incorrect definition or name, or a duplicate. Some steps work differently in Statsig Cloud and Statsig Warehouse Native (WHN). This page calls out those differences in each section. ## Archive a metric You can archive a metric from three places: 1. In the **Metrics Catalog**, select one or more metrics. In the toolbar that appears, select the **Archive** icon. ![Bulk Archive](https://docs.statsig.com/images/metrics/archiving-metrics/215638876-3c2ae682-8db8-4dc7-9c14-3b4d7185f57e.png) 2. On the metric's detail page, select **...** in the upper-right corner, then select **Archive**. ![Archive](https://docs.statsig.com/images/metrics/archiving-metrics/215639240-321b4e3f-d9c7-4f7d-ab77-9e18ba1c5867.png) 3. With the Console API, use [Schedule a metric archive](https://docs.statsig.com/api-reference/metrics/schedule-a-metric-archive). When archiving takes effect depends on your deployment: | | Statsig Cloud | Warehouse Native | | --- | --- | --- | | When the metric is archived | After a 24-hour grace period. You can undo the archival during this period. | Immediately. | | Notifications | Statsig emails the metric's creator, the person who archived it, and the owners of experiments that use the metric. They also get an in-app notification. | None. | | Newly created metrics | You can't archive a metric within 24 hours of creating it. | No restriction. | ### Before you archive The **Archive Metric** dialog shows what the archival affects: - **Experiments Impacted**: experiments that use the metric. This is a warning only and doesn't block the archival. - **Metrics Impacted** (Statsig Cloud): other metrics built on this metric, such as ratio or composite metrics. You must delete those metrics before you can archive this one. ![Archive dependencies](https://docs.statsig.com/images/metrics/archiving-metrics/215640348-b210eb9e-5475-4853-869f-7a9f66375f0a.png) If your project requires reviews for metric changes, the dialog shows **Submit for Review** instead of **Confirm**. The metric is archived after the review is approved. Archiving a metric also changes two settings that unarchiving doesn't restore: - **Permanent status**: archiving a permanent metric marks it as non-permanent. If you unarchive it, mark it as permanent again. - **Metric family membership**: archiving a child metric removes it from its [metric family](https://docs.statsig.com/metrics/metric-family). Unarchiving the child doesn't add it back to the family. ### Grace period (Statsig Cloud) On Statsig Cloud, a **Pending Metric Archival** banner appears at the top of the metric's detail page during the 24-hour grace period. Statsig keeps computing the metric during this time. To cancel the archival, select **Undo** on the banner. ![Archive Grace Period](https://docs.statsig.com/images/metrics/archiving-metrics/215640435-412375f7-398b-4bef-9495-cc20d1805769.png) ## What happens to an archived metric After archival takes effect: - **The metric drops out of new analyses.** Statsig stops computing custom metrics once they're archived, and archived metrics are left out of new experiment results. For details, see [Archived metrics in experiment results](#archived-metrics-in-experiment-results). The metric's definition and history are kept. - **The metric page shows an Archived Metric banner**, which says when the metric was archived and by whom. - **The metric stays in the Metrics Catalog.** Archived metrics are listed after active metrics, with their names greyed out. To find them, filter the catalog by **Status** and select **Archived**. The **Status** filter also includes **Scheduled for Archival**, **Scheduled for Deletion**, and **Permanent**. - **You can't add the metric to new analyses.** Archived metrics can't be added to experiment scorecards or dashboards. ### Archived metrics in experiment results Archiving a metric doesn't edit the experiments that use it. How the metric appears in results depends on your deployment: - **Statsig Cloud**: the metric no longer appears in the experiment's setup scorecard. In results, Statsig hides the metric only when the analysis period ends after the archival date. Results for a period that ended before the metric was archived still include it. If you unarchive the metric, it reappears in the experiment. - **Warehouse Native**: results that were loaded before the archival keep showing the metric. Result loads that run while the metric is archived, scheduled or manual, don't calculate it. ## Unarchive a metric ### During the grace period (Statsig Cloud) Select **Undo** on the **Pending Metric Archival** banner at the top of the metric's detail page. Statsig was still computing the metric during the grace period, so nothing is lost. ### After the metric is archived You can unarchive a metric from three places: - On the metric's detail page, select **Unarchive** on the **Archived Metric** banner. - In the **Metrics Catalog**, filter by **Status** > **Archived**, select the metrics, then select the **Unarchive** icon in the toolbar. - With the Console API, use [Unarchive a metric](https://docs.statsig.com/api-reference/metrics/unarchive-a-metric). ![Archive after grace period](https://docs.statsig.com/images/metrics/archiving-metrics/215640543-7cb05d46-e61d-4cf4-a07c-eb76c9f50e36.png) What happens next depends on your deployment: - **Statsig Cloud**: Statsig starts computing the metric again about 24 hours after you unarchive it. History from before the archival is kept, but Statsig doesn't compute the metric for the period it was archived, so that period stays a gap in the metric's data. - **Warehouse Native**: the metric is available again immediately. Result loads that ran while it was archived didn't calculate it. To include the metric in those results, run a full reload of the experiment. After unarchiving, mark the metric as permanent again if it was permanent before it was archived. You can't unarchive a metric while: - Its metric source is archived. Unarchive the metric source first. See [Archive a metric source](#archive-a-metric-source-warehouse-native). - It has a pending review. ## Archive a metric source (Warehouse Native) Archiving a metric source stops anyone from creating new metrics on it or using it in a metric definition. It's reversible, and it doesn't change or delete the source's setup or the metrics linked to it. ### Before you archive a metric source You must archive every metric on the source before you can archive the source. Until then, the **Archive** option is disabled with the message "Archive all dependent metrics before archiving this metric source." A metric that is only scheduled for archival, but not yet archived, still counts as active. Experiment- or gate-scoped (local) metrics on the source count as active until their experiment or gate is archived. You can't archive: - Statsig-generated metric sources - Metric sources with an active review - Qualifying event sources ### Archive or unarchive a metric source 1. Open the metric source. 2. Select **...**, then select **Archive**. 3. Confirm. If your project requires reviews, submit a review instead. To unarchive, select **...** > **Unarchive** on the same page. ### While a metric source is archived The metric source page shows the banner "This metric source is not available for new metrics. Existing metrics can keep referencing it, but it must be unarchived before it can be used again." "Existing metrics" refers to the archived metrics that still point to the source. Archiving a source doesn't detach them. Active metrics can't run on an archived source, because every metric on it must be archived first. While the source is archived: - You can't create a metric on it or save a metric definition that uses it. This applies in the Console, the Console API, and Semantic Layer Sync. - You can't unarchive the metrics on it. - It still appears on the **Metric Sources** page, after active sources, labeled **Archived**. To see only archived sources, use the **Archived** filter. - In metric source pickers, it appears disabled with the message "Archived metric sources cannot be used in metrics." ### Restore a metric source and its metrics Unarchiving a metric source doesn't unarchive its metrics. To fully restore them: 1. Unarchive the metric source. 2. Unarchive each metric you want back. 3. Mark as permanent any metrics that were permanent before they were archived. 4. Run a full reload of experiments whose results were loaded while the metrics were archived. ## Auto-archival To reduce metric clutter, Statsig can automatically archive custom metrics that have been inactive for at least 60 days. A Project Admin can turn this on or off in **Project Settings** > **General** > **Auto-archive inactive metrics**. ![Project Settings](https://docs.statsig.com/images/metrics/archiving-metrics/74cd5575-e1bb-4f69-87f9-1feece5eb73f.png) ### Which metrics are auto-archived A metric is auto-archived only when all of the following are true: - It's a custom metric in the Metrics Catalog. Built-in metrics and experiment- or gate-scoped (local) metrics are never auto-archived. - It was created more than 60 days ago. - It isn't marked as permanent. - It isn't used by an active experiment, an active feature gate, or another metric. - It had no activity in the last 60 days. ### How Statsig measures activity Statsig counts a metric as active when, in the last 60 days, it was: - **Used** in an experiment scorecard, a feature gate's monitoring metrics, or another metric, such as a ratio or composite metric. - **Changed**: you edited its setup, restored a previous version, added a tag, or created or updated an alert on it. - **Viewed** in the Console, for example by opening it from the Metrics Catalog. You can see a summary of a metric's usage on its detail page: ![Metric References](https://docs.statsig.com/images/metrics/archiving-metrics/6f7eb3db-399a-45c8-be19-794e89dd349d.png) ### When auto-archival happens | | Statsig Cloud | Warehouse Native | | --- | --- | --- | | Timing | Statsig schedules the archival 14 days ahead. | Statsig archives the metric immediately. | | What you see | A **Pending Metric Archival** banner on the metric's detail page: "Metric auto-archival is turned on for this project. This metric will be automatically archived on \[date\] due to a period of inactivity." In the Metrics Catalog, a clock icon marks the metric as scheduled for archival. | The metric shows as archived. | | Email notification | None. | None. | During the 14-day period on Statsig Cloud, the banner offers two options: - **Extend by 30 Days**: moves the scheduled archival date 30 days later. - **Mark as Permanent**: removes the metric from auto-archival. ![Banner](https://docs.statsig.com/images/metrics/archiving-metrics/d7378d7b-a588-496b-ae35-24f38c6d5b6a.png) Using or changing the metric before the scheduled date also cancels the pending archival. Turning off **Auto-archive inactive metrics** cancels all pending auto-archivals in the project. ### Mark a metric as permanent Permanent metrics are never auto-archived. Reserve permanent status for your most important and widely reused metrics. To mark a metric as permanent, on its detail page select **...** > **Mark as Permanent**. You can also select **Mark as Permanent** on the **Pending Metric Archival** banner. ![Dropdown](https://docs.statsig.com/images/metrics/archiving-metrics/2a570a92-76d6-41b3-aea5-ebdd53469856.png) If the metric is already archived, marking it as permanent also unarchives it. If the metric's source is archived, unarchive the metric source first. See [Archive a metric source](#archive-a-metric-source-warehouse-native). To remove the status, select **...** > **Mark as Non-Permanent**. ## Delete a metric To delete a metric, open its detail page, select **...** in the upper-right corner, then select **Delete**. You can also delete a metric with the Console API's [Delete a metric](https://docs.statsig.com/api-reference/metrics/delete-a-metric) endpoint. ![Delete metric](https://docs.statsig.com/images/metrics/archiving-metrics/215641202-82f23bac-f620-4d4a-8c32-fe64a4ffc06c.png) How deletion works depends on how you delete the metric: | | Statsig Cloud, metrics older than 24 hours | Warehouse Native, Statsig Cloud metrics created in the last 24 hours, and the Console API | | --- | --- | --- | | When the metric is deleted | After a 24-hour grace period. | Immediately. | | Undo | Select **Undo** on the **Pending Metric Deletion** banner during the grace period. | Not available. | | Dependency checks | The dialog lists experiments that use the metric. If other metrics are built on this metric, you must delete them first. | None. | ![Dependencies](https://docs.statsig.com/images/metrics/archiving-metrics/215641295-55c8dc10-7199-4505-ba0e-d02299fb371a.png) ![Undo delete](https://docs.statsig.com/images/metrics/archiving-metrics/215641634-1c70e688-0fe9-4cac-80bb-d3faeedcc0ed.png) > **Warning:** > > You can't undo a deletion after it takes effect. Statsig permanently removes the metric and its history. If you might need the metric again, archive it instead. After a metric is deleted, it no longer appears in experiment results, scorecards, or the Monitoring Metrics section of feature gates. You can't delete auto-generated event metrics. You can delete an archived metric. ================================================================================ # Creating Metric Tags URL: https://docs.statsig.com/metrics/create-metric-tags ================================================================================ # Creating Metric Tags ## Tagging metrics Metric tags group related metrics into collections you can organize by product area, business function, business objective, or any other shared attribute. Tag your metrics to filter Pulse and experiment results down to the collection that matters most. To create a metric tag, click on **Metrics** in the left hand navigation menu, and click on the [Metrics Catalog](https://console.statsig.com/4TLCtqzctSqusYcQljJLJE/metrics/metrics_catalog) tab. ![Metrics catalog navigation](https://docs.statsig.com/images/metrics/create-metric-tags/172474361-3c47eb33-0d44-457f-b3be-dc61cd085cb8.png) In the **Metrics Catalog** tab, click on the **Tags** filter icon in the upper right-hand corner, and then tap **Manage** in the drop-down. Selecting **Manage** takes you to the tag manager within Project Settings for all tags in your project. ![Tags filter management](https://docs.statsig.com/images/metrics/create-metric-tags/172474897-7eb84784-ff21-4461-87cd-6a0c45bb7ef7.png) Tap on the **Create New Tag** in the upper right-hand corner of the tag manager tab to create a new tag. Enter a name and description for your new tag. Click on **Create**. ![Create new tag dialog](https://docs.statsig.com/images/metrics/create-metric-tags/154555162-9309a3f5-0278-4a04-8620-245408e5d6d0.png) After creating the tag, add it to any metric using the **+** icon when you hover on the metric. To see which metrics have a given tag, refer to the **Tags** tab within Project Settings. ![Metrics catalog with tag management interface](https://docs.statsig.com/images/metrics/create-metric-tags/154557097-3a2e07d9-1bb4-4cc5-9d03-c96b61f34296.png) After tagging your metrics, you can filter **Metric Lifts** in Pulse by the tagged collection to focus on the results that matter most. ![Pulse results showing tagged metric lifts](https://docs.statsig.com/images/metrics/create-metric-tags/154556623-79b2b198-b24d-40fa-bcf8-0feccef70f29.png) ## Core tag Every Statsig project includes an auto-created **Core** tag pre-populated with a subset of User Metrics. User Metrics are classic growth metrics (such as MAU, WAU, DAU, L7, and 28-day retention) that Statsig calculates daily from your logged events. Statsig adds the following User Metrics to the Core tag by default (you can remove them or replace them with more relevant business metrics): - DAU/ WAU/ MAU - New users - Daily/ Weekly/ Monthly user stickiness The Core tag serves as a collection of your most important business metrics to monitor with every new feature rollout and experiment. Statsig automatically adds the Core tag to all new feature gates and experiments at the point of creation. In an experiment, Statsig adds the Core tag to the Scorecard, under **Secondary Metrics**. In a feature gate, Statsig adds the Core tag to the **Monitoring Metrics** section. If you create a gate or experiment under a Team that has default metrics configured, the Team's defaults override the Core tag. To include Core metrics for those Teams as well, add the Core tag to the Team's **Default Secondary Metrics** (experiments) or **Default Monitoring Metrics** (gates). ## Configuring your core metrics Because the Core tag receives special treatment, curate the metrics in this tag collection during project setup. Go to **Metrics** → **Metrics Catalog** and add the **Core** tag to any relevant metrics. To see which metrics already have the **Core** tag applied, filter by the **Core** tag in the Metrics Catalog by tapping the filter icon in the upper right-hand corner, then **Tags**, then selecting the **Core** tag. Remove the Core tag from any unwanted metrics in the filtered list. ![Core metrics filter view](https://docs.statsig.com/images/metrics/create-metric-tags/206882708-399dbb67-098e-463c-aa56-df62fc5c780a.png) ## Setting rollout alert thresholds for your core metrics When rolling out a new feature or experiment, you may want Statsig to notify you if the rollout negatively impacts a key business metric. Statsig lets you set Rollout Alerts at the per-metric level. You receive an alert if any running experiment or feature gate regresses the metric beyond the set threshold. Because Core Metrics are important, configure Rollout Alerts for Core Metrics through the Metrics Catalog. For more on Rollout Alert configuration, refer to [Rollout Alerts](https://docs.statsig.com/metrics/rollout-alerts). ================================================================================ # User Accounting Metrics (DAU/WAU/etc.) URL: https://docs.statsig.com/metrics/user ================================================================================ # User Accounting Metrics (DAU/WAU/etc.) ## DAU (daily active user) definition Statsig automatically creates a standard set of user accounting metrics to track common product-wide engagement metrics like daily active users (DAU), new users, and retention. Statsig also tracks more sophisticated metrics like L-ness, retention, and stickiness. All Standard User Accounting Metrics rely on a company-wide definition of a daily active user. By default, Statsig defines a DAU as a [user that the Statsig SDK has logged](https://docs.statsig.com/sdks/user) any custom event (`log_event`) for. You can [customize the DAU definition](#customizing-the-dau-definition). > **Info:** > > **Warehouse Native Users** > > You're viewing a feature designed for Statsig Cloud users. Warehouse Native customers typically have multiple datasets that uniquely affect how they define active users. Refer to [Retention metrics in Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/metrics/retention). ## Notation and conventions - The first day a new user was active is Day Zero (D0), with subsequent days labeled D1, D2, D3, and so on. - A weekly active user is someone active within the last 7 days (0-6 days), including users active on all 7 days and users active on only a single day. The same definition applies to a monthly active user. - A user with a single session that spans midnight (with qualifying events at 11:59 PM and 12:01 AM) qualifies as a daily active user on both days. - Statsig reserves the right to limit tracking to 100M unique IDs per unit type per year. ## Default user accounting metrics in Statsig ### General user metrics | **Metric Name** | **Type** | **Description** | | --- | --- | --- | | `daily_active_user` | Count | Users who were active on a given calendar day (DAU). | | `weekly_active_user` | Count | Users who were active at least once in the past 7 days (WAU). | | `monthly_active_user` | Count | Users who were active at least once in the past 28 days (MAU). | | `new_dau` | Count | Users who became active for the first time on a specific day. | | `new_wau` | Count | Users who became active for the first time within the last 7 days. | | `new_mau_28d` | Count | Users who became active for the first time within the last 28 days. | | `daily_user_stickiness` | Stickiness (Rolling) | Fraction of the prior day's users who are active on the next day. Rolling day-to-day repeat engagement (**not** DAU/MAU or DAU/WAU). | | `weekly_user_stickiness` | Stickiness (Rolling) | Fraction of the previous week's users who have been active within the last 7 days. This metric tracks rolling week-over-week repeat engagement (**not** WAU/MAU). Statsig defines the previous week as 8-14 days before the metric date. | | `monthly_user_stickiness` | Stickiness (Rolling) | Fraction of the previous month's users who have been active within the last 28 days. This metric tracks rolling month-over-month repeat engagement (**not** DAU/MAU). Statsig defines the previous month as 29-56 days before the metric date. | | `d1_retention_rate` | Retention (Rolling) | % of new users from 1 day ago who were active at least once today. Rolling Day 2 window retention. | | `WAU @ D14 Retention Rate` | Retention (Rolling) | % of new users from 13 days ago who were active at least once in days 8–14. Rolling Week 2 window retention. | | `MAU @ D56 Retention Rate` | Retention (Rolling) | % of new users from 56 days ago who were active at least once during days 29–56. Rolling Month 2 retention. | | `L7` | L-ness | Average number of days a user was active in the last 7 days (value range: 0–7). | | `L14` | L-ness | Average number of days a user was active in the last 14 days (value range: 0–14). | | `L28` | L-ness | Average number of days a user was active in the last 28 days (value range: 0–28). | These user metrics are useful for understanding long-term user behavior. However, several of these metrics don't behave well as daily experimentation metrics, because metrics like L7 are highly correlated across days. For example, a user with L7 = 7 on a given day has either L7 = 6 or L7 = 7 the following day, which means L7 isn't a true daily independent variable. Such metrics are more likely to trigger false positive and false negative results. This limitation applies generally to stickiness and L-ness metrics. ## Customizing the DAU definition You can customize the DAU definition in the Statsig Console by specifying or excluding a set of Statsig and custom events. Find this setting in _Project Settings_. You need the required privileges to edit this setting. ![DAU definition configuration interface](https://docs.statsig.com/images/metrics/user/8239e1f5-133c-4ae2-914a-df5864159ccf.png) By default, all events qualify a user as active. There are two ways to customize this: 1. **Excluding specific events**: Some companies exclude specific events that aren't significant user interactions (for example, `homepage_visit` or `notification_sent`). Expand the event list and uncheck events you don't want to include. You can also toggle whether to include or exclude future events (not shown in the list). 2. **Including specific events**: Some companies use a narrow definition of an active user (for example, event = `login`). Select the set of events and turn off **Include New Events by Default**. Changes to the DAU definition take effect on the date of the change. Historical data remains unchanged. Statsig doesn't support backfill. Set your DAU definition before running any experiments or rolling out any features. ================================================================================ # Metric Directionality URL: https://docs.statsig.com/metrics/directionality ================================================================================ # Metric Directionality ## Setting metric directionality By default, Statsig assumes increases to a metric value are good and displays them in green in experiment results. For many metrics, a decrease is the wanted outcome: for example, page load times and most performance metrics. For these metrics, you can set the direction you want the metric to move, and experiment results update color-coding in metric lifts accordingly. To configure directionality, go to any metric detail view page. Select the **Edit Pencil** next to the _Directionality_ section in the right rail to open the **Set Metric Directionality** option. ![Metric directionality configuration interface](https://docs.statsig.com/images/metrics/directionality/fa0cbf9f-c84f-4db6-b9fa-84d672358a72.png) ================================================================================ # Metrics 301 - Real-time Analytics URL: https://docs.statsig.com/metrics/301 ================================================================================ # Metrics 301 - Real-time Analytics Analyze the sampled real-time events your application emits, build user funnels, and map user flows across your product with Statsig's real-time product analytics. This guide covers: 1. How to use [Events Explorer](https://docs.statsig.com/product-analytics/overview) to analyze sampled real-time events emitted by your application 2. How to [Create User Funnels](https://docs.statsig.com/metrics/create-user-funnels) 3. How to [Create User Flows](https://docs.statsig.com/metrics/create-user-flows) Statsig continues to add real-time and default product analytics features. > **Info:** > > **What's on the roadmap?** > > Join the > > [Statsig Slack channel](https://statsig.com/slack) > > to ask for previews of Statsig's upcoming features or to submit a request. Statsig builds most of the roadmap based on requests from customers! ================================================================================ # Funnel Metrics URL: https://docs.statsig.com/metrics/create-user-funnels ================================================================================ # Funnel Metrics Funnel metrics track how many users convert through a multi-step process, from a starting event to an end event. You can create a custom **funnel metric** from either the **Custom Metrics** creation wizard in the **Metrics Catalog** or through the **Charts** tab. ![Funnel metric creation interface](https://docs.statsig.com/images/metrics/create-user-funnels/172472515-c94b264c-85a6-4b78-bf12-769585e4880d.png) ## Components of Funnel Metrics Funnel metrics have the following components: 1. **Lineage**: Surfaces the events used to generate the funnel 2. **Metric Value**: Metric value represents the overall funnel conversion rate, or the percentage of users who complete a funnel (trigger the end event) relative to all users who start the funnel (trigger the starting event). 3. **Roll-up Window**: Statsig calculates funnel metrics daily. 4. **Conversion Rate between Stages**: This set of metrics track the percentage of users who triggered an event N relative to all users that triggered event N-1 in the funnel. ![Funnel components diagram](https://docs.statsig.com/images/metrics/create-user-funnels/172446711-5511e394-b353-4d38-97f1-1b681b67042b.png) After Statsig creates and populates funnels, you can view your funnel metric like any other metric in Pulse. You can also expand the funnel metric to view Pulse performance at each step in the funnel. ## User-based Funnel Metrics When counting distinct events, funnel metrics sum the number of events per day over the analysis period. When counting distinct users, funnel metrics sum the number of distinct users per day over the analysis period. For example, if a funnel consists of events A, B, and C in that order, user-based funnel metrics count the number of distinct users who triggered events A, B, and C on a given day. If you're tracking funnel conversion over multiple days, the daily granularity of funnel metrics may not suit your analysis. ## Example In the example below, the **Square** variant shows a lift in the **overall funnel conversion rate**. When you expand the metrics to examine the entire funnel, two key insights appear: - Both the **Square** and **Circle** variants show a lift in top-of-funnel DAU (_Land Page View Start DAU_). However, only the **Square** variant shows statistically significant increase in end-of-funnel DAU (_Purchase Event End DAU_). - The overall funnel conversion rate improvement for **Square** is primarily due to the higher conversion from _Checkout Event_ to _Purchase Event_ stages in the funnel. ![Funnel experiment results showing Square variant performance](https://docs.statsig.com/images/metrics/create-user-funnels/148440643-8e8a24bd-934d-4100-a15a-abcbcc4bb11c.png) ================================================================================ # User Flows URL: https://docs.statsig.com/metrics/create-user-flows ================================================================================ # User Flows Statsig's **User Flows** enable you to visualize customer journeys through your application. To create a **User Flow**, 1. Log into the Statsig console at https://console.statsig.com 2. On the left-hand navigation panel, select **Metrics** and then click on the **Charts** tab 3. Click on the **Create** button 4. Enter the chart name and start event of the User Flow that you want to visualize 5. Select the additional events that you want to include in the User Flow (Statsig automatically determines the sequence of events) 6. Enter the number of days that users typically take to complete these events 7. You can also optionally enter the depth of the flow to define the scope of your analysis 8. Click on **Create** to finish ![User flow creation interface](https://docs.statsig.com/images/metrics/create-user-flows/141128226-097e2441-e5ee-4e8d-8725-6d57d3fdeb83.png) If there is sufficient data for the User Flow, the chart appears in the console within a few minutes. ================================================================================ # Count Distinct Metrics URL: https://docs.statsig.com/metrics/count-distinct ================================================================================ # Count Distinct Metrics ## Purpose of count\_distinct The `count_distinct` metric reports the number of unique values at unit-level. At group-level, the mean is the sum of unit-level count distinct divided by the count of unique units exposed to the experiment. Because this metric relies on probabilistic HyperLogLog++ (HLL++) sketches, it carries a small estimation error (around 0.2%–0.3%), which may increase as the experiment window grows. By default, Statsig sets precision p = 12 for `count_distinct`. This precision provides good accuracy for most use cases while keeping results stable and resource usage efficient. > **Info:** > > Reach out to Statsig to enable sketch-based count distinct metrics for your project. ## For context, what are sketches Sketches are probabilistic summaries of large datasets. They answer certain queries approximately, quickly, and using little memory (often a fixed-size or sublinear footprint, such as O(log n) or even constant space regardless of dataset size). ## Core principles of HLL++ 1. **Hashing and Leading Zeros** - HLL++ hashes each input uniformly into a 64-bit integer. - The position of the first 1-bit in the hash (the "rank") provides an estimate of how many distinct items precede that hash in sorted order. 2. **Register Array** - The algorithm allocates _m_ registers, where _m_ = 2^p and _p_ is the precision parameter. - Each hashed value maps to one register. The register stores the maximum rank seen so far for values mapped to it. 3. **Sparse and Dense Modes** - **Sparse mode** applies when the number of distinct items is below 2^(p+5). It keeps an exact list of non-zero registers in a compact form. This yields near-zero error for small cardinalities. - **Dense mode** applies when the count exceeds the sparse limit. HLL++ represents the sketch as a fixed array of _m_ registers, each one byte in size. Error increases slightly but remains tightly bounded. 4. **Estimation and Bias Correction** - HLL++ computes the raw estimate as the harmonic mean of 2^(–register\_value) across all registers, multiplied by a constant factor (alpha\_m). - BigQuery applies empirical bias corrections and the HIP (historic inverse probability) estimator to reduce variance and worst-case error. ## Precision, memory, and error relationship The precision parameter _p_ controls the number of registers _m_ and thus the sketch's size and accuracy: | Precision p | Registers m = 2^p | Memory per Sketch | Approximate Relative Standard Error (1 sigma) | | --- | --- | --- | --- | | 10 | 1,024 | ~1 KB | 0.83 / sqrt(1,024) ≈ 2.6 % | | 12 | 4,096 | ~4 KB | 0.83 / sqrt(4,096) ≈ 1.3 % | | 13 | 8,192 | ~8 KB | 0.83 / sqrt(8,192) ≈ 0.92 % | | 15 | 32,768 | ~32 KB | 0.83 / sqrt(32,768) ≈ 0.46 % | - Memory used grows linearly with _m_. - Error decreases as the inverse square root of _m_. - To halve the error, you must quadruple the number of registers. ### Examples of thresholds and steady‑state for common precisions - **p = 10** (_m_ = 1,024 registers, ~1 KB): - Sparse limit: 2^(10+5) = 32,768 distincts (error ≈ 0%). - Plateau begins at ~5·m = 5,120 distincts. - Steady‑state error: 0.83/√1,024 ≈ 2.6%. - **p = 12** (_m_ = 4,096 registers, ~4 KB): - Sparse limit: 2^(12+5) = 131,072 distincts. - Plateau begins at ~5·m = 20,480 distincts. - Steady‑state error: 0.83/√4,096 ≈ 1.3%. - **p = 15** (_m_ = 32,768 registers, ~32 KB): - Sparse limit: 2^(15+5) = 1,048,576 distincts. - Plateau begins at ~5·m = 163,840 distincts. - Steady‑state error: 0.83/√32,768 ≈ 0.46%. ## Error behavior over cardinality The relative error of an HLL++ sketch evolves through three phases: - **Exact Counting Phase** - Cardinality ≤ 2^(p+5). The sketch operates in sparse mode with error close to 0%. - **Bias Ramp Phase** - Cardinality between 2^(p+5) and approximately 5·m. The sketch is in dense mode. Systematic bias increases gradually from near 0 up to the maximum bound. - **Steady-State Phase** - Cardinality ≥ 5·m. Relative error stabilizes at the theoretical bound of 0.83 / sqrt(m). When in this phase, adding more distinct items doesn't change the sketch's register distribution shape, so the error remains effectively constant. In other words, after enough uniques, the sketch "plateaus," and error fluctuations stay within the estimator's minimal random variance around that fixed bound. ### Example for p = 15 (m = 32,768) - **Exact in sparse mode (≤ 1,048,576 items)**: For up to 2^(p+5) = 2^20 = 1,048,576 distinct elements, HLL++ uses a compact "sparse" representation that records individual hashes directly, resulting in an exact count (0% error). - **Transition to dense mode & rising error**: Beyond 1,048,576 distinct elements, it switches to the full register array of size m = 2^p = 32,768. In this _dense_ regime, the Relative Standard Error (RSE) gradually increases from 0% to its theoretical limit. - **Asymptotic error plateau (≈ 0.46%)**: When in dense mode, the RSE quickly converges to RSE ≈ 0.83/√m = 0.83/√32,768 ≈ 0.46%, and remains at approximately 0.46% regardless of further increases in distinct count. ## Merging sketches over time or partitions To compute distinct counts across multiple segments (for example, daily sketches), merge sketches by taking the element-wise maximum of their registers. This operation is associative and idempotent. Merged sketches preserve the same error bound as individual sketches and don't add additional error. ## Mathematical formulation 1. **Raw Estimate** - _M\[i\]_ is the value of register _i_. - _alpha\_m_ is a bias correction constant dependent on _m_. This is the core HyperLogLog "raw" estimator for the number of distinct elements in a multiset. You take each register value M\_i, compute $2^{-M_i}$, sum those values, invert that sum, and multiply by m^2 (where m is the number of registers) to get a harmonic-mean-based estimate. The bias-correction constant α\_m then scales this value. In effect, this formula transforms the observed distribution of leading-zero counts into an approximate count of unique items. 2. **HIP Estimator** - Maintains a running sum of inverse probabilities for each new distinct element. - Produces lower variance and a smaller worst-case error constant (0.83 instead of 1.04). 3. **Relative Standard Error (RSE)** RSE ≈ 0.83/√m ## Best practices and limitations - Choose precision _p_ based on the maximum expected cardinality and your error tolerance. (Statsig sets this for you by default.) - After Statsig creates a sketch with precision _p_, you can't increase its precision. You can only merge or downsample sketches to lower precision. - Long keys or complex objects increase CPU and memory in sparse mode but don't affect dense mode size. - Plan for a noise floor equal to the sketch's relative error when designing experiments or setting thresholds. - Reach out if you believe you require higher precision. ## Summary and recommendations HLL++ sketches provide efficient, bounded-error approximations for `count_distinct` queries, trading a small, predictable error for large savings in memory and compute. - Memory scales as O(m) rather than O(n). - Error scales as O(1/√m). - Merging sketches is exact for unions, with no extra error. Select the smallest precision _p_ that meets your accuracy requirements to minimize storage and computation costs. ## Choosing precision for your cardinality When you know the maximum number of unique items (cardinality) ahead of time, pick a precision _p_ so that **5 · 2^p** exceeds that cardinality. This ensures the sketch is in its steady‑state phase, where the relative error remains at the bound of 0.83/√(2^p). - **Up to 10,000 uniques** - _p_ = 12 (m = 4,096 registers) → memory ~4 KB - Steady state from ~20,480 distincts (5·m) onward - Relative error ≈ 0.83/√4,096 ≈ 1.3 % - **Up to 50,000 uniques** - _p_ = 13 (m = 8,192 registers) → memory ~8 KB - Steady state from ~40,960 distincts onward - Relative error ≈ 0.83/√8,192 ≈ 0.92 % - **Up to 100,000 uniques** - _p_ = 15 (m = 32,768 registers) → memory ~32 KB - Steady state from ~163,840 distincts onward - Relative error ≈ 0.83/√32,768 ≈ 0.46 % - **Up to 500,000 uniques** - _p_ = 16 (m = 65,536 registers) → memory ~64 KB - Steady state from ~327,680 distincts onward - Relative error ≈ 0.83/√65,536 ≈ 0.32 % - **Up to 1,000,000 uniques** - _p_ = 17 (m = 131,072 registers) → memory ~128 KB - Steady state from ~655,360 distincts onward - Relative error ≈ 0.83/√131,072 ≈ 0.23 % - **General rule** 1. Compute _m_ = 2^p 2. Ensure **5·m ≥ expected cardinality** 3. Verify memory footprint (_m_ bytes) fits your budget 4. Confirm relative error (0.83/√m) meets your accuracy target ## How count\_distinct fits into your workflow `count_distinct` provides a consistent way to measure breadth at scale. Define a metric once, use it anywhere, and merge across time and partitions with stable behavior. The metric produces answers to “How many unique X?” without requiring custom ETL or one-off SQL. ================================================================================ # Parameter Stores URL: https://docs.statsig.com/client/concepts/parameter-stores ================================================================================ # Parameter Stores Parameter Stores provide a way to organize and manage parameters in your web or mobile app through the Statsig console. Available for JS, React, React Native, Android, iOS, and Dart SDKs on the client side and Java, Node, Python, and Rust on the server side. Reach out in [Slack](https://statsig.com/slack) if you want support for a specific language. ## What is a Parameter Store Rather than thinking in terms of Statsig entities like Feature Gates, Experiments, Layers, or Dynamic Configs, Parameter Stores let you focus on **parameters**. Parameters are the values in your app that need to be configurable remotely. Parameter Stores **decouple your code from configuration**. This abstraction lets you run experiments, adjust gating, or change values dynamically **without hardcoding any experiment or gate names**. Instead, you define parameters that you can remap remotely to any value or any Statsig entity. ## An example: parameterizing the Statsig website Release cycles are often more constrained on mobile platforms. As an example, the Statsig website marketing team frequently requests updates, so the team parameterizes text, images, buttons, colors, and more: ![Parameter Store Mapping](https://docs.statsig.com/images/tutorials/parameter-stores/param_stores_mapping.png) To run an experiment, point these variables directly at experiments to start an A/B test without writing any code: ![Parameter Store Experiment Mapping](https://docs.statsig.com/images/tutorials/parameter-stores/param_stores.gif) The experiment on the tagline is now running without any code change. Access the parameter in code like this: ```javascript const homepageStore = StatsigClient.getParameterStore("www_homepage"); const tagline = homepageStore.get("tagline", <optional_default_value>); ``` ## How to use Parameter Stores Here’s a suggested workflow: 1. **Create a Parameter Store**: Set up a Parameter Store for your team or project. Parameter Stores hold related parameters in one object. 2. **Identify Configuration Variables**: Consider which variables you want to decouple from your app and control through Statsig rather than hardcoding them in your app. These could include: - A boolean parameter to control access to a new feature. Even if you're used to using Feature Gates for boolean feature management, start with a boolean parameter instead. - A string parameter for text resources that you may want to swap or experiment with. - A number parameter for inputs such as the number of onboarding steps, a list length to truncate, and more. 3. **Start with Static Values**: Begin with a static value for each parameter (what you would have hardcoded in the app). Use this static value initially. 4. **Remap When Ready**: After you ship your app and the feature is ready, remap the parameter to a Feature Gate, Experiment, Dynamic Config, or Layer to test and target different variants. 5. **Update in Real-Time**: After experimenting, you can update the static value or gate the feature for specific app versions. You can do this in real time across mobile apps that you've already released. ## Why use Parameter Stores Parameter Stores draw inspiration from solutions such as Facebook’s Mobile Config, Uber’s experimentation approach, and Firebase Remote Config. Leading mobile companies use these patterns to: - Move faster - Maintain backward compatibility - Experiment more freely The extra setup in the Statsig console takes more initial effort than creating a gate, but saves time after you ship the app. Parameter Stores ensure you don't hardcode any Statsig entity values, giving you flexibility to update parameters without a new release. This is particularly useful for mobile apps, where app store release cycles create delays unlike backends or websites. ## Supported SDK versions The following SDKs support Parameter Stores: - **Android SDK** v4.33.0+ - **iOS SDK** v1.45.0+ - **@statsig/js-client**, **@statsig/react-bindings**, **@statsig/react-native-bindings**, **@statsig/expo-bindings** v1.4.0+ - **Dart SDK** v1.2.1+ - **Statsig Server Core SDKs** are gradually adding support, available in: - **com.statsig:javacore** 0.1.0+ - **statsig-rust** 0.1.0+ - **@statsig/statsig-node-core** 0.1.0+ - **statsig-python-core** 0.5.0+ - **statsig-dotnet-core** 0.6.1+ Non-server-core server SDKs don't support Parameter Stores, and Parameter Stores aren't available when bootstrapping a client SDK from one of those SDKs. For support in a specific language, reach out in [Slack](https://statsig.com/slack). --- ================================================================================ # Build your first Device-level Experiment URL: https://docs.statsig.com/guides/first-device-level-experiment ================================================================================ # Build your first Device-level Experiment Device-level experiments randomize assignment on a consistent identifier for the user's device instead of a user ID, so you can test users you can't identify through a login. Statsig generates a stable ID automatically, though it recommends using your own cookie or logged-out ID when possible. Use device-level experiments for anonymous or first-time users and to keep the same experience on a device regardless of sign-in status. Device-level experiments are ideal in scenarios such as: - **Anonymous or first-time users**: When users haven't signed in yet or are browsing anonymously. - **Cross-device consistency**: Ensuring the same experience on the same device, regardless of user sign-in status. You can implement a device-level experiment almost exactly like a traditional user-level experiment. The key difference is setting the experiment’s ID type. This example uses `stableID` as the ID type, but you can substitute your own identifier if you have one. ## Step 1: Create a device-level experiment 1. **Log into the Statsig Console**: Visit [Statsig Console](https://console.statsig.com/) and navigate to **Experiments+** on the left-hand sidebar. 2. **Create a New Experiment**: - Click on **Create** and fill out the **name** and **description** of your experiment. - Enable the **Use Stable ID** option during setup. - Click **Create** to proceed. ![Stable ID Setup](https://docs.statsig.com/images/tutorials/device-level-experiment/device-level-stable-id.png) 3. **Define Experiment Metrics**: Add a hypothesis, primary metrics, and secondary metrics in the **Scorecard** section, the same as for a user-level experiment. 4. **Set Groups and Parameters**: - In the **Groups** section, define the parameters for your experiment. For instance, you can experiment with a simple boolean parameter like `"enabled"`. ![Experiment Groups](https://docs.statsig.com/images/tutorials/device-level-experiment/device-level-groups.png) 5. **Set Allocation**: - By default, the experiment targets 100% of your user base. Adjust the allocation if needed. Start with a smaller rollout until you're confident in the new variant. ![Allocation Panel](https://docs.statsig.com/images/tutorials/device-level-experiment/device-level-allocation.png) 6. **Save and Start**: After you've configured everything, click **Save** to finalize your experiment. When you're ready to launch, click **Start** to roll it out. ## Step 2: Initialize the SDK in your application After setting up your experiment in the Statsig console, integrate it into your client application using one of Statsig’s SDKs. **Important:** - Set **`userID`** only for authenticated, logged-in users. - For logged-out or anonymous users, use **`stableID`** (Statsig’s auto-generated device ID) or your own custom deviceID to identify the device. Refer to [customID types](https://docs.statsig.com/guides/experiment-on-custom-id-types) if you have your own deviceID. - Always pass all known IDs to the SDK. Statsig uses the correct one for evaluation based on the experiment or gate’s ID type. - If you do rely on stableID, only Statsig client SDKs (javascript, react, mobile, etc) generate it. Server SDKs can't generate this ID for you. - **User attributes**: You can pass additional attributes like `appVersion`, and `custom` properties for experiment targeting. ### Example (JavaScript) ```javascript const user = { userID: userID: isLoggedIn() ? getLoggedInUserID() : undefined, // Optional attributes to help with targeting appVersion: "1.0.0", custom: { promoCode: "New30Off" } }; // Initialize the Statsig Client const client = new StatsigClient(sdkKey, user, { environment: { tier: "production" } }); await client.initializeAsync(); ``` > **Info:** > > If your app collects other relevant attributes (e.g., device type, region), pass them in the `user` object to improve experiment precision. ## Step 3 (Optional): Update user info for logged-in users When a user signs in or creates an account, call the SDK’s updateUser method to attach userID and other logged-in attributes. This enables user-level experiments and gates to evaluate with the authenticated identifier. ### Example (JavaScript) ```javascript const updatedUser = { ...user, // continue to send the deviceID! userID: loggedInID, email: signUpEmail }; // Update the user object await client.updateUserAsync(user); ``` > **Note:** > > When you add userID after login, user-level experiments and gates can target and evaluate using userID. _Device-level_ experiment evaluations remain based on stableID (or deviceID) and don't change when you add userID, as long as you continue to pass that identifier as well! This preserves consistency of device-level bucketing. --- ================================================================================ # Experiment on custom Unit ID types URL: https://docs.statsig.com/guides/experiment-on-custom-id-types ================================================================================ # Experiment on custom Unit ID types A custom Unit ID randomizes experiment bucketing on an identifier you choose, such as `companyID`, `accountID`, or a device ID, instead of the default `userID` or Statsig-generated Stable ID. For example, a task management tool can bucket by `companyID` so everyone at the same company gets the same experience and you measure impact at the company level. Use a custom Unit ID for B2B, session-level, or group-level experiments and feature gates. ### When to use custom Unit IDs - **Organization-wide experiments**: Group users by `companyID` for company-wide consistency. - **Session-based experiments**: Use a session or device ID to control the experiment within a specific session. - **Group-level rollouts**: Target teams, regions, or other specific cohorts using a relevant ID type. Follow these three steps to set up an experiment with a custom Unit ID. The following examples use `companyID`, but you can replace it with any ID relevant to your use case. > **Note:** > > These steps also apply to feature gates, allowing you to partially roll out features based on custom Unit IDs. --- ### Step 1: Add `companyID` as a custom Unit ID 1. **Log into the Statsig Console**: Go to [Statsig Console](https://console.statsig.com/) and navigate to **Project Settings**. 2. **Find Custom Unit IDs**: Under _Manage Account > Info_, look for the **Custom Unit IDs** section. ![Custom Unit ID Settings](https://docs.statsig.com/images/tutorials/custom-id-types/console-add-custom-id.png) 3. **Add a New Custom Unit ID**: - Click the **Edit** button. - Enter `companyID` as the new ID type and provide a description. - Save the changes. ![Add Custom ID](https://docs.statsig.com/images/tutorials/custom-id-types/custom-id-add.png) After adding a custom Unit ID, you can use it across all Statsig configurations: experiments, gates, layers, dynamic configs, and autotunes. You only need to configure it once per project. ### Step 2: Select `companyID` as the ID type in your experiment 1. **Create a New Experiment**: - Navigate to **Experiments+** in the Statsig Console. - When setting up a new experiment, find the **ID Type** dropdown and select `companyID`. ![Select Custom ID Type](https://docs.statsig.com/images/tutorials/custom-id-types/custom-id-selection.png) 2. **Complete Experiment Setup**: - Finish configuring your experiment as you would for any [user-level experiment](https://docs.statsig.com/guides/abn-tests). - Define your hypothesis, metrics, and target audience. After completing the setup, click **Save**. When you choose the right custom Unit ID, Statsig places all users with the same `companyID` in the same experiment group, which makes it easier to measure performance at the group level. --- ### Step 3: Provide `companyID` in the Statsig SDK To use the custom Unit ID in your application, provide it when initializing the Statsig SDK. The `customIDs` field in the Statsig user object lets you pass the `companyID` (or any other custom ID) along with the usual user information. #### Example (JavaScript) ```javascript var user = { userID: "some_user_id", // Standard user identifier customIDs: { companyID: "some_company_id" // Custom ID for grouping }, // Other attributes (optional) email: "user@example.com", appVersion: "1.0.0" }; // Initialize the Statsig Client const client = new StatsigClient(sdkKey, user); await client.initializeAsync(); ``` - **`customIDs` field**: This allows you to pass a dictionary of custom IDs, including `companyID`, to ensure the experiment targets users based on that ID. After providing the necessary IDs in the SDK, you can start logging events and fetching experiment configurations based on the custom Unit ID. --- ================================================================================ # Environment-based Evaluation URL: https://docs.statsig.com/guides/using-environments ================================================================================ # Environment-based Evaluation Statsig SDKs let you set the environment tier for your app during initialization. Setting the environment tier lets you evaluate feature gates, dynamic configs, and experiments differently in non-production environments like development or staging. Configure the appropriate environment in your code and adjust feature rules in the Statsig Console. --- ## Configure environments in the SDK There are two key ways to set up environments within your app: 1. **Environment-specific SDK keys**: These determine which rule sets the SDK downloads based on the environment. 2. **Environment tier at SDK initialization**: This defines how Statsig evaluates rules for the app. ### 1. Environment-specific SDK keys Environment-specific SDK keys control which rules Statsig sends to the SDK. For example, an SDK initialized with a development environment key doesn't receive rules set for staging or production environments. For more information, go to [Per-Environment API Keys](#per-environment-api-keys) below. ### 2. Environment tier parameter SDK keys can correspond to multiple environments. Explicitly set the environment tier during SDK initialization to ensure Statsig applies the correct rules. All SDKs accept an `SDK Key` and an optional `StatsigOptions` dictionary. The `StatsigOptions` parameter includes the `environment` key, which has a `tier` field. This tier corresponds to one of your pre-configured environments (e.g., development, staging). > **Note:** > > If the environment tier is unset, all checks and event logs default to "production." Here's an example of setting the environment tier in your code for the **development** environment: #### Example (JS Client SDK) ```javascript const client = new StatsigClient(<SDK_KEY>, user, { environment: { tier: 'development' } }); ``` #### Example (Node Server SDK) ```javascript await statsig.initialize(<SDK_KEY>, { environment: { tier: 'development' } }); ``` Go to your language-specific SDK documentation for details. --- ## Using environments in feature gates To configure environment-specific rules for a feature gate, follow these steps: 1. **Create a new feature gate**: In the Statsig Console, create a new Feature Gate. For example, name it "development mode" to target only your development environment. ![Feature Gate](https://docs.statsig.com/images/tutorials/environments/environments-feature-gate.png) 2. **Specify environments**: When configuring the rule, check the **Specify Environments** box and select the environments you want to target. By default, Statsig enables rules for all environments unless you specify otherwise. ![Specify Environment](https://docs.statsig.com/images/tutorials/environments/environments-specify.png) 3. **Save your settings**: After saving, the environments where you enabled the rule appear below the rule name. ![Enabled Environments](https://docs.statsig.com/images/tutorials/environments/environments-enabled.png) You can also filter rules by environment using the filter in the upper-right corner of the Feature Gate UI. To edit the target environments of a rule, click **...** next to the rule name and select **Edit Rule**. ![Edit Rule](https://docs.statsig.com/images/tutorials/environments/environments-edit-rule.png) --- ## Configuring environments By default, Statsig provides three environments: **Development**, **Staging**, and **Production**. You can add more environments or rename the default ones, but you can't delete or modify the **Production** environment. ### Steps to add or edit environments 1. Go to **Project Settings** → [**Environments & Keys**](https://console.statsig.com/api_keys). ![Project Settings](https://docs.statsig.com/images/tutorials/environments/environments-project-settings.png) 2. Click **Edit** to add new environments or reorder the existing ones using drag-and-drop. ![Edit Environments](https://docs.statsig.com/images/tutorials/environments/environments-edit-environments.png) > **Note:** > > Reordering environments doesn't affect any rule logic, but it helps convey the rollout hierarchy (e.g., development → staging → production) to your teams. --- ## Per-environment API keys Statsig lets you create per-environment API keys to enhance security and privacy. SDKs initialized with a specific environment key only access the rules relevant to that environment. ### Steps to generate environment-specific API keys 1. Go to **Project Settings** → [**Environments & Keys**](https://console.statsig.com/api_keys). 2. Click **Generate New Key** and specify the environment for which you want to generate the API key. ![Generate API Key](https://docs.statsig.com/images/tutorials/environments/environments-generate-key.png) > **Note:** > > The default environments (Development, Staging, and Production) share the same server and client-side API keys. You can generate new keys for custom environments as needed. --- ================================================================================ # Ingesting Open Telemetry Data URL: https://docs.statsig.com/server/concepts/open_telemetry ================================================================================ # Ingesting Open Telemetry Data > **Tip:** > > Setting up OTEL can be complex. If you have questions, contact the Statsig team on Slack. ## How OpenTelemetry integration works This guide walks you through setting up the OpenTelemetry Collector in your Kubernetes environment and configuring it to send telemetry data to Statsig using the official `otlphttp` exporter. --- ## ✅ Prerequisites - A running Kubernetes cluster (e.g., GKE, EKS, Minikube, etc.) - Helm installed, or another mechanism to apply helm charts to your cluster, like ArgoCD - API Access to a Statsig project with a Server SDK Secret Key - Optional: `kubectl` configured and connected to the cluster, for validating and debugging setup --- ## 1. Setup OpenTelemetry Collector on Kubernetes The recommended setup follows the official OpenTelemetry Kubernetes guide to install the OpenTelemetry Collector in both **DaemonSet** and **Deployment** modes using the official Helm chart. Tested `values.yaml` files for both deployment modes are available in Step 3. **📘 Official Guide:** [OpenTelemetry Collector for Kubernetes – Getting Started](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/) ### Why both - **DaemonSet Collector**: Runs one instance per node to collect host-level telemetry (e.g., logs, pod and node metrics). - **Deployment Collector**: Runs one instance per cluster to gather telemetry related to the cluster as a whole. Configure at least the receivers below for a useful Statsig-powered observability platform for your Kubernetes workloads. The setup uses [Presets](https://opentelemetry.io/docs/platforms/kubernetes/helm/collector/#presets) from the official chart and customizes some components, as shown in the sample values files in Step 3. - Minimum for scraping logs: - [Filelog Receiver](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/#filelog-receiver) - [Kubernetes Attributes Processor](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/#kubernetes-attributes-processor) - Minimum for scraping kubernetes metrics - [KubeletStats Receiver](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/#kubeletstats-receiver) - [Kubernetes Cluster Receiver](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/#kubernetes-cluster-receiver) - Minimum for metrics about Otel Collector itself - [OTLP Receiver](https://opentelemetry.io/docs/platforms/kubernetes/getting-started/#otlp-receiver) for [scraping internal metrics](https://opentelemetry.io/docs/collector/internal-telemetry/#configure-internal-metrics) (alternatively scraped through prometheus receiver) --- ## 2. Configure exporting telemetry to Statsig with OTLP HTTP Exporter Statsig supports receiving OTLP-formatted, JSON-encoded telemetry at the endpoint `https://api.statsig.com/otlp`. The OpenTelemetry Collector supports sending telemetry to the Statsig endpoint using the official `otlphttp` exporter. ### Authentication Statsig authenticates requests using the request header `statsig-api-key` and a valid SDK Server Secret key generated from [console.statsig.com](http://console.statsig.com) (under _Settings > Keys & Environments_). Keep your secret key secure using a Kubernetes Secret management provider and make it available to the OpenTelemetry collector pod’s environment. ### Example Exporter Config ```yaml exporters: otlphttp: endpoint: https://api.statsig.com/otlp encoding: json headers: statsig-api-key: ${env:STATSIG_SERVER_SDK_SECRET} ``` ## 3. Example Helm Chart Values for a quick and correct setup The following two complete and tested `values.yaml` configurations work with the OpenTelemetry Helm charts: ### 🔗 Deployment Collector 👉 [values-gateway.yaml](https://gist.github.com/karan-statsig/d5c70b7fd100ab445985b620dcb7e8c6) ### 🔗 DaemonSet Collector 👉 [values-agent.yaml](https://gist.github.com/karan-statsig/f02ee95fef00aecde402829b5a4c60e8) Use them with the Helm chart version `0.75.1` like this: ```yaml helm repo add open-telemetry https://open-telemetry.github.io/opentelemetry-helm-charts helm repo update # Install Deployment Collector helm install otel-deployment open-telemetry/opentelemetry-collector \ --version 0.75.1 \ -f values-gateway.yaml -n otel --create-namespace # Install DaemonSet Collector helm install otel-daemonset open-telemetry/opentelemetry-collector \ --version 0.75.1 \ -f values-agent.yaml -n otel ``` ## 4. Verify the Setup Check that all pods are running: ```bash kubectl get pods -n otel ``` Check logs for a specific collector pod and confirm no errors appear: ```bash kubectl logs -n otel $pod_name ``` ## 5. Explore Explore your logs and metrics at [console.statsig.com](http://console.statsig.com) using the Logs Explorer and Metrics Explorer products under _Analytics_ in the sidebar. --- ## 🔗 Resources - [OpenTelemetry Collector Documentation](https://opentelemetry.io/docs/collector/) - [Important Concepts for Kubernetes](https://opentelemetry.io/docs/platforms/kubernetes/collector/components/) - [Helm Chart Reference](https://github.com/open-telemetry/opentelemetry-helm-charts) - [Collector Configuration Reference](https://opentelemetry.io/docs/collector/configuration) - [OTLP Protocol Specification](https://opentelemetry.io/docs/specs/otlp/) ================================================================================ # Testing your Gates/Experiments URL: https://docs.statsig.com/guides/testing ================================================================================ # Testing your Gates/Experiments Statsig gives you three ways to test feature gates and experiments before you ship: overrides, unit testing with local mode, and non-production environments. Overrides set specific gate, experiment, or holdout values without affecting live data. Local mode runs the SDK offline against mocked configs for unit tests. Environments let you evaluate rules in Development or Staging before Production. --- ## Overrides: test features, experiments, or holdouts Overrides allow you to manually configure [features](https://docs.statsig.com/feature-flags/overrides#adding-an-override), [experiments](https://docs.statsig.com/experiments/setup/overrides), or [holdouts](https://docs.statsig.com/experiments/holdouts-introduction) for testing. This method enables safe testing without affecting live production data or skewing experiment results. Statsig excludes overrides from Pulse analysis to maintain unbiased results. - Use **Segments** to target overrides to pre-production environments or specific groups (e.g., employees) for testing. ![Feature Override Example](https://docs.statsig.com/images/tutorials/testing/testing-feature-override.png) ![Experiment Override Example](https://docs.statsig.com/images/tutorials/testing/testing-experiment-override.png) For more details on adding overrides, go to: - [Feature Overrides](https://docs.statsig.com/feature-flags/overrides#adding-an-override) - [Experiment Overrides](https://docs.statsig.com/experiments/setup/overrides) - [Holdout Overrides](https://docs.statsig.com/experiments/holdouts-introduction) --- ## Unit testing with Statsig Statsig's server SDKs offer a `localMode` feature that disables network access, ensuring that tests run locally and independently of production systems. When `localMode` is active, the SDK returns default values, allowing you to mock features and experiments in a controlled test environment. ### Override APIs for testing You can use the `overrideGate` and `overrideConfig` APIs to set specific overrides for users or globally during testing. ```js function overrideGate( gateName: string, value: boolean, userID?: string, ): void; ``` ```js function overrideConfig( configName: string, value: object, userID?: string, ): void; ``` For example, to override a gate for testing: ```js statsig.overrideGate("example_gate", true); ``` - For more information on mocking Statsig for testing, go to [Node.js Server SDK](https://docs.statsig.com/server/nodejsServerSDK#how-can-i-mock-statsig-for-testing) or [JavaScript Client SDK](https://docs.statsig.com/client/javascript-sdk#testing). --- ## Environments: configuring Development, Staging, and Production Statsig lets you assign environments to feature gates, experiments, and events. By default, Statsig assigns checks without a defined environment to **Production**. You can customize environments (such as **Development**, **Staging**, or **Production**) and use them to target different versions of feature gates or segments. - Non-production events appear in diagnostics and Statsig uses them to track cumulative exposures and metric results when testing experiments in lower environments with **Enable for Environments**. Statsig prioritizes production data for final Pulse result analyses. ### Customizing environments You can map your internal environments to Statsig's built-in environments or create custom mappings. Common setups include: - Assigning Dev One boxes to **Development**. - Creating an **Early Access** slice (e.g., 1% of production users) as part of the **Production** environment for phased rollouts. For more details on environments, go to the [Statsig blog post](https://blog.statsig.com/environments-on-statsig-6a818805b3c2). --- ================================================================================ # Migration Overview URL: https://docs.statsig.com/guides/migration-overview ================================================================================ # Migration Overview Migrating to Statsig moves your events, feature flags, experiments, and decision workflows into one platform and a single source of truth. The process runs in four phases: audit and plan, set up live data, import historical data, then validate and decommission your legacy tool. For provider-specific steps, refer to the LaunchDarkly and Mixpanel guides. ## Migration phases ### 1. Audit and plan - Identify the datasets, events, and feature flags you want to move - Decide what needs full historical backfill vs. what can start fresh - Document any dashboards or KPIs that need rebuilding in Statsig ### 2. Set up live data - Implement Statsig SDKs to start streaming new events and feature flag evaluations - Validate critical events are firing with the correct schema - Use Statsig for the newly recorded events and flags ### 3. Import historical data - Export data from your existing tool (S3 or warehouse is preferred) - Transform the schema to Statsig's event format (`event`, `user`, `timestamp`, `metadata`) - Import using Statsig's Event Webhook, S3 ingestion, or warehouse ingestion ### 4. Validate and decommission - Compare metrics between your legacy tool and Statsig to ensure parity - Rebuild dashboards and charts in Statsig - Decommission old pipelines once Statsig is your single source of truth ## Best practices - **Start small**: Run a pilot project or test migration before backfilling all history - **Align IDs early**: Ensure `userID` and `stableID` mapping is consistent. Identity mismatches are the most common failure point - **Shard historical imports**: Break large datasets into daily partitions for stability - **Rebuild insights intentionally**: Don't port all events and flags directly. Use migration as a chance to clean up stale data - **Plan change management**: Teams need time to adjust workflows, queries, and dashboards, so migrate for 1-2 teams before championing in the broader org ## Provider-specific guides - [Migrate from Mixpanel](https://docs.statsig.com/guides/migrate-from-mixpanel) - [Migrate from LaunchDarkly (Feature Flags)](https://docs.statsig.com/guides/migrate-from-launchdarkly) - Additional guides coming soon ## Get help Statsig has helped many customers migrate from other tools. For tailored guidance, reach out to the support team, your sales contact, or through the [Slack community](https://statsig.com/slack). ================================================================================ # Migrate your analytics data from Mixpanel URL: https://docs.statsig.com/guides/migrate-from-mixpanel ================================================================================ # Migrate your analytics data from Mixpanel Migrate your Mixpanel event data into Statsig in three steps: export raw events from Mixpanel, transform them into Statsig's event format, then ingest them into your Statsig project. After your events land in Statsig, you work in a single platform that combines analytics, experimentation, and feature flagging. This guide covers the essentials; for anything beyond these basics, contact Statsig. > **Note:** > > This guide covers only importing raw events into Statsig. Statsig doesn't support importing user/group profiles, dashboards, reports, etc. After your raw events are in the Statsig project, you can re-create your critical dashboards there. ## Step 1. Export your data from Mixpanel Mixpanel offers a few different export methods. Pick the one that matches your data size and setup: **1. CSV Export** Export small batches of events as CSV using the Events tab → query events → click "Export" button. **2. Export API** Use Mixpanel's [Raw Event Export API](https://developer.mixpanel.com/reference/raw-event-export) to pull JSONL data: - **Limit**: Export one day's data at a time for optimal performance - **Format**: JSONL where each line is a valid JSON object ```bash curl --location --request GET 'https://data.mixpanel.com/api/2.0/export?from_date=2023-01-01&to_date=2023-01-01' \ -u '{project_id}:{service_account_secret}' ``` **3. Data Pipelines (Bulk Export)** For large data volumes, use Mixpanel's [Data Pipelines](https://docs.mixpanel.com/docs/data-pipelines) feature to export to: - Cloud Storage (AWS S3, Google Cloud Storage, Azure Blob Storage) - Data Warehouse (BigQuery, Redshift, Snowflake) ## Step 2. Transform your data Mixpanel and Statsig store events in slightly different formats. Map your Mixpanel data to Statsig's format: | Mixpanel field | Statsig field | | --- | --- | | `event` | `event` | | `properties.time` | `timestamp` (ms since epoch) | | `properties.distinct_id` or `properties.user_id` | `user.userID` | | `properties.device_id` | `user.stableID` | | `properties.*` (other fields) | `metadata` | **Before transform** ```json // Mixpanel event { "event": "Signed up", "properties": { "time": 1618716477, "distinct_id": "user-123", "device_id": "xyz", "Referred_by": "Friend", "URL": "website.com/signup" } } ``` **After transform** ```json // Statsig event { "event": "Signed up", "user": { "userID": "user-123", "stableID": "xyz" }, "timestamp": 1618716477000, "metadata": { "Referred_by": "Friend", "URL": "website.com/signup" } } ``` ## Step 3. Import into Statsig After your data is in Statsig event format, choose an import path: | If you exported from Mixpanel through... | Import into Statsig using... | Best when... | | --- | --- | --- | | S3 export | [S3 ingestion](https://docs.statsig.com/data-warehouse-ingestion/s3) | You're backfilling large datasets | | Warehouse (Snowflake/BigQuery/Redshift) | [Warehouse ingestion](https://docs.statsig.com/data-warehouse-ingestion/introduction) | Your Mixpanel data already lives in a warehouse | | Export API | [Event Webhook](https://docs.statsig.com/http-api/overview) | You're moving a few days/weeks of data programmatically | | CSV download | [Event Webhook](https://docs.statsig.com/http-api/overview) | You're testing or moving a small slice of data | **Event Webhook (for API/CSV exports)** ```bash curl -X POST https://api.statsig.com/v1/webhooks/event_webhook \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: $STATSIG_SERVER_SECRET" \ -d '{ "event": "Signed up", "user": { "userID": "user-123", "stableID": "xyz" }, "timestamp": 1618716477000, "metadata": { "Referred_by": "Friend", "URL": "website.com/signup" } }' ``` ### Important notes - **S3 ingestion**: Shard your Mixpanel data into 1 day's data per directory for Statsig - **Scale gradually**: After small tests, backfill in chunks to manage loads - **Future tracking**: After historical import, switch Mixpanel code calls to Statsig SDKs ## Get migration help If you're unsure how to approach this migration, contact the Statsig team. Statsig has experience helping customers migrate from Mixpanel. Reach out to the support team, your sales contact, or through the [Slack community](https://statsig.com/slack). ================================================================================ # LaunchDarkly Migration Guide URL: https://docs.statsig.com/guides/migrate-from-launchdarkly ================================================================================ # LaunchDarkly Migration Guide Migrate your feature flags and rollouts from LaunchDarkly to Statsig by importing your flags, swapping the SDK, and recreating your targeting rules. Statsig converts LaunchDarkly's boolean flags to Feature Gates and its string, number, and JSON flags to Dynamic Configs. Run both systems in parallel behind a wrapper, then cut over one team at a time to keep the migration low-risk. ## How this guide is organized This guide covers the following topics: 1. Conceptual differences between LaunchDarkly and Statsig 2. Deciding what to migrate vs. not 3. Importing flags into Statsig 4. Flipping evaluation from LaunchDarkly to Statsig 5. How to run the migration process ## Conceptual differences between LaunchDarkly and Statsig LaunchDarkly and Statsig structure their feature management data models differently in several key ways: **Environment**: LaunchDarkly treats environments as a top-level concept where you must duplicate and manage flags and segments separately across environments. Statsig uses a centralized model where flags and configs handle environment-specific logic in their targeting rules. **Flag types**: LaunchDarkly uses a mix of boolean, multivariate, and JSON flags. Statsig distinguishes between Feature Gates (boolean) and Dynamic Configs (typed multivariate configs with JSON values). **Targeting**: LaunchDarkly relies on Contexts to evaluate flags. Statsig evaluates based on a StatsigUser object. #### Side by side comparison | LaunchDarkly concept | Can you migrate? | Statsig notes | | --- | --- | --- | | Project | ✅ Yes | Convert to Project | | Environment | ✅ Yes | Convert to Environment (mark critical as production in Statsig) | | Boolean Flags | ✅ Yes | Convert to Feature Gates | | String, Number, and JSON Flags | ✅ Yes | Convert to Dynamic Configs | | Segments | ✅ Yes | Convert to Segments (Statsig doesn't import big ID list segments) | | Targeting Rules | ✅ Yes | Convert to Rules | | Context kind | ✅ Yes | Convert to Custom Unit ID in Statsig | | Context attribute | ✅ Yes | Convert to Custom Fields in Statsig | | Flag owner, tags, teams, and history | ❌ No | Statsig doesn't preserve any metadata or historical versions of a flag during migration | #### User context mapping example LaunchDarkly supports multi-kind, structured user contexts. Statsig requires a user object to represent these contexts. In Statsig, User ID or Custom ID is equivalent to LD's key. Known top-level fields in Statsig include userID, email, ip, userAgent, and custom. All other fields go under the custom object. **Example 1: LD User context to Statsig User object conversion** ```javascript // 1 - LD User context { "kind": "user", "key": "user-key-123abc", "name": "Anna", "email": "anna@globalhealthexample.com", "organization": "Global Health Services", "jobFunction": "doctor", "device": "iPad" } // 1 - Statsig User object { "userID": "user-key-123abc", "email": "anna@globalhealthexample.com", "custom": { "name": "Anna", "organization": "Global Health Services", "jobFunction": "doctor", "device": "iPad" } } ``` **Example 2: LD Multi context kind to Statsig User object conversion** ```javascript // 2 - LD Multi context kind { "kind": "multi", "user": { "key": "user_abc", "name": "Anna", "email": "abc@company.com", "region": "us-east" }, "org": { "key": "org_xyz", "tier": "enterprise" } } // 2 - Statsig user object { "userID": "user_abc", "email": "abc@company.com", "customIDs": { "org_id": "org_xyz" }, "custom": { "user_name": "Anna", "user_region": "us-east", "org_tier": "enterprise" } } ``` In Statsig, `email` is a top-level reserved field on the user object: place it directly as `email` (not `user_email`). Statsig expects `userID`, `email`, `ip`, and `userAgent` at the top level for user targeting and analytics. ## Deciding what to migrate vs. not Before migrating flags from LaunchDarkly to Statsig, audit your existing flags and remove those that are no longer needed. Many organizations accumulate flag debt over time from stale flags, deprecated toggles, and legacy kill switches. Migration is an opportunity to start fresh with only active, valuable flags. Use filters such as "Lifecycle" and "Type" in LaunchDarkly to identify which flags are worth importing into Statsig. The following decision framework can help you decide which flags to import. The migration script follows this framework by default, but you can modify the script as needed. ![Migration Decision Framework](https://docs.statsig.com/images/tutorials/migration-launchdarkly/migration-decision-framework.png) ## Importing flags into Statsig Use the official import tool to import feature flags from LaunchDarkly into Statsig. The tool fetches flags from LaunchDarkly, translates them into Statsig's format, creates corresponding feature gates in Statsig, and tracks migration status and details in a CSV file. You have two options: 1. **[Open source script](https://docs.statsig.com/guides/open-source-script) (Recommended)**: Use this option to customize the integration logic. The script outputs a CSV of all your LaunchDarkly flags with migration status and URLs to the flag in LaunchDarkly and the gate in Statsig. This option imports all environments. 2. **[Statsig console](https://docs.statsig.com/guides/ui-based-tool)**: A UI-based wizard for importing LaunchDarkly feature flags and segments into Statsig. The wizard reports which gates and segments it migrated. This option imports only the production environment. > If you're migrating from a different system, recreate flags manually in Statsig. After auditing and removing unneeded flags, you should have a smaller set of flags to migrate. Contact the Statsig team over email or Slack if you need assistance. ## Flipping evaluation from LaunchDarkly to Statsig After you import your flags into Statsig, update the evaluation logic in your application. Rather than replacing every LaunchDarkly evaluation call with a Statsig call at once, introduce a wrapper that supports gradual migration. The wrapper lets you run both systems in parallel, compare outputs, and switch over incrementally with minimal risk. The wrapper approach provides several key benefits: - **Parallel execution**: Run both systems simultaneously to validate behavior - **Gradual rollout**: Migrate flags one at a time or by percentage - **Easy rollback**: Quickly revert to LaunchDarkly if issues arise - **Consistent interface**: Maintain existing application code structure #### Implementation guide **1. Before migration: LaunchDarkly Evaluation** Here's what a typical LaunchDarkly setup might look like: ```javascript import { LDClient } from 'launchdarkly-js-client-sdk'; const ldClient = LDClient.initialize('client-key', { key: 'user_abc', custom: { plan: 'pro' } }); ldClient.on('ready', () => { const isNewHomepageEnabled = ldClient.variation('new_homepage_flag', false); const buttonColor = ldClient.variation('button_config', 'gray'); }); ``` **2. Create the Migration Wrapper** Create a wrapper (`featureWrapper.js`) that handles both systems. The wrapper should check Statsig first and fall back to LaunchDarkly if Statsig is unavailable: ```javascript import { getLDClient } from './launchdarklyService'; import { getStatsigClient } from './statsigService'; export const wrapperFlags = { // For boolean flags wrapperGetFlag(flagKey, defaultValue = false) { const statsigClient = getStatsigClient(); if (statsigClient) { return statsigClient.checkGate(flagKey); } const ldClient = getLDClient(); if (ldClient) { return ldClient.variation(flagKey, defaultValue); } return defaultValue; }, // For dynamic configs (string, number, or json flags) wrapperGetConfig(user, configKey) { const statsigClient = getStatsigClient(); if (statsigClient) { const config = statsigClient.getConfig(user, configKey); return { get: (paramKey, defaultValue) => config.get(paramKey, defaultValue) }; } const ldClient = getLDClient(); if (ldClient) { return { get: (paramKey, defaultValue) => { const ldKey = `$\{configKey\}.${paramKey}`; return ldClient.variation(ldKey, defaultValue); } }; } return { get: (_key, defaultValue) => defaultValue }; } }; ``` **3. Refactor application code to use the wrapper** After the wrapper is in place, route all flag checks through it. The application logic doesn't change: only the mechanism that retrieves flags changes. ```javascript import { wrapperFlags } from './featureWrapper'; const user = { userID: 'user_abc', custom: { plan: 'pro' } }; // Boolean gate if (wrapperFlags.wrapperGetFlag('new_homepage_flag', user)) { showNewHomepage(); } // Multivariate config const buttonConfig = wrapperFlags.wrapperGetConfig('button_config', user); const buttonColor = buttonConfig.get('color', 'gray'); ``` **4. Validate and gradually cut over** After you have validated that Statsig is working as expected and that migrated flags return correct values, begin migrating more flags. Repeat these steps for 2–3 engineering teams to confirm the migration covers different use cases. After you maintain flags in both systems long enough to confirm stability, phase out LaunchDarkly. 1. **Remove LaunchDarkly fallback from the wrapper.** Update the wrapper functions to rely solely on Statsig. Removing the fallback simplifies the logic and ensures your app no longer queries LaunchDarkly in production. 2. **Delete LD initialization logic and SDK imports.** You can now safely remove any references to `LDClient.initialize` or `ldClient.variation`. ## How to run the migration process Use a phased rollout so each team can adopt Statsig independently. This approach supports gradual migration, scoped validation, and shared learnings across the organization. | Phase | Description | Who | Duration | | --- | --- | --- | --- | | 1. Auditing existing flags in LaunchDarkly | Each team reviews their LaunchDarkly flags and identifies which flags are worth migrating | Individual Teams | Ongoing (2-3 days per team) | | 2. Start creating all new flags in Statsig | Starting immediately, create all new flags in Statsig to avoid using the legacy system out of habit | Org-wide | 1 week | | 3. Pilot migration with one team | Select one team to migrate a small set of LaunchDarkly flags to Statsig using the wrapper. Validate that migrated flags work as expected | Pilot team | 1–2 weeks | | 4. Org-Wide migration and cutover | Repeat migration for more teams in waves. Create training docs and guides for org wide adoption. After Statsig is stable and adopted org-wide, remove LaunchDarkly fallback from wrapper | All teams + central guidance | 3–4 weeks (rolling) | If you need additional assistance or want to discuss your specific case, contact Statsig. ================================================================================ # Open Source Script URL: https://docs.statsig.com/guides/open-source-script ================================================================================ # Open Source Script The [Statsig open-source migration script](https://github.com/statsig-io/migrations) moves feature flags from LaunchDarkly to Statsig. It fetches your LaunchDarkly flags, translates them into Statsig's format, creates matching feature gates in Statsig, and writes the migration status to a CSV file. Use it when you need to customize the import logic beyond what the in-console tool offers. ## Considerations This script works by default. Start with a test environment of 5–10 flags. Before running the script at scale, consider the following: - **IMPORTANT**: If you don't need to customize the import script, use [Statsig's in-console tool](https://docs.statsig.com/guides/ui-based-tool) instead. - The script uses a tag `Imported from LaunchDarkly` to identify migrated flags in Statsig. Ensure this tag is unique and recognizable. - The script includes a function to delete all Statsig feature gates with a specific tag. Use this function with caution to clean up after a test or failed migration. - The script requires API keys for both LaunchDarkly and Statsig. Keep these keys secure. ## Installation To run the script, you need Node.js and npm installed on your system. Execute directly: ```bash npx @statsig/migrations --from launchdarkly --launchdarkly-project-id default <more-arguments> ``` ## Configuration - Provide your [LaunchDarkly API key](https://docs.launchdarkly.com/home/account/api) and [Statsig Console API key](https://docs.statsig.com/console-api/introduction) in the script. - Map LaunchDarkly environments to Statsig environments that aren't already the same by passing `--environment-name-mapping` to the script. - Map LaunchDarkly context kind to Statsig's custom unit ids and custom fields. You can find the detailed instructions for these steps on the [Github repo](https://github.com/statsig-io/migrations). ## Running the script To execute the migration script, run the following command in your terminal: ```bash node index.js ``` The script performs the following actions: 1. Fetch all feature flags from LaunchDarkly. 2. Translate each flag into Statsig's format. 3. Create feature gates in Statsig. 4. Write the migration status and details to a CSV file named `flag_migration_tracker.csv`. ## Example translations The following examples show how the script translates LaunchDarkly feature flags into Statsig feature gates: **Example 1:** LaunchDarkly flag with email and name targeting conditions ![Example 1 - LaunchDarkly to Statsig translation](https://docs.statsig.com/images/tutorials/migration-launchdarkly/open-source/example-translation-1.png) **Example 2:** LaunchDarkly flag with country-based targeting (off flag) ![Example 2 - LaunchDarkly to Statsig translation](https://docs.statsig.com/images/tutorials/migration-launchdarkly/open-source/example-translation-2.png) ## Troubleshooting If you encounter issues during the migration, check the following: - Confirm that the API keys are correct and have the necessary permissions. - Review the error messages in the console to diagnose the problem. Pull requests and feedback are welcome. ================================================================================ # UI-Based Tool URL: https://docs.statsig.com/guides/ui-based-tool ================================================================================ # UI-Based Tool Statsig's UI-based migration tool imports feature gates from LaunchDarkly into your Statsig project through the console, with no code required. Use it for a guided, screen-by-screen migration instead of the API. The tool imports only the "production" environment. ## What you need Review the full checklist in the [LaunchDarkly Migration Guide](https://docs.statsig.com/guides/migrate-from-launchdarkly#what-you-need), then gather: 1. Your project key. Projects in LaunchDarkly have a Name (for example, "My Mobile App") and a Key (for example, my\_mobile\_app). 2. A read-only access token for this project. Create one in LaunchDarkly under Account Settings > Authorization and limit the scope to read-only. 3. A Statsig project. Try this in a test project first. ## How it works These screens mirror the [console walkthrough](https://docs.statsig.com/guides/migrate-from-launchdarkly#how-it-works): 1. If you don't have any feature gates in your project, Statsig prompts you to import Feature Gates. ![Import Feature Gates prompt](https://docs.statsig.com/images/tutorials/migration-launchdarkly/ui-tool/ui-based-tool1.png) 2. Select LaunchDarkly as the platform you want to migrate from. ![Platform selection interface](https://docs.statsig.com/images/tutorials/migration-launchdarkly/ui-tool/ui-based-tool2.png) 3. Enter your LaunchDarkly Project Key and API Key/access token. ![LaunchDarkly credentials input form](https://docs.statsig.com/images/tutorials/migration-launchdarkly/ui-tool/ui-based-tool3.png) 4. Preview the migration summary. The tool highlights which gates it can and can't migrate. Gates it doesn't migrate include those with segments (coming soon) and those with non-Boolean flags. ![Migration summary preview screen](https://docs.statsig.com/images/tutorials/migration-launchdarkly/ui-tool/ui-based-tool4.png) 5. Finish migration of the gates. Statsig tags all migrated gates "Migrated" so you can identify them. ![Migration completion confirmation](https://docs.statsig.com/images/tutorials/migration-launchdarkly/ui-tool/ui-based-tool5.png) ================================================================================ # FAQ URL: https://docs.statsig.com/faq ================================================================================ # FAQ ## SDKs and APIs ### How does bucketing in the Statsig SDKs work Refer to [How Evaluation Works](https://docs.statsig.com/sdks/how-evaluation-works). --- ### Can I add a layer to a running experiment No. Layers lock after an experiment starts to preserve the integrity of results. Statsig may support editing layers in the future. --- ### Can I rename an existing experiment or feature gate Yes. When renaming an entity (for example, a feature gate, experiment, or layer), only its display name changes. The underlying ID referenced in your code remains unchanged because IDs are immutable, which prevents breaking existing implementations. --- ### Why define parameters instead of reading the experiment group Parameters let you iterate quickly without code changes and support richer experiment setups. For example: ```js // Group-based approach — requires code changes for each variant if (otherEngine.getExperiment('button_color_test').getGroup() === 'Control') { color = 'BLACK'; } else if (otherEngine.getExperiment('button_color_test').getGroup() === 'Blue') { color = 'BLUE'; } // Statsig parameter approach — variants can be changed from the console const color = statsig.getExperiment('button_color_test').getString('button_color', 'BLACK'); ``` --- ### Why aren't exposures or custom events showing up In short-lived environments (scripts, edge workers), the process may exit before events flush. Call `statsig.flush()` before shutdown. For more detail, refer to the [Node.js server SDK docs](https://docs.statsig.com/server/nodejsServerSDK#flushing-events). --- ### My SDK language isn't listed. Can I still use Statsig Likely yes. Post in the [Statsig Slack community](https://statsig.com/slack) and the team discusses options. --- ### How do I retrieve all exposures for a user The [Users tab](https://console.statsig.com/users) shows historical exposures. For hypothetical assignments (e.g., to bootstrap clients) you can call `getClientInitializeResponse` on the server. Pass `{ hash: 'none' }` if you need readable keys: ```js const assignments = statsig.getClientInitializeResponse(user, 'client-key', { hash: 'none' }); ``` --- ### What happens if I check a config that doesn't exist The SDK returns defaults: `false` for gates and the supplied fallback for experiments/layers. The evaluation reason is `Unrecognized`. Refer to [SDK debugging](https://docs.statsig.com/sdks/debugging#evaluation-reason) for more detail. This behavior applies to deleted, archived, or unseen configs (for example, configs filtered by [target apps](https://docs.statsig.com/sdks/target-apps)). --- ## Feature gates ### If I change the rollout percentage, do existing users keep their result Yes. Increasing the pass percentage (for example, 10% to 20%) keeps the original 10% and adds new traffic until it reaches the new percentage. Decreasing it removes the newest slice first. To reshuffle all users, you must resalt the gate. Experiments behave differently; use targeting gates for deterministic control. --- ## Statistics ### What statistical tests does Statsig use Statsig uses a two-sample Z-test for most experiments and [Welch's t-test](https://docs.statsig.com/experiments/statistical-methods/p-value#welchs-t-test) when sample sizes are small or variances differ. --- ### How does Statsig handle low sample sizes Statsig falls back to [Welch's t-test](https://docs.statsig.com/experiments/statistical-methods/p-value#welchs-t-test) and offers CUPED/winsorization to boost power. --- ### When should I use one-sided vs. two-sided tests Use one-sided when you only care about movement in a single direction; it increases power but hides movement in the opposite direction. --- ## Experimentation ### How do I get started with an A/B test If the feature isn't live yet, wrap it in a [feature gate](https://docs.statsig.com/guides/first-feature) and roll out. If it's already in production, create an [experiment](https://docs.statsig.com/guides/abn-tests). Results appear in the Pulse view. --- ### Can I target experiments to specific users (e.g., iOS only) Yes. Use a feature gate with targeting rules as a pre-filter for your experiment. ![Targeting iOS users in an experiment setup](https://docs.statsig.com/images/experiments/power-analysis/navigation.png) --- ## Billing ### What counts as a billable event Any gate/experiment check or event logged through the SDK or APIs. Pre-computed metrics and custom metrics based on existing data also count. Refer to the [Statsig pricing FAQ](https://statsig.com/pricing#faq) for a complete definition. --- ### How do I monitor and manage billable volume 1. Export usage from the **Usage and Billing** tab. 2. Pivot by event to identify high-volume events. 3. Admins receive alerts at 50/75/100% of contract. ![Usage dashboard showing event volume](https://docs.statsig.com/images/guides/first-feature/diagnostics-stream.png) --- ### How many projects can I create with a Pro subscription Each Statsig Pro plan unlocks one project with pro features and 5M events. Additional projects require their own upgrade. Enterprise plans can cover multiple projects. [Contact Statsig](https://statsig.com/contact/demo) to discuss options. --- ## Platform usability ### When should I create a new project Projects have distinct boundaries. If you're using the same userIDs and metrics across surfaces, apps or environments, put them in the same project. Create a new project when you're managing a separate product with unique user IDs and metrics. For example, if you have a marketing website (anonymous users) and a product (signed-in users), you may want to separate them. However, if you want to track success across both, you should manage them in the same project. For example, track from user signup on the marketing website to user engagement within the product. Reasons to avoid creating a new project: - Segregating by environment: Statsig supports environments natively, and you can customize them. You can turn features or experiments on and off by environment. - Segregating by platform: If you have an iOS app and a web app, collecting data in the same project lets you view data by platform and understand whether you increased the overall metric or moved users from one platform to the other. --- ### How can I monitor the health of Statsig and get support You can check the live operational status of Statsig at [status.statsig.com](http://status.statsig.com). To report an issue or receive help, contact the team directly in the [Slack Community](https://statsig.com/slack). --- ================================================================================ # About Warehouse Native URL: https://docs.statsig.com/statsig-warehouse-native/introduction Updated: 2025-09-18 ================================================================================ # About Warehouse Native > **Note:** > > Warehouse Native is part of Statsig's Enterprise tier. [Contact Statsig](https://statsig.com/contact/demo) to get started. Statsig Warehouse Native is an experimentation platform that runs analysis directly in your data warehouse. Statsig Warehouse Native connects to your existing datasets and any source of experiment assignment data, including Statsig's SDKs and real-time logging infrastructure. Warehouse Native shares core features with Statsig Cloud but focuses on specific scenarios around running experiments on top of your warehouse. ### Use cases for Statsig Warehouse Native - End-to-end experimentation platform covering targeting, experiment setup and assignment, and analysis. - Features include Feature Flagging, Automated/Protected Rollouts, Native Holdouts, Mutual Exclusion, and comprehensive analysis tools. - Modern statistical engine for running analyses on existing experiments from third-party or internal systems. - Statsig offers a full suite of experiment measurement tools, including CUPED, Stratified Sampling, Switchback Tests, and more. If you aren't sure whether Statsig Warehouse Native or Statsig Cloud is a better fit, contact the support team, your sales contact, or the [Slack community](https://statsig.com/slack). ## How Warehouse Native works Statsig Warehouse Native runs experimentation compute jobs directly in your data warehouse, using your existing datasets to calculate metrics and enrich experiment analysis based on your data. ![SDK exposures flow from your application into the Statsig warehouse as experiment and feature gate exposures, then into an assignments table in your warehouse. That table, which can also receive in-house assignments, and your metric source tables and queries both feed the Stats Engine, which runs experiment reloads and Metrics Explorer in your warehouse.](https://docs.statsig.com/images/diagrams/whn-data-flow.svg) ![SDK exposures flow from your application into the Statsig warehouse as experiment and feature gate exposures, then into an assignments table in your warehouse. That table, which can also receive in-house assignments, and your metric source tables and queries both feed the Stats Engine, which runs experiment reloads and Metrics Explorer in your warehouse.](https://docs.statsig.com/images/diagrams/whn-data-flow.dark.svg) ### SDK integration Using [Statsig SDKs](https://docs.statsig.com/sdks/getting-started) with Statsig Warehouse Native is similar to integrating with Statsig Cloud: 1. **Set Up Targeting and Experiments**: Create and manage experiments using the Statsig console. 2. **Initialize the SDK**: Integrate the Statsig SDK on your client or server-side applications. 3. **Targeting and Assignment**: Call the Statsig SDK to assign users to variants. - Optionally provide a logging callback to store logs in your warehouse or use Statsig's real-time infrastructure for instant diagnostics and safe rollouts. The resulting assignment and optional event logging data is stored in your warehouse, where you can connect it to other datasets for analysis. If you log to Statsig, Statsig exports data on-demand for real-time analysis or in scheduled batch jobs. ### Experiment setup Running experiments on Warehouse Native involves several key steps: 1. **[Connect Statsig to Your Warehouse](https://docs.statsig.com/statsig-warehouse-native/guides/quick-start#step-1-connect-your-warehouse)**: Integrate Statsig with your data warehouse to access relevant datasets. 2. **Create Metrics**: Define the input data and configure experiment metrics. 3. **Log Exposures**: Log experiment exposures with Statsig or point to existing assignments in your warehouse. 4. **State Your Hypothesis**: Formulate a hypothesis and choose scorecard metrics to evaluate the experiment. 5. **Run Pulse Analysis**: Execute a Pulse analysis to test your hypotheses and measure the impact on scorecard metrics. ### Advanced analysis tools Statsig’s [data analysis tools](https://docs.statsig.com/experiments/interpreting-results/read-results) run directly in your data warehouse. Your warehouse holds all queries, intermediate datasets, and final results that Statsig generates, for auditing and custom analysis. - **Pulse Analysis**: Pulse helps you test your hypotheses and measure the impact of changes on your scorecard metrics. - **Metrics Explorer**: Visualize experiment metrics for your entire population and drill down into user behavior. Metrics Explorer is part of a broader suite of product observability tools, including Session Replay, advanced filtering, and custom dashboards. - **Exposure Analysis**: Analyze your experiment's first exposures to debug and gain insights on your experiments in Metrics Explorer. Drill down into certain properties or understand how your experiments interact with one another. ## Start using Warehouse Native > **Info:** > > Contact the support team, your sales contact, or the [Slack community](https://statsig.com/slack) with any questions. Use the following guides to start running or analyzing an experiment: ### [Quick Start](https://docs.statsig.com/statsig-warehouse-native/guides/quick-start) Connect Statsig to your warehouse and get test results in minutes ### [Evaluate Statsig](https://docs.statsig.com/statsig-warehouse-native/guides/running_a_poc) Evaluate how Statsig Warehouse Native can work for you ### [Learn About Experimentation](https://docs.statsig.com/statsig-warehouse-native/features/statistics) Learn about Statsig's modern Stats Engine --- ================================================================================ # Warehouse Native Quickstart URL: https://docs.statsig.com/statsig-warehouse-native/guides/quick-start Updated: 2025-09-18 ================================================================================ # Warehouse Native Quickstart Statsig Warehouse Native connects to a table in your warehouse, builds metrics on top of it, and computes experiment results. This quickstart walks through connecting your data, configuring a metric, and reading your first results. All you need is a table in your warehouse that has metric or event logging data. ## Step 1: Connect your warehouse Statsig uses your warehouse to store and analyze your experiment data; you have total control and visibility over the data itself. To connect your warehouse, go to your warehouse's setup page. - [Snowflake](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/snowflake) - [Athena](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/athena) - [BigQuery](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/bigquery) - [Databricks](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/databricks) - [Redshift](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/redshift) ## Step 2: Connect to data To connect your event or metric data, you create a [Metric Source](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources). Go to the _Metric Sources_ page and click **Create** to make a new Metric Source. ![Create metric source button](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/66229d92-99a8-45c6-9a1c-7f8585465338.png) If you have a table, use the `Table` metric source type and put in the path to your table. Otherwise, you can write a query to access or generate some test data. Press **Analyze** to generate samples from your table, then map required columns (Timestamp and UserID) so Statsig can connect your metric data to your assignment data. ![Metric source configuration mapping timestamp and user ID](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/c0982d71-71c5-4899-bed9-a72c7db59515.png) Save your changes, and you've connected to your data! ## Step 3: Make a metric Now that you've connected to data, you can build metrics on top of this data. You can configure metrics programmatically later; for now, go to your _Metrics Catalog_ and click **Create** to make a new metric. ![Metrics catalog create button](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/8b997a0c-22e9-409d-8918-d21a95af1367.png) Point to the metric source you configured, name your metric, and press **Create**. Pressing **Create** takes you to the new metric's page, where you can configure the metric. To get started, Statsig recommends making a [count metric](https://docs.statsig.com/statsig-warehouse-native/metrics/count). A count metric counts the number of rows in your metric source. A count metric is useful for event logging. For example, you might filter to a "purchase" event to count the number of times users purchased an item. Select "Count" and save, or pause here to explore the options. ## Step 4: Connect an experiment Next, you connect to experiment data. If you have a table with exposures you've already logged, use that. Ensure you've logged the same identifier there as you used in your metric source. Otherwise, you can quickly follow the guide to setting up an [A/A test](https://docs.statsig.com/experiments/types/aa-test), using the same data you used for your exposures. An A/A test should generate a neutral experiment result. Go to _Assignment Sources_ and create a new one. ![Create assignment source page](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/fe0e4c5d-e2a6-4943-9b09-cb81dbadee9e.png) If using an AA test, follow the instructions to randomly assign users to groups. If you're using existing assignments, write a query to pull the data from your logs and map the unit, group, experiment, and timestamp columns. ![Assignment source query configuration](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/08e3f20c-1590-4b08-ad60-fa96ecbf15cb.png) Pressing **Save and Scan** saves your new source and detects experiments that exist on the source. The scan takes seconds to a few minutes. After it finishes, scroll down to look through the experiments Statsig found. ![Detected experiments table](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/8be2f079-4440-4742-9727-08e25b65c84b.png) ## Step 5: Analyze your experiment Press **Create** on your experiment of interest to start creating your experiment. ![Experiment creation wizard](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/fc6e7092-b621-494a-bedb-8cd03a64d510.png) Add a display name and hypothesis, then press **Create**. Pressing **Create** takes you to the final setup step, where you specify the metrics for your experiment. Choose the metric you created in step 3. Statsig automatically detects the group split, but if the detected split is incorrect you can manually adjust it to the intended value. ![Experiment setup selecting metrics and group split](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/287bc60b-23a6-4681-ac26-282ce8b88c13.png) Press **Save and Analyze**, and Statsig starts calculating Pulse Results. You can track the progress in the loading bar at the bottom of the experiment's results page. ## Step 6: Read results If everything worked, you should see: - Your hypothesis. The hypothesis lives at the top of the results page to give context and guide interpretation of the results. - Cumulative exposures. Cumulative exposures show the number of unique units exposed to each group, and the balance between groups. - Your scorecard. The scorecard shows a summary of the observed differences in metrics between your experiment groups, with access to additional views and raw statistics. ![Experiment results showing hypothesis and exposures](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/38f4f438-2592-44cb-9063-d3bc97da404b.png) Explore the product and docs to learn more about these features: - Click into a result's error bar to view raw statistics, timeseries, and projected [timeline impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact). - Hover over a metric to get detailed context on its inputs and how Statsig calculated the pulse result. - Go to the **Diagnostics** tab to view the [checks](https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment) Statsig automatically ran to validate your experiment results. - Select the reloaded timestamp to view the run time and query cost of your Pulse analysis, and the SQL queries used to calculate the results. - Go to the **Explore** tab to start filtering data, exploring results by dimensions, or running other follow-up analyses. - Go to the **Summary** tab to start putting together a [report](https://docs.statsig.com/statsig-warehouse-native/features/reports) to share the results of your analysis. - Start a discussion or add context, either in the **Discussion** tab or with in-context comments on top of the results themselves. The example experiment wasn't an AA test, and there was an experimental impact. The result is statistically significant, with an estimated lift of +12.89% ±0.93% from control to test. Select the result to view additional details, such as the expected change to the overall topline metric value if the experiment ships. ![Detailed metric lift view with significance](https://docs.statsig.com/images/statsig-warehouse-native/guides/quick-start/33e5fc2a-9b36-43f9-a6c2-2936867a7980.png) You've completed the Quick Start guide. To run an experiment of your own rather than the example, [Experiment process overview](https://docs.statsig.com/experiments/process-overview) lists each step, from sizing the experiment with a power analysis through making a decision. ================================================================================ # Comparing Warehouse Native and Cloud URL: https://docs.statsig.com/statsig-warehouse-native/native-vs-cloud Updated: 2025-09-18 ================================================================================ # Comparing Warehouse Native and Cloud Statsig Warehouse Native and Statsig Cloud share many capabilities, but the two platforms differ in important ways. Compare those differences to choose the right product for your experimentation needs. If a feature is critical for your evaluation, contact the support team, your sales contact, or the [Slack community](https://statsig.com/slack). ## Feature gates | Feature | Cloud vs. WHN Status | | --- | --- | | Targeting | Identical | | Overrides | Identical | | SDKs | Identical | | Diagnostics | Identical | | Pulse | Identical | | Gate lifecycle management | Identical | ## E2E experiments (with SDK) | Feature | Cloud vs. WHN Status | | --- | --- | | Pulse | WHN offers on-demand reloads | ## Pulse (scorecards) | Feature | Cloud vs. WHN Status | | --- | --- | | CUPED | Identical | | CURE | WHN only for now | | Topline Impact | Identical | | Daily Time Series | Identical | | Frequentist vs Bayesian | Identical | | Sequential Testing | Identical | | BF Correction | Identical | | Power Analysis | Identical | | Custom Queries | Identical | | Guardrail Metric Alerts | Available in WHN, based on your pipeline cadence | | Export to CSV | Identical | | Share Links | Identical | ## Analysis only experiments (without SDK) | Feature | Cloud vs. WHN Status | | --- | --- | | Overrides | Not relevant w/o SDK | | Diagnostics (SDK Related) | Not relevant w/o SDK | | Diagnostics (Data specific) | WHN has additional | | Capture Hypothesis | Identical | | Capture Images | Identical | | Experiment Groups | Identical | | Experiment Parameters | Not relevant w/o SDK | | SRM Checks | Identical | | View SQL | WHN-only | ## Core features | Feature | Cloud vs. WHN Status | | --- | --- | | Layers | Identical | | Dynamic Config | Identical | | Dashboards | Identical | | Segments | Identical | | Holdouts | Identical | ## Insights | Feature | Cloud vs. WHN Status | | --- | --- | | Experiment Timeline | Identical | | Knowledge Bank | Identical | | Metric Insights | Identical | | Metric Correlations | Identical | | Metric Impacts | Identical | | Active feature analysis | Identical | | Historic feature analysis | Identical | ## Metrics | Feature | Cloud vs. WHN Status | | --- | --- | | Metrics Explorer | Substantially Identical | | SDK Events Logstream | Identical | | Autocreate metric from SDK Events | Cloud only for now | | User Accounting Metrics (DAU, Stickiness) | Cloud only for now | | Automated A/A Tests | Cloud only for now | | Entity Property Source ID mapping | WHN only | ## Organization & settings | Feature | Cloud vs. WHN Status | | --- | --- | | SSO | Identical | | Experiment Policy | Identical | | Change Reviews | Identical | | Custom UnitIDs | Identical | | Custom RBAC | Identical | ## Integrations & admin | Feature | Cloud vs. WHN Status | | --- | --- | | Change mgmt (Slack, Datadog, Github etc) | Identical | | CDBs (Segment/Rudderstack etc) | Not relevant for WHN | | Custom Environments | Identical | | Target Applications | Identical | | Console API | Identical | | Audit Log | Identical | | Audit Log API | Identical | | Autotune (MAB) | Identical | | Users Tab | Identical | ================================================================================ # Migrating to Warehouse Native URL: https://docs.statsig.com/statsig-warehouse-native/guides/migrate-to-whn Updated: 2026-07-21 ================================================================================ # Migrating to Warehouse Native This guide applies to any migration into Statsig Warehouse Native, whether you're coming from **Statsig Cloud** or from an **existing Warehouse Native project** (for example, moving to a different warehouse or restructuring your setup). If you're migrating from Cloud, the main change is where Statsig computes your metrics: it sources them from your data warehouse instead. If all (or most) of your metrics already come from your warehouse, migration is relatively simple. The recommended migration path is a **side-by-side migration into a new Warehouse Native project**, not an in-place conversion of your existing project. Your current project stays unchanged, so you can validate the new project at your own pace, compare results directly between the two, and switch over only when you're confident. ## Migration overview 1. **Prepare your warehouse.** Make sure your data warehouse is ready and contains the historical data you care about, including metric data and assignment (exposure) data, backfilled to the depth you need. 2. **Create a new Warehouse Native project** and [connect it to your warehouse](https://docs.statsig.com/statsig-warehouse-native/guides/connect). 3. **Set up your data foundations** under the Data tab: [metric sources](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources), assignment sources, and your metrics catalog. 4. **Recreate your configurations** (gates, experiments, and dynamic configs) manually, programmatically with the [Console API](https://docs.statsig.com/console-api/introduction), or with the [self-serve migration wizard (early access)](https://docs.statsig.com/statsig-warehouse-native/guides/self-serve-migration), which copies them for you. 5. **Run both projects side by side** and compare results between your existing project and the new Warehouse Native project. Re-analyze experiments you've already run to confirm the numbers line up with what you expect. 6. **Switch your client-side SDKs** to the new project's keys once you're satisfied with the comparison. ## Why a separate project Because the migration never changes your original project: - **No cutover window or change freeze**: Your team keeps working in the existing project until you're ready to switch. - **Easy rollback**: If anything looks off, keep using your existing project, which stays unchanged. - **Historical data stays accessible**: Your past experiment results remain available in the original project. - **Direct validation**: You can make an apples-to-apples comparison between the two projects before committing. ## Before you start - If you're migrating from Cloud, review the [feature comparison between Cloud and Warehouse Native](https://docs.statsig.com/statsig-warehouse-native/native-vs-cloud) so your team knows what changes. A few features behave differently on Warehouse Native, and it's best to identify those gaps before you migrate rather than after. - Plan for the setup work in the new project up front: warehouse readiness, data backfill, and the Data tab configuration are the bulk of the migration effort. - If you're an enterprise customer, work with your Statsig contact to evaluate feasibility and plan the migration. ================================================================================ # Self-Serve Migration Wizard (Early Access) URL: https://docs.statsig.com/statsig-warehouse-native/guides/self-serve-migration ================================================================================ # Self-Serve Migration Wizard (Early Access) > **Note:** > > Statsig enables the wizard per project on request. To try it, raise a [support request](https://docs.statsig.com/support-options) through your dedicated Slack channel, the [Slack community](https://statsig.com/slack), or support@statsig.com. You can also ask your account team. Include your **source project ID** and, if you've already created it, your **destination Warehouse Native project ID**, so Statsig can enable access. The self-serve migration wizard automates step 4 of the [migration guide](https://docs.statsig.com/statsig-warehouse-native/guides/migrate-to-whn): instead of recreating your configurations manually or through the Console API, the wizard copies them from your existing project into a separate, pre-created Warehouse Native project for you. The wizard never modifies your source project. It keeps serving traffic throughout the migration and remains your rollback path and your historical record. ## What the wizard copies | Copied | Notes | | --- | --- | | Feature gates | Rules, targeting, and tags; segment references resolve by name | | Dynamic configs | Rules and values | | Segments | Rule-based segments; the wizard flags large ID-list segments for manual handling | | Layers | Explicit layers with parameters and allocations | | Experiments | Full setup, groups, and parameters, created unstarted; metrics re-attach by name | | Holdouts | Including member gates, experiments, and layers | | Parameter stores | With references remapped to the copied entities | | Autotunes | Setup only; the wizard flags event-based autotunes, which can't run in a Warehouse Native project | | Project settings | Relevant non-cutover settings and custom ID types | ## What it doesn't copy - **Metrics and metric sources**: These are warehouse-specific SQL that you must create in the destination project before migrating. Use the same metric names as the source project so experiments re-attach automatically. - **Historical results, exposures, and decision records**: These describe the source project's run history and stay readable there. - **Dashboards, alerts, and large ID-list segments**: The wizard flags these in its report for manual recreation. - **SDK keys and environments**: The destination project issues its own keys; you switch your SDKs over at cutover time. ## Assignment after you switch SDKs Users keep their assignments when you move your SDKs to the destination project. The wizard copies each entity's bucketing salts, the values Statsig hashes with a unit ID to [assign users deterministically](https://docs.statsig.com/sdks/how-evaluation-works), so the same users pass the same gates and land in the same experiment groups and layer allocations as in the source project. | Entity | Salts the wizard keeps | | --- | --- | | Feature gates, dynamic configs, and segments | The entity salt and every rule's salt, so partial rollouts pass the same users | | Holdouts | The holdout salt and its rule salts, so the same users stay held out | | Layers | The layer's universe salt | | Experiments | The experiment salt and the experiment's allocation within its layer | | Autotunes | The experiment salt | The wizard creates experiments unstarted, so users get the default experience in the destination until you start each copy. Start the copies of experiments that are running in the source project before you switch SDK keys. When the wizard can't keep an assignment, it reports the entity in the step summary instead of failing: - `allocation_not_preserved`: Another experiment in the destination layer already uses the source experiment's allocation, or the source allocation doesn't match the copy's size. The copy gets a new allocation, so a different set of users enters the experiment. - `layer_universe_salt_differs`: The experiment joined a layer with the same name that you created in the destination before the migration. That layer has its own salt, so users fall into different allocations. Let the wizard create layers to avoid this. - `holdout_salts_not_preserved`: The source holdout's salt changed after Statsig set up its groups, and the source still buckets users on the earlier salt. The copy uses the current salt, so some users can move into or out of the holdout. The wizard doesn't report two cases: - **Copies from earlier runs**: Re-runs skip entities that already exist in the destination, so they don't update salts on existing copies. Copies from a run on or before October 16, 2026 can have new salts. To give them the source salts, delete those copies from the destination project and re-run the wizard. - **Stratified sampling on unstarted experiments**: The wizard doesn't copy the stratified sampling salt. Started experiments already bucket on it through the experiment salt, but for an unstarted experiment, run [stratified sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling) again in the destination before you start it. ## Prerequisites Before running the wizard, fully set up the destination Warehouse Native project: 1. Create the new Warehouse Native project. 2. [Connect and test your warehouse connection](https://docs.statsig.com/statsig-warehouse-native/guides/connect). 3. Configure the Data tab: assignment sources, [metric sources](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources), and metrics that match the source project's metric names. 4. Backfill any historical data you want available in your warehouse. ## Run the wizard 1. **Open the wizard** in the source project. It appears once Statsig enables early access for your project. 2. **Pick the destination project.** The wizard runs a precheck that validates the destination (warehouse connection and required setup) before it copies anything. 3. **Start the migration.** Steps run in dependency order: segments before gates, layers before experiments, and so on. Each step reports what it created, skipped, or flagged with a warning as it completes. 4. **Review the report.** Warnings, such as entities that need manual handling or references the wizard couldn't resolve, stay visible after the run completes, including across page reloads. > **Note:** > > Runs are idempotent: if the wizard stops partway or you re-run it, it skips entities that already exist in the destination (matched by name) rather than duplicating them. ## Verify, then cut over 1. Spot-check copied entities in the destination project: rules, experiment groups, holdout membership, and parameter store references. 2. Compare entity counts against the source project, minus the intentionally skipped items from the report. 3. Check the report for [assignment warnings](#assignment-after-you-switch-sdks), and start the copies of experiments that are running in the source project. 4. When you're satisfied, update your SDK initializations to the destination project's keys, environment by environment. Nothing in this flow modifies the source project, so rolling back is simply continuing to use your existing keys. ## FAQ **Do my running experiments stop?** No. The source experiments keep running untouched; the wizard creates copies unstarted in the destination. **Do users get the same gate results and experiment groups after I switch SDKs?** Yes. The wizard copies bucketing salts, so users keep their assignments once you start the copied experiments. Check the run report for the exceptions in [Assignment after you switch SDKs](#assignment-after-you-switch-sdks). **Can I re-run the wizard?** Yes. Runs are idempotent, and the wizard skips entities that already exist in the destination (by name). **Does this move my data?** No. The wizard copies configuration. Exposure and metric data in a Warehouse Native project come from your warehouse, and backfilling historical data is part of the prerequisites. ================================================================================ # Running a Warehouse Native POC URL: https://docs.statsig.com/statsig-warehouse-native/guides/running_a_poc Updated: 2025-09-18 ================================================================================ # Running a Warehouse Native POC ## What Statsig Warehouse Native does **Statsig Warehouse Native** enables customers with existing metric logs to analyze that data, and optionally bring previous assignment data or offline experiments into the platform. Statsig WHN has two types of experiments: 1. **Assign and Analyze**: You can run an experiment on **web/mobile/app** and use Statsig’s SDKs to assign (bucket or randomize) users, and then analyze results. 2. **Analyze**: You can run an experiment elsewhere (_**your own SDK, email, direct mail, sms, ivr, etc.**_) and use Statsig to analyze that data and calculate experiment results. Statsig reads this assignment data from your warehouse in [this format](https://docs.statsig.com/statsig-warehouse-native/configuration/assignment-sources#example-data); Statsig calls these [Assignment Sources](https://docs.statsig.com/statsig-warehouse-native/configuration/assignment-sources). If you have a pre-existing experiment in your warehouse, start with an **Analyze** experiment. An Analyze experiment is an effective way (less than 1 day) to establish a connection between Statsig and your warehouse, and to experience [experiment results](https://docs.statsig.com/experiments/interpreting-results/read-results) in the Statsig console. After that, run an **Assign and Analyze** experiment using Statsig's SDKs (typically an A/A test). The A/A **Assign and Analyze** experiment lets you test Statsig's SDKs and implementation process with your engineering and product team. ## Steps to running an effective proof of concept with Warehouse Native ![If you have existing experiment data, analyze that experiment in Statsig in about 30 minutes. If not, and you have an experiment in mind, set it up with the Statsig SDK. If neither applies, contact Statsig to simulate a quick A/A test. All three paths end with looping in cross-functional teams to review the experiment results.](https://docs.statsig.com/images/diagrams/whn-poc-decision-flow.svg) ![If you have existing experiment data, analyze that experiment in Statsig in about 30 minutes. If not, and you have an experiment in mind, set it up with the Statsig SDK. If neither applies, contact Statsig to simulate a quick A/A test. All three paths end with looping in cross-functional teams to review the experiment results.](https://docs.statsig.com/images/diagrams/whn-poc-decision-flow.dark.svg) Follow these steps when planning your Warehouse Native implementation: 1. **Define your experiment(s) and metrics for validation** - A proof of concept determines if Statsig fits your experimentation needs; running an experiment is the most direct path for evaluation. **Responsible Party**: Typically a product or engineering lead. - Plan to run 1-2 production level experiments to validate. Past experiments, A/A tests or upcoming projects or product changes are great opportunities to implement a Statsig experiment! - Identify your hypothesis and [metrics](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics) to validate this hypothesis. Statsig joins these metrics with unit assignment/exposure data and runs them through the stats engine. - If your team plans on running **analysis only**, identify the user **assignment** data that Statsig joins with the metric data. - The analysis-only approach can yield results in as little as 30 minutes, assuming data is readily available for ingestion. - If your team plans on using the **Assign and Analyze** experimentation option, identify where the experiment runs. Typically, web-based experiments are easier to evaluate, but Statsig also has SDK support for server and mobile SDKs. - **Note**: It’s important the implementing team understands how the SDKs operate before executing a proof of concept. The [client](https://docs.statsig.com/client/introduction) and [server](https://docs.statsig.com/server/introduction) docs can help orient your team. - A typical evaluation takes 2-4 weeks to account for experiment design, implementation, time to gather data, and analysis. To ensure a successful POC, [have a well scoped plan](https://docs.statsig.com/statsig-warehouse-native/guides/running_a_poc#2-phase-0-scope--prepare-your-poc) and include the right teams to assist. - Read [experimentation best practices](https://statsig.com/blog/product-experimentation-best-practices) to learn how to succeed. 2. **Connect the warehouse** - To query data and operate within your warehouse, you need to allocate resources and connect to Statsig. You may choose to use an existing prod database or create a separate cluster specifically for experimentation (if you don’t already have one). - Statsig requires a role and the following access: - Read access to metric and exposure data - Write access so Statsig can write results and exposures back to the warehouse - Access to run jobs and query data - Find more guidance on [connecting with your specific warehouse vendor here](https://docs.statsig.com/statsig-warehouse-native/guides/connect). - Review the [data pipeline overview](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview) to understand how data flows for warehouse native jobs. 3. **Connect metric sources and define metrics** - After you connect the data warehouse, you can begin defining metric and assignment sources (if applicable) in Statsig. Statsig expects specific schemas to correctly map the data to its pipelines: ![Schema requirements diagram for metric sources](https://docs.statsig.com/images/statsig-warehouse-native/guides/running_a_poc/4fa8c5e2-c19f-4ef6-be70-f31b61170e7c.png) Beyond these columns, the schema is flexible and can accept additional columns. You can use **Metadata** to filter metrics and perform more granular analysis. - Review guides for creating a [metric](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources) and [assignment](https://docs.statsig.com/statsig-warehouse-native/configuration/assignment-sources) source - Follow the [data best practices](https://docs.statsig.com/statsig-warehouse-native/guides/best-practices) to ensure your queries are running efficiently. > **Info:** > > This section is important to review and can prevent unnecessary infrastructure costs! After you connect metric sources, configure [metrics](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics) to perform various aggregations (e.g., Sum, Mean, Count, Unique Users) that represent what you’re trying to measure in your experiments. - [Supported metric types](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics#metric-types) and ways to [configure them](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics) - Use [cohort metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) to measure impact during a certain time frame per user. 4. **Create and roll out an experiment** - In step 1, you defined the planned experiment(s) and the metrics used to validate them. With metrics and assignment sources configured, you can now create the experiment(s). Refer to the [detailed guide for experiment setup](https://docs.statsig.com/statsig-warehouse-native/guides/experiments), and consider these things as you complete this step: - Create your hypothesis and select the **experiment (assignment) source**. - If using the SDK for assignment, the SDK itself serves as the assignment source. - You can use [Custom IDs](https://docs.statsig.com/guides/experiment-on-custom-id-types) but must first configure them; for example: `device_id`, `vehicleId`. - Refer to [advanced settings](https://docs.statsig.com/statsig-warehouse-native/features/configure-an-experiment#advanced-settings) for the many ways you can configure your experiment. - As you roll out your experiment, you can [monitor the status with health checks](https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment) and get a readout of live exposures as they come through the SDK. - If you’re hoping to quickly validate the platform, you can create and run a [quick A/A test](https://docs.statsig.com/statsig-warehouse-native/guides/aatest). 5. **Read results** - After the experiment runs successfully, read the results and ensure everything looks reasonable. Did the results validate your hypothesis, or are they surprising? Are the results easy to interpret and navigate for the teams involved? Refer to the [section on Pulse](https://docs.statsig.com/statsig-warehouse-native/guides/pulse) to understand the high-level analytics capabilities. A few things to note: - You can slice results further using the [_Explore_ tab](https://docs.statsig.com/statsig-warehouse-native/guides/pulse#explore), which lets you break down results by specific user and event properties. - You can configure Statsig to forward exposure and metric data to your warehouse. - The [_Health Checks_ (diagnostics) tab](https://docs.statsig.com/statsig-warehouse-native/guides/pulse#health-checks) surfaces the SQL used to generate results so you can validate any analysis performed on your systems. 6. **Finalize evaluation and next steps:** Ultimately, a POC validates a set of evaluation criteria that determines whether Statsig is a good fit for your team’s workflows. The following graphic provides high-level guidance on what to look for during your evaluation phase. ![POC evaluation checklist graphic](https://docs.statsig.com/images/statsig-warehouse-native/guides/running_a_poc/c5f86db5-6bf9-4a5e-9709-ede36384b3ca.png) To move forward, convert your POC environment to a production-level implementation. Refer to the [production guide](https://docs.statsig.com/statsig-warehouse-native/guides/production) for details. Statsig offers support through the [community Slack channel](https://statsig.com/slack). ================================================================================ # How to Run a Playground Evaluation URL: https://docs.statsig.com/statsig-warehouse-native/guides/playground_eval Updated: 2025-09-18 ================================================================================ # How to Run a Playground Evaluation > **Info:** > > Statsig recommends playground evaluations only for Enterprise-tier customers. A Playground Evaluation is a Statsig-hosted project with sample, near-real-time data sources that you use to set up experiments, analyze metrics, and explore Statsig Warehouse Native. Use it to evaluate the product when privacy or data-security requirements make testing on your own production data slow. The read-only [Demo Project](https://console.statsig.com/whn_demo) doesn't cover the full warehouse native experience, so contact support to request a Playground Evaluation project. You're an admin on the project and can add teammates to explore it together. ## Playground projects Playground projects come with some boilerplate connections hooked up: - A real-time event streaming metric source - A daily user-level metric source - An assignment source with a handful of experiments - A handful of pre-loaded metrics and experiments > **Note:** > > Playground projects don't come with any assign-and-analyze experiments, so you can't use some features that require SDK usage (e.g. Stratified Sampling). You can use a normal demo project with an SDK on a local script to generate data for those use cases. ## Evaluation Follow steps 2 and later from the [quick start](https://docs.statsig.com/statsig-warehouse-native/guides/quick-start) guide, starting with the tables available to the playground project. These steps give you a sense of what running experiments and managing metrics in Statsig involves. After completing those steps, refer to the [POC guide](https://docs.statsig.com/statsig-warehouse-native/guides/running_a_poc) and simulate the steps relevant to your evaluation. Exploring the Pulse UI together has been useful for teams. The Statsig team welcomes any questions or feedback. ================================================================================ # Working With the SDK URL: https://docs.statsig.com/statsig-warehouse-native/guides/sdks Updated: 2025-09-18 ================================================================================ # Working With the SDK Statsig Warehouse Native works with any Statsig SDK to log events and assign users to feature flags or experiments. Statsig then forwards that assignment and event data to your warehouse for analysis. Refer to the [client](../../client/introduction) or [server](../../server/introduction) SDK docs for help setting up SDKs. ## Data Forwarding When you first set up your data connection, Statsig creates tables to forward datasets to. Statsig also generates assignment and metric sources that include any user-level metadata fields you log during your evaluation. You can find the configuration for these datasets and the table Statsig creates or outputs data to in the advanced section of the warehouse connection page. ![Choose Groups](https://docs.statsig.com/images/whn/data_forwarding_whn.png) ## Exposures Statsig calculates deduplicated first-exposure rollups for you on a daily basis and exports that miniaturized dataset to your warehouse. Additionally, on every Pulse load on the first day of an experiment, Statsig exports deduplicated exposures for the day to your warehouse in near real-time, up to 1 million exposures. ## Log Events You can also use Statsig's powerful event logging to send events to the Statsig SDK; Statsig later exports them to your warehouse for analysis. ================================================================================ # Synthetic A/A Test URL: https://docs.statsig.com/statsig-warehouse-native/guides/aatest Updated: 2025-09-18 ================================================================================ # Synthetic A/A Test An A/A test randomly splits users you already have events for into two groups that receive the same experience. Run one to validate your experimentation setup and confirm your metrics and Pulse scorecards behave correctly before you run a real A/B test. Create an assignment source with the following script, then analyze the A/A test in minutes as Pulse scorecards populate. Example script: ```sql SELECT user_id, timestamp, 'AA_Test_1' AS experiment_name, --CAST('AA_Test_1' as varchar) AS experiment_name for Redshift warehouse CASE WHEN <random_logic> THEN 'Control' ELSE 'Test' END AS GroupAssignment FROM <my_event/metrics_table> ``` Replace `<random_logic>` with the following based on your warehouse: - Bigquery: `mod(abs(farm_fingerprint(cast(user_id as string))), 100) < 50` - Redshift: `mod(abs(farmFingerprint64(cast(user_id as varchar))), 100) < 50` - Snowflake: `mod(abs(hash(cast(user_id as string))), 100) < 50` - Databricks: `mod(abs(hash(cast(user_id as string))), 100) < 50` - Athena: `mod(abs(cast(conv(substr(md5(cast(user_id as varchar)), 1, 16), 16, 10) as bigint)), 100) < 50` ================================================================================ # Running Email Experiments URL: https://docs.statsig.com/statsig-warehouse-native/guides/email-experiments Updated: 2025-09-18 ================================================================================ # Running Email Experiments Statsig Warehouse Native runs email marketing experiments by analyzing the downstream outcomes of your email sends. Configuring an email experiment involves three questions: whether your marketing platform can export email engagement events to your warehouse, which down-funnel metrics to score, and how to define your test and control groups. ### Data access offered by your marketing platform > Does the platform offer the ability to ETL email engagement events (sends, deliveries, email opens) to your data warehouse either directly, or through a CDP or other pipeline? Data access may be critical to the viability and quality of your experiment, depending on your specific use case. In particular, `email open` events are useful for controlling the population of users Statsig counts for analysis. For example, suppose you send 20,000 emails and only 12,000 are delivered and opened. Counting only the 12,000 email-open users in the test population (rather than the entire recipient list) avoids diluting the population and achieves more statistical power. Use email open events to manually create an assignment source for an `Analyze Only` experiment, or to [filter your analysis population](https://docs.statsig.com/statsig-warehouse-native/configuration/qualifying-events/#filter-by-qualifying-events) for an `Analyze Only` experiment. ### Configuring scorecard metrics > What are your key down-funnel (for example, on-site or in-app) success metrics for the experiment, and can you unify email recipients with their subsequent down-funnel interactions? Email open events are useful for filtering the test population or for monitoring purposes, but aren't typically a primary metric unless the experiment is testing different subject lines. Consider which down-funnel metrics to include as primary metrics for deciding on your experiment. Attributing down-funnel interactions that occur before user login can be complex, but [ID resolution in Statsig](https://docs.statsig.com/statsig-warehouse-native/features/id-resolution/) solves this attribution problem. Down-funnel metrics that occur after login are easy to attribute to the experiment, because you have the user ID and email address to map directly to the identifiers on your assignment source. ### Designing test groups and running the test > What options does your email platform offer for defining test and control groups? Does the platform require you to upload a list of users for each group, or does it natively support A/B cohort definitions? If your platform offers native A/B split capabilities, configure your test as an `Analyze Only` experiment in Statsig. Select **Analyze** and leave the **Experiment Completed** checkbox unchecked. Statsig then continues computing results from the first exposure time until you decide to conclude the experiment. If you need to manually create the test groups, set up an `Assign and Analyze` experiment and use Statsig's SDKs to generate your test and control lists. Loop over all intended recipients in code and call `getExperiment`. This call captures each test group assignment and automatically writes the assignment events to your data warehouse through the [Statsig managed exposure pipeline](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). Select **Start** before running your assignments script, then keep the test in a running state until you decide to conclude the experiment. ================================================================================ # Running Analysis Across Unit Types, AKA Cluster Experiments URL: https://docs.statsig.com/metrics/different-id ================================================================================ # Running Analysis Across Unit Types, AKA Cluster Experiments There are two common scenarios where the experiment assignment unit differs from the analysis unit: 1. Measuring session-level metrics for a user-level experiment. Ratio metrics commonly solve this scenario (covered on this page). 2. Measuring logged-in metrics (eg. revenue) on a logged-out experiment. There are two solutions: a. Running the experiment at the [device-level](https://docs.statsig.com/guides/first-device-level-experiment), with device-level metrics collected even after the user is logged-in. b. Using [ID resolution](https://docs.statsig.com/statsig-warehouse-native/features/id-resolution). This page explains how to set up the first scenario using Warehouse Native. ![Workflow diagram for analyzing metrics at different ID levels](https://docs.statsig.com/images/metrics/different-id/0b75615f-2b66-44f4-b6e0-e0bd3e555199.png) ## Example: Organizations and users Scenario: - Your metrics source has both `org_id` and `user_id`. - The relationship between `org_id` and `user_id` is 1-to-many. A single `org_id` can map to multiple users (`user_id`), but a `user_id` maps to only a single `org_id`. - Statsig assigns your experiment at the `org_id` level. - You're interested in understanding the treatment effect at the `user_id` level, such as revenue per user. ### 1. Set up the metric source with `org_id` as an ID type - In this table, each row of data should have both `org_id` and `user_id`. ![Metric source table setup with org_id and user_id fields](https://docs.statsig.com/images/metrics/different-id/a99a4577-8be5-4001-ac4d-2297f3b2fff0.png) ### 2. Choose your assignment source, where the unit of assignment is `org_id` ![Assignment source configuration selecting org_id unit](https://docs.statsig.com/images/metrics/different-id/16472cd7-1aa1-44a2-9a6b-0f789ac5308e.png) ### 3. Define your metric of revenue per `user_id` - Your denominator should be `count distinct user_id` instead of `unit count`, because `unit count` is equivalent to `count distinct org_id` in an `org_id` level experiment. ![Metric definition screenshot showing revenue per user_id formula](https://docs.statsig.com/images/metrics/different-id/ca4c9076-28e1-4cf8-8aa1-2127def7d771.png) ### 4. Set up the experiment with `org_id` ![Experiment setup specifying org_id as unit type](https://docs.statsig.com/images/metrics/different-id/02f9c6bb-0b32-4caf-a529-5bacc2a56d44.png) ## How the Stats Engine handles cluster experiments The Stats Engine uses the delta method to calculate variance and confidence intervals. - For mean metrics, the Stats Engine records the number of observations per exposed unit in the records column of the staging data. This value acts as the denominator or cluster-size value for delta calculations. - For general ratio metrics, the Stats Engine tracks the two-component metrics (the ratio and the denominator) as independent metrics, then combines them during the pulse analysis to derive a single metric. For more information about the delta method, go to [Statsig - Delta Method Methodology](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method). The delta method accounts for the covariance between the numerator and the denominator (more users per org correlates with more revenue). Refer to section 3 of [this paper](https://alexdeng.github.io/public/files/kdd2018-dm.pdf) for details. The delta method also applies when analyzing event-level outcomes, such as average purchase value, where randomization occurs at the user level, and each user may experience multiple session events. ================================================================================ # Setup Checklist URL: https://docs.statsig.com/statsig-warehouse-native/guides/checklist Updated: 2025-09-18 ================================================================================ # Setup Checklist This checklist verifies your Statsig Warehouse Native setup before you launch your first experiment. After you've connected your warehouse and set up both metrics and assignment sources, check the following items: 1. Primary keys 2. Timestamps 3. Duplication 4. Data availability After completing these checks, your offline results should align with those in the Statsig console when you disable advanced features. ## 1. Primary keys When setting up an experiment, you can select the unit of assignment, acting as the primary key to join the assignment with metrics. The assignment source and the metrics source must use the same primary key. In an Analyze-Only experiment, you can select this primary key from the unit IDs your assignment source defines. - Ensure the unit ID in your assignment source matches the unit ID in your metrics source. In an Assign and Analyze experiment, the Statsig SDK generates the primary key (unit ID). - You can verify this unit ID in the statsig\_forwarded\_exposures table within the assignment sources. - You must either forward the unit ID to the SDK ([docs](https://docs.statsig.com/client/introduction)) or use the SDK to manage your features and correspondingly generate the metrics table. ## 2. Timestamps Analyze metric data only after Statsig exposes a user to the experiment. Pre-experiment data has no average treatment effect, so including it dilutes results. Statsig uses a timestamp-based join for this purpose, with an option for a date-based join for daily data. The join should look like the SQL snippet below: ```sql WITH metrics as (...), exposures as (...), joined_data as ( SELECT exposures.unit_id, exposures.experiment_id, exposures.group_id, metrics.timestamp, metrics.value FROM exposures JOIN metrics ON ( exposures.unit_id = metrics.unit_id AND metrics.timestamp >= exposures.first_timestamp ) ) SELECT group_id, SUM(value) as value FROM joined_data GROUP BY group_id; ``` ## 3. Exposure duplication Deduplicate exposure data before joining to ensure a single record per user. Many vendors also manage crossover users (users present in more than one experiment group) by removing them from analysis or alerting when this occurs with high frequency. ```sql SELECT unit_id, experiment_id, MIN(timestamp) as first_timestamp, COUNT(distinct group_id) as groups FROM <exposures_table> GROUP BY unit_id, experiment_id, group_id HAVING COUNT(distinct group_id) = 1; ``` ## 4. Data availability When comparing a platform analysis to an existing experiment analysis that was run in the past, the underlying data may have fallen out of retention or been deleted. To check this, compare the table's retention policy to the analysis dates used in your original experiment analysis to confirm the data still exists. ## Verify that results match After completing these four checks (primary keys, timestamps, exposure duplication, and data availability), your offline analysis should produce results that match those in the Statsig console. > **Note:** > > The Statsig Console includes several advanced features, such as [winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization#winsorization-statsig-whn), [CUPED](https://docs.statsig.com/experiments/statistical-methods/variance-reduction#cuped), and [the delta method](https://docs.statsig.com/experiments/statistical-methods/variance#ratio-and-mean-metrics) to address ratio metrics. Disable these features initially when comparing results. [This article](https://www.statsig.com/blog/how-to-analyze-an-experiment-from-databricks-tables) provides an example of conducting offline calculations in Databricks. If you have additional questions, send Statsig a Slack message. ================================================================================ # Warehouse Native Debugging Guide URL: https://docs.statsig.com/statsig-warehouse-native/guides/debugging Updated: 2025-09-18 ================================================================================ # Warehouse Native Debugging Guide ## Common debugging scenarios Statsig Warehouse Native proactively monitors your data jobs and notifies you when results look off. This guide helps you diagnose the errors, missing data, and result discrepancies that complex data sources can cause, then reconcile Statsig's analysis with your own. ## Common issues that cause errors or missing data ### Exposures appear in Diagnostics but not in the warehouse An exposure in Diagnostics doesn't necessarily qualify for warehouse forwarding. Check the experiment's group split. By default, the daily export excludes groups at 0% or 100%. This is separate from the experiment's overall allocation. Results reloads may forward recent exposures before the daily export, but these updates are best-effort and can be incomplete. Use the daily export as the authoritative record of eligible exposures. A full reload doesn't rebuild or backfill the forwarded exposures table. For forwarding requirements, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). If you need exposures from experiment groups at 0% or 100%, contact Statsig Support. For export history and monitoring options, go to [Monitor your export status](https://docs.statsig.com/integrations/data-exports/data_warehouse_exports#monitor-your-export-status). ### Mismatched IDs In many cases, you may have multiple versions of the same ID across tables. For example, the user `abc123` in one source might be `USER_abc123` in another, or certain loggers may hash ID values for privacy reasons. This usually triggers a Statsig alert that it was unable to join data between sources. To resolve this: - Go to the relevant sources and run the sample queries to check for obvious ID mismatches. - If no mismatch is obvious, find the job that is unable to join sources and copy the SQL. Working through the SQL query should pinpoint where the mismatch is occurring. ### Conflicting filters Statsig allows a high degree of customization in explore queries and on explore pages. This can lead to scenarios where you add two conflicting filters that, together, never pass. For example: - You have a metric with a cohort window from 7 to 13 days, but set up your experiment analysis to run on users' first 6 days. These two filters return no users. - You create a count metric filtered to `event='purchase'`, and then create a local metric that filters to `event='checkout'`. This set of filters also returns a null set. To resolve conflicting filters, go to the Unit-Level Aggregations jobs (where Statsig renders filters) and search for the metric name of interest in the SQL code. ## Common points of confusion Many data scientists run their own analyses using the Statsig staging data in their warehouse. In some cases, they see very different results. A few common methodology differences tend to explain these discrepancies: ### Join conditions Statsig joins events and metrics to exposures based on the event or metric input data occurring after the user's exposure to the experiment under analysis. If you enable the Treat Timestamp as Date setting, Statsig performs the join by comparing dates. By default, Statsig uses a timestamp. Not having a time filter, or using a date when Statsig uses a timestamp (or vice versa), can yield very different results. ### Winsorization/capping You can configure Statsig to cap or winsorize metrics. If you have extreme outliers, you see significant differences in results if you don't apply this procedure. You can apply winsorization yourself, or create a local metric (or clone the metric) without winsorization. ### CUPED CUPED can greatly reduce variance, and for aggregation (non-ratio) metrics can shift the group-level mean estimates if there is pre-experiment bias. You can disable CUPED in the scorecard at any time to view the non-CUPED results for comparison. ### Metric types In some cases, users have assumed that their input data is binomial, meaning the metric is only 1 or 0 at a unit/user level. If this isn't the case and you configure the metric as a count or sum, the result can be much higher variance than expected. ================================================================================ # View SQL URL: https://docs.statsig.com/statsig-warehouse-native/guides/sql Updated: 2025-09-18 ================================================================================ # View SQL Statsig Warehouse Native runs SQL in your warehouse to generate experiment results. The queries are fully transparent and visible in the console, so you can trace any result back to its calculation, artifacts, and raw events. The [pipeline-overview](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview) describes how Statsig orchestrates queries to produce experiment results. To debug or inspect details, find the experiment-specific SQL by going to the experiment’s Pulse view, then selecting view history, then view details on a specific pulse load. That page shows all jobs that contributed to that pulse load. ![Pulse view SQL query details interface](https://docs.statsig.com/images/statsig-warehouse-native/guides/sql/f34e1265-e303-4705-b8cd-1a170a2af91e.png) A few queries with a \[Health Check\] prefix automatically check the health of the experiment. Go to [Monitor an Experiment](https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment) to learn what these queries do. For experiment result calculation queries, below are one-sentence summaries of what each query does. - First exposure: Generate the first exposure time of this experiment at the unit level, given the assignment source. - Exposure summary: Summarize the first exposures at the group level and generate cumulative exposures. - User-level calculations: Calculate unit-level metrics at unit \_ metric \_ day grain. - Windowed rollups: Rollup unit-level metrics at different time windows. - Pulse calculation: Generate the sample parameters that are necessary for calculating treatment effects, such as units, total, mean, standard deviation, population variance, covariance, etc. ================================================================================ # Bootstrapping Your Experimentation Program URL: https://docs.statsig.com/statsig-warehouse-native/guides/experimentation-program ================================================================================ # Bootstrapping Your Experimentation Program Building an experimentation program on Statsig takes five steps: generating product ideas, running your first A/B test, sharing results, accelerating your experiment velocity, and building a culture of learning. You can start on Statsig’s free tier, which includes up to 5M events per month and no limit on the number of team members. ## 1. Generate product ideas Generating ideas for experimentation is essential to running a successful program. Common methods include dogfooding your product, studying competitors, analyzing existing metrics, and gathering UX research and user feedback. Here are three common frameworks used at Statsig and among customers: ### Generate ideas based on your business context 1. **Turn every upcoming feature into an experiment**: - At Statsig, teams place new features behind feature flags. Statsig’s [Feature Flags](https://docs.statsig.com/feature-flags/overview) (also called "gates") automatically convert a feature rollout into an A/B test, measuring the impact on key metrics as the rollout progresses. If your engineering team already uses feature flags for releases, this approach is the most direct path to your first A/B test. 2. **Work backwards from company goals**: - Many customers begin by aligning experiments with strategic company goals. For example, if the goal is to drive adoption growth, break down the goal into actionable metrics (e.g., total revenue, monthly active users). Then run experiments that can move those metrics incrementally. Instead of targeting broad goals like revenue, focus on specific, actionable metrics like checkout completions or user onboarding time. 3. **Break down your business levers**: - Decompose key drivers of your business to reveal more granular areas where you can experiment. For example, an e-commerce business might focus on increasing the checkout rate, which could lead to experiments on improving the CTA, reducing friction, or building urgency. ![Business levers breakdown diagram](https://docs.statsig.com/images/statsig-warehouse-native/guides/experimentation-program/162062869-ead09b8f-0d2e-4c01-8bed-5c40039abe56.png) ### Prioritize your ideas Use a simple return-on-investment (RoI) approach to prioritize your experimentation ideas: - Choose ideas that are simple to execute, easy to measure, and high in potential. - Start with ideas that are easy to implement. After running a few experiments, focus on higher-impact or more controversial ones. A prioritized list of ideas accounts for more than half the work in running a successful experimentation program. > **Tip:** > > **(Optional) Create a Backlog** > > You can create an experimentation backlog from your list of ideas. Because running experiments often generates more ideas, treat the backlog as optional and useful for future planning. ## 2. Run a simple A/B test ### Clarify your hypothesis Start by formulating a hypothesis for one of your high-priority ideas. A well-framed hypothesis defines the expected outcomes of your experiment, which makes it easier to align with stakeholders and evaluate results objectively. A hypothesis consists of three key elements: **Action**, **Predicted Outcome**, and **Rationale**. Example: | Element | Example | | --- | --- | | **Action** | If you reduce the number of fields on the sign-up page | | **Predicted Outcome** | Then the percentage of users that complete sign-up will increase | | **Rationale** | Because users will spend less time and effort, leading to higher completion rates | ### Create your experiment To create an A/B test, go to the [Statsig Console](https://console.statsig.com/login): 1. Name your experiment. 2. Define the variants you want to test. 3. Set the percentage of users eligible to participate. ### Set up your application for the experiment To start the experiment: 1. Use a Statsig SDK to assign users to experiment variants. 2. Validate assignments through the **Diagnostics** tab in the Statsig console. Refer to the [quick start guide](https://docs.statsig.com/guides/abn-tests) to set this up. To compute results, you can: - Log events directly from your application. - Pipe events to Statsig through a service like Segment. - Configure Statsig to ingest data from your warehouse. ### Validate your experiment configuration After your application is set up: - Validate the configuration through the Statsig console, which provides a live exposure stream as users encounter different variants. - Statsig flags issues, such as missing identifiers or mismatches between exposure and application events, so you don’t miss results. After validation, select **Start** to begin the experiment. > **Tip:** > > **(Optional) Set a Target End Date** > > Set a target end date using Statsig's power calculator. A target end date ensures you make decisions only after the experiment has gathered enough data for reliable results. > **Tip:** > > **Running Experiments in Registration Funnels** > > If you don't have user IDs for users who haven't signed up yet, create an experiment using a `stableID`, which Statsig SDKs auto-generate. The `stableID` acts as the unit of analysis. > **Tip:** > > **Selecting Key Metrics** > > When setting up an experiment, configure the key metrics to evaluate your hypothesis. Statsig computes results for all your metrics, but focusing on key metrics helps avoid cherry-picking. ### Organize regular experiment reviews Experiment reviews provide a structured environment to discuss results, share insights, and align on decisions. Run weekly or bi-weekly reviews to reinforce a culture of data-driven decision-making and experimentation rigor. ## 3. Share your results Sharing your results widely is key to building momentum for experimentation. Here are a few ways to share insights across your organization: - **Monthly Experimentation Update**: Summarize the number of experiments run, their business impact, and key learnings. - **Slack #experimentation Channel**: Use a dedicated channel to post real-time experiment learnings and foster discussion. - **Weekly Experiment Review**: Open these reviews to a broader audience to increase visibility and foster engagement. ## 4. Accelerate your speed of experimentation ### Cement the value of experimentation As you gain confidence, try balancing ideas with more uncertain outcomes. Counterintuitive results can solidify the value of experimentation and lead to new discoveries. ### Increase experimentation with self-serve experiments Statsig’s results are trustworthy and easy to interpret, making it possible for any team to run experiments. Reduce the barrier to entry for experimentation by educating team members on how to create and run their own experiments. ### Build incentives to run more experiments Encourage engineers and teams to prioritize impact over shipping new features. Reward them for experimentation outcomes rather than the volume of shipped features, ensuring a focus on end-user value. ## 5. Build a culture of learning ### Accelerate learning > “If you double the number of experiments you do per year, you're going to double your inventiveness.” Jeff Bezos, Founder of Amazon Frequent experimentation leads to faster learning, helping teams discover user preferences and make data-driven product decisions. Even inconclusive results can prompt deeper analysis and more informed hypotheses. ### Measure the impact of your experimentation program Evaluate your program’s success using key criteria such as: | Success Criteria | Score | Weight | | --- | --- | --- | | Time spent to set up an experiment | | | | Time spent to prepare experiment results | | | | Percentage of decisions made using trustworthy data | | | | Number of experiments run per week | | | | Quality of experiments run | | | | Time spent indexing/searching past results and discussions | | | Use these criteria to score your team's progress, set goals, and demonstrate the productivity boost from a well-implemented experimentation program. ================================================================================ # Forwarded Data URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data ================================================================================ # Forwarded Data If you log events or exposures through Statsig's SDKs, Statsig can forward that data to your warehouse. Exposure forwarding follows the eligibility rules below. For custom events, refer to [Events](#events). ## Setting up tables for forwarded data By default, when you set up a data connection, Statsig automatically creates tables named `exposures` and `events` to receive forwarded SDK data. To rename these tables, go to the data connection page, open the **Advanced** tab, and update the table names. ![Forwarded data table configuration interface](https://docs.statsig.com/images/whn/forwarded_data_tables.png) > **Note:** > > If Statsig already exported data and you change the table name, Statsig writes future data to the new table. > **Info:** > > Statsig doesn't forward non-production exposures or log events to external warehouses. ## Exposures Statsig exports eligible first exposures to your warehouse daily. The daily export is the authoritative record of exposures that qualify for forwarding. When you load Pulse results, Statsig may also forward recent exposures before the daily export. These updates are best-effort and can be incomplete. The daily export may replace them. A full reload recalculates experiment results. It doesn't rebuild or backfill the forwarded exposures table. ## Which exposures are forwarded? By default, the daily export excludes experiment groups with a 0% or 100% traffic split. This is each group's share of experiment traffic, not the experiment's overall allocation. An experiment at 100% overall allocation with 50/50 groups passes this percentage check. Other forwarding requirements still apply. If you need exposures from experiment groups at 0% or 100%, contact Statsig Support. For feature gates at 0% or 100% rollout, Statsig doesn't forward exposures by default. To forward them, turn on the project and per-gate settings below. Statsig bills these exposures as analytic events. > **Info:** > > To forward gate exposures: > > 1. A project admin goes to _Settings > Project Configuration > Feature Management_ and turns on **Enable exposure tracking for 0/100% rolled out Gates**. > 2. On each gate that needs these exposures, turn on **Store 0/100 Exposures**. An exposure in Diagnostics confirms that Statsig received it. It doesn't confirm that the exposure qualifies for warehouse forwarding. For export history and monitoring options, go to [Monitor your export status](https://docs.statsig.com/integrations/data-exports/data_warehouse_exports#monitor-your-export-status). ## Duplicate exposure records Statsig retains exposure data for 30 days and can't deduplicate beyond that window. After 30 days, Statsig re-sends exposures for units first exposed more than 30 days ago that were re-exposed on a given day. Statsig correctly deduplicates these records during analysis in your warehouse. The table doesn't contain unique user records, even after filtering out best-effort exposure updates, which can also include duplicate records. ## Events If you use Statsig SDKs to capture custom events, Statsig exports those events to your warehouse hourly. Pulse results on metrics derived from those events are as fresh as approximately 1 hour. To check whether Statsig successfully exported forwarded exposures and events, [monitor your export status](https://docs.statsig.com/integrations/data-exports/data_warehouse_exports#monitor-your-export-status). ================================================================================ # Connect Your Warehouse URL: https://docs.statsig.com/statsig-warehouse-native/guides/connect Updated: 2025-09-18 ================================================================================ # Connect Your Warehouse To run analysis on your warehouse, Statsig needs to connect to your warehouse through a service user. You control the access this user gets to your warehouse. In general, Statsig requires: - Read access to metric data and exposures data - Write access to an isolated Statsig Staging database for writing results and exporting data - Access to run jobs and queries > **Note:** > > Warehouse Native is part of Statsig's Enterprise tier. [Contact the Statsig team](https://statsig.com/contact/demo) to get started. ## Choose your warehouse Statsig Warehouse Native supports the following warehouses/tools: - [Snowflake](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/snowflake) - [Athena](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/athena) - [Bigquery](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/bigquery) - [Databricks](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/databricks) - [Redshift](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/redshift) ================================================================================ # Snowflake Connection URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/snowflake Updated: 2025-09-18 ================================================================================ # Snowflake Connection ## How Snowflake connection works Statsig Warehouse Native connects to your Snowflake account to read experiment data and materialize results in a Statsig-specific schema. To set up the connection, Statsig needs the following: - Account Name - Database Name - Schema Name - Service User Name - If authenticating using login credentials: - Service User Password - If authenticating using key-pair authentication: - Private Key - Private Key Passphrase (Optional) The service user needs the following permissions: - READ on any tables you're using for experimentation - USAGE/WRITE on a Statsig-specific schema that Statsig uses to materialize temp tables and results > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. ### Account name For the Account Name field, enter in the format `<id>.<region>.<provider>`. For example: `xy12345.us-central1.gcp` To get this information, navigate to the bottom left of your Snowflake console, as shown below, and copy the link URL: ![Frame 6](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/snowflake/187517221-4bb3dce3-8b8f-4f30-b4d4-fd12e5249722.png) The copied URL looks something like this: `https://xy12345.us-central1.gcp.snowflakecomputing.com` Extract the required Account Name value from this URL. For this example, the Account Name is `xy12345.us-central1.gcp`. > **Info:** > > ### Using <orgname>-<account\_name> for account name > > For the Account Name field, you can also enter your Snowflake [account identifier](https://docs.snowflake.com/en/user-guide/admin-account-identifier.html#format-1-preferred-account-name-in-your-organization), which typically takes the form `<orgname>-<account_name>`. To find the `<orgname>` in the Snowflake console, click on your account profile (usually at the bottom left) to view account details as shown below. > > ![Snowflake account profile interface](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/snowflake/195217037-ad630f37-a8fe-4b61-823f-ce0e8c984ed0.png) ### Database and schema name Provide the Schema and corresponding Database where Statsig materializes results. ![Frame 7](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/snowflake/187517225-017b4626-eaea-443b-a042-59fd474ae657.png) ### Key-pair authentication To set up key-pair authentication, follow the [Snowflake documentation](https://docs.snowflake.com/en/user-guide/key-pair-auth) to generate the private and public keys, then set the public key on the service user. Provide the private key in the field below: ![Key-pair authentication configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/snowflake/1fa7bda1-5d9c-414b-8e2f-7e36b900acfb.png) ### Boilerplate setup SQL To create a Statsig user with sufficient privileges and a Statsig staging schema, run the following code in a Snowflake worksheet with sysadmin and securityadmin roles. Replace `<USER>` and `<PASSWORD>` with your values, which you copy into the Statsig console. Adjust the warehouse size based on the scope of your data. ```sql BEGIN; -- set up variable values to be used in statements later -- make sure to configure user_name and user_password with your own values SET user_name = '<USERNAME>'; -- REPLACE WITH YOUR OWN VALUE SET user_password = '<PASSWORD>'; -- REPLACE WITH YOUR OWN VALUE SET role_name = 'STATSIG_ROLE'; -- change role to sysadmin for warehouse / database steps USE ROLE sysadmin; -- create a warehouse, database, schema and tables for Statsig CREATE OR REPLACE WAREHOUSE STATSIG WITH warehouse_size='XLARGE'; -- adjust based on your data size CREATE DATABASE IF NOT EXISTS STATSIG_STAGING; CREATE SCHEMA IF NOT EXISTS STATSIG_STAGING.STATSIG_TABLES; -- change current role to securityadmin to create role and user for Statsig's access USE ROLE securityadmin; -- create role for Statsig CREATE ROLE IF NOT EXISTS identifier($role_name); GRANT ROLE identifier($role_name) TO ROLE SYSADMIN; -- create a user for Statsig CREATE USER IF NOT EXISTS identifier($user_name) password = $user_password default_role = $role_name default_namespace = STATSIG_STAGING.STATSIG_TABLES default_warehouse = STATSIG; GRANT ROLE identifier($role_name) TO USER identifier($user_name); -- grant Statsig role access to create warehouse and schema GRANT USAGE ON WAREHOUSE STATSIG TO ROLE identifier($role_name); GRANT USAGE ON SCHEMA STATSIG_STAGING.STATSIG_TABLES TO ROLE identifier($role_name); GRANT CREATE SCHEMA, MONITOR, USAGE ON DATABASE STATSIG_STAGING TO ROLE identifier($role_name); -- ONLY GIVE THIS LEVEL OF ACCESS in the staging schema. GRANT CREATE TABLE, CREATE FUNCTION ON SCHEMA STATSIG_STAGING.STATSIG_TABLES TO ROLE identifier($role_name); GRANT SELECT, UPDATE, INSERT, DELETE ON ALL TABLES IN SCHEMA STATSIG_STAGING.STATSIG_TABLES TO ROLE identifier($role_name); GRANT SELECT, UPDATE, INSERT, DELETE ON FUTURE TABLES IN SCHEMA STATSIG_STAGING.STATSIG_TABLES TO ROLE identifier($role_name); GRANT OWNERSHIP ON FUTURE TABLES IN SCHEMA STATSIG_STAGING.STATSIG_TABLES TO ROLE identifier($role_name); -- grant Statsig role read access to database and schema passed in -- do this at a table level, database level, and/or schema level -- for data Statsig needs to access GRANT USAGE ON DATABASE <DATABASE> TO ROLE identifier($role_name); GRANT USAGE ON SCHEMA <DATABASE>.<SCHEMA> TO ROLE identifier($role_name); GRANT SELECT ON ALL TABLES IN DATABASE <DATABASE> TO ROLE identifier($role_name); GRANT SELECT ON FUTURE TABLES IN DATABASE <DATABASE> TO ROLE identifier($role_name); GRANT SELECT ON ALL VIEWS IN DATABASE <DATABASE> TO ROLE identifier($role_name); GRANT SELECT ON FUTURE VIEWS IN DATABASE <DATABASE> TO ROLE identifier($role_name); COMMIT; ``` ### What IP addresses Statsig accesses data warehouses from [Go to FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) ### Additional setup for Warehouse Explorer Warehouse Explorer lets you find and bring data from any table into Statsig for ad-hoc analysis. To enable Warehouse Explorer, grant Statsig additional permission to query the INFORMATION\_SCHEMA metadata tables. These tables allow the Statsig user to read schema, column, and table definitions. ```sql GRANT USAGE ON SCHEMA <DATABASE>.INFORMATION_SCHEMA TO ROLE identifier($role_name); ``` ================================================================================ # Athena Connection URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/athena Updated: 2025-09-18 ================================================================================ # Athena Connection ## Athena Warehouse Native overview Connecting Amazon Athena lets Statsig Warehouse Native read your experiment data and manage staging tables directly in your AWS account. To set up the connection, Statsig needs the following: - An S3 Bucket - A Glue Database for staging - An S3 Query Result Location - Athena Access Permissions (using an AWS Role or an AWS User) ## Set up Statsig staging structure 1. Create or choose an S3 Bucket. Statsig uses a subfolder inside this S3 Bucket to store all staging data. Statsig has write-access to ONLY this scoped subfolder of this S3 Bucket (specifically labeled `Statsig S3 Folder` in your Data Connection settings in the Statsig Console). 2. Create or choose a Glue Database (can be `default`). Statsig uses this as a staging Database to create and manage tables. Statsig can drop/create tables within ONLY this staging Database. 3. Choose an S3 Query Result Location folder within the S3 Bucket. This S3 location acts as the Output Location for `SELECT` queries you run in your Athena Warehouse. You can specify this location either: - Explicitly as an S3 location (ex: `s3://my_bucket/my_query_results_folder/`) - OR as part of a setting within an Athena Workgroup - NOTE that your workgroup must have the 'Query result location' field populated accordingly 4. Add this information, along with your AWS Region, to your Data Connection settings in the Statsig Console. ## Grant permissions to Statsig Grant the following permissions for Statsig from your AWS console: - READ on any tables and data you're using for experimentation - USAGE and WRITE on a Statsig-specific schema used to materialize temp tables and results. This enables caching and incremental loads. You specify which Glue Database and S3 Bucket to use, and Statsig creates a Statsig S3 Subfolder for staging operations. 1. Create an AWS IAM Policy to house the required access permissions This policy contains the permissions Statsig requires to access your warehouse. You can return to this policy later and edit it as needed. - In your AWS IAM Dashboard, select the Policies page under the Access Management tab - Click 'Create policy' - Switch the Policy Editor type from 'Visual' to 'JSON' - Copy and paste the below JSON template block - Replace the placeholders with your setup information and the Statsig S3 Folder (specified in your Statsig project's Data Connection settings) - Specify all S3 locations and Glue Databases of any read-only assignment/metric data - Remove the descriptor comments ```json { "Version": "2012-10-17", "Statement": [ // Allow Statsig to recognize your staging S3 Bucket { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], "Resource": "arn:aws:s3:::__S3_BUCKET__" }, // Allow Statsig to read events/exposures data from your S3 Buckets { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::__PATH_TO_YOUR_READONLY_DATA__/*" }, // Allow Statsig to read events/exposures tables from your Glue Databases { "Effect": "Allow", "Action": [ "glue:GetTable", "glue:GetTables", "glue:GetDatabase", "glue:GetDatabases", "glue:GetPartition", "glue:GetPartitions" ], "Resource": [ "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:database/__YOUR_READONLY_DATABASE__", "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:table/__YOUR_READONLY_DATABASE__/*" ] }, // Allow Statsig to read/write/use data and tables in an isolated staging S3 subfolder { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "athena:StartQueryExecution", "athena:GetQueryResults", "athena:GetQueryExecution", "athena:StopQueryExecution", "glue:GetTable", "glue:GetTables", "glue:CreateTable", "glue:UpdateTable", "glue:DeleteTable", "glue:GetPartition", "glue:GetPartitions", "glue:CreatePartition", "glue:UpdatePartition", "glue:DeletePartition", "glue:BatchCreatePartition", "glue:BatchDeletePartition", "glue:GetDatabase", "glue:GetDatabases" ], "Resource": [ "arn:aws:s3:::__S3_BUCKET__/__PATH_TO_S3_QUERY_RESULTS_FOLDER__/*", "arn:aws:s3:::__S3_BUCKET__/__STATSIG_S3_FOLDER__/*", "arn:aws:athena:__REGION__:__YOUR_AWS_ACCOUNT_ID__:workgroup/__WORKGROUP_NAME__", "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:catalog", "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:database/__GLUE_STAGING_DATABASE__", "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:table/__GLUE_STAGING_DATABASE__/*" ] } ] } ``` 2. Create an IAM Role or IAM User: #### IAM Role With an IAM Role, Statsig assumes your IAM Role through a Statsig Service Account. The Statsig Account ID for this service account is in your Data Connection settings in the Statsig Console. Statsig runs queries on behalf of this IAM Role. Optionally, you can add an External ID condition for added security ([AWS External ID Docs](https://aws.amazon.com/blogs/security/how-to-use-external-id-when-granting-access-to-your-aws-resources/)). Statsig generates this External ID, which you can view in your Data Connection settings in the Statsig Console. - In your AWS IAM Dashboard, select the Roles page under the Access Management tab - Click 'Create role' - Choose 'AWS account' as the Trusted entity type - Choose 'Another AWS account' from the options, and copy the Statsig Account ID from your Statsig console - Optionally, require use of an External ID for connections to this role (also specified in your Statsig console) - Continue to next step of setup, and select your IAM Permissions Policy from earlier - Name, review, and create; your Trust Policy JSON should follow the format below: ```json { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "sts:AssumeRole", "Principal": { "AWS": "__STATSIG_ACCOUNT_ID__" }, "Condition": { "StringEquals": { "sts:ExternalId": "__ROLE_EXTERNAL_ID__" } } } ] } ``` - Add the ARN for this IAM Role to your Data Connection settings in the Statsig Console #### IAM User With an IAM User, Statsig uses AWS Access Keys to access the IAM User and runs queries on behalf of that user. - In your AWS IAM Dashboard, select the Users page under the Access Management tab - Click 'Create user' - Name your user - On the next step of setup, choose 'Attach policies directly' and select your newly created Permissions Policy - Under the Security Credentials tab of this newly created User, find the Access Keys block - Click 'Create access key', and choose 'Third-party service' from the Use Case options - Add the Access Key and Secret Access Key to your Data Connection settings in the Statsig Console ## Set up reading data from your events/exposures tables 1. Give Statsig read-access to your Glue Database containing any tables you need Statsig to read from. Do this by adding the following to your AWS IAM Permissions Policy: ```plaintext { "Effect": "Allow", "Action": [ "glue:GetTable", "glue:GetTables", "glue:GetDatabase", "glue:GetDatabases", "glue:GetPartition", "glue:GetPartitions" ], "Resource": [ "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:database/__YOUR_READONLY_DATABASE__", "arn:aws:glue:__REGION__:__YOUR_AWS_ACCOUNT_ID__:table/__YOUR_READONLY_DATABASE__/*" ] } ``` 2. Give Statsig read-access to your S3 Bucket locations of the tables you need Statsig to read from. Add this to your AWS IAM Permissions Policy: ```plaintext { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::__PATH_TO_YOUR_READONLY_DATA__/*" } ``` 3. In Statsig, when setting up Metric or Assignment Sources, select from these tables using `"database"."table"` format. 4. Repeat for any additional tables, or when you need to read a new table from Statsig. > **Info:** > > If your data warehouse is IP protected, add Statsig IP ranges to your allow list as part of your setup steps. After you create the connection, Statsig automatically sets up the [Pipeline Overview](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview), so you don't need to configure pipeline observability yourself. ## Gate and experiment key naming Athena supports gate and experiment keys that contain `.` and `-`, so it reaches naming parity with BigQuery and Databricks Warehouse Native. AWS Glue Data Catalog allows only the characters `[A-Za-z0-9_]` in table names, so earlier Athena metric jobs required keys that avoided `.` and `-`. Statsig now sanitizes table names for you: `.` becomes `__p__` and `-` becomes `_`, the same mapping BigQuery uses. Statsig keeps the Iceberg S3 locations and the retry and cleanup path in sync with the sanitized names. Existing keys without `.` or `-` don't change, and you don't need to rename anything. You can use any naming convention on Athena. ## Additional Athena resources ### S3 bucket encryption guide Statsig supports encryption for all accessed S3 Buckets. To allow Statsig to access encrypted S3 Buckets: 1. From the AWS Key Management Service console, create a new KMS Key using the below cryptographic configuration settings: ([AWS SSE KMS Docs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html?icmpid=docs_s3_hp_batch_ops_create_job_encryption_key_type)) - Key Type: Symmetric - Key Usage: Encrypt and Decrypt - Advanced Options - Key Material Origin = KMS - Regionality = Single-Region Key 2. From the Key Policy tab of your newly created KMS Key, find the Key Administrators box. Click Add, and select the AWS IAM Role/User you provided to Statsig as an administrator. 3. Navigate to your S3 Bucket. From your S3 Bucket Properties tab, find the Default Encryption box. Click Edit, and select the below default encryption settings: - Encryption Type: SSE-KMS - AWS KMS Key: Enter AWS KMS Key ARN - (enter your newly created KMS Key ARN in the box) - Bucket Key: Enable ### Statsig staging architecture details Statsig creates all staging tables within the Glue Staging Database that you create and provide. Statsig creates all tables as table-type `ICEBERG`, except the forwarded exposures and events tables, which are regular `EXTERNAL` Athena tables. Statsig stores all staging data within the `Statsig S3 Folder` of your S3 Bucket. Statsig manages the structure within this subfolder. The folder structure is as follows: - S3 Bucket (you create and provide Statsig the name) - Statsig S3 Folder (Statsig creates and names, name provided in the Data Connection settings in your Statsig Console) - Experiment Folder(s) (Statsig creates a subfolder for each unique experiment you run, named `experiment-<ID>`) - Staging Tables Folders (Statsig puts data for each created staging table in its own subfolder, named intuitively after the data they contain) - `metadata/` - Iceberg Table Metadata - `data/` - Table Data Files (stored as Parquet) - `statsig_forwarded_exposures/` - Forwarded Exposures Table Subfolder (named in the Data Connection settings in your Statsig Console) - Dates in `YYYY-MM-DD` format (Statsig partitions this table by date, and there is a subfolder for each date that has exposure data sent through Statsig) - Forwarded Exposure Data - `statsig_forwarded_events/` - Forwarded Events Table Subfolder (named in the Data Connection settings in your Statsig Console) - Dates in `YYYY-MM-DD` format - Forwarded Event Data ### What IP addresses does Statsig use to access data warehouses Go to the [FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) for the list of IP addresses. ================================================================================ # Bigquery Connection URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/bigquery Updated: 2025-09-18 ================================================================================ # Bigquery Connection ## How BigQuery connection works Connecting Google BigQuery lets Statsig Warehouse Native read your experiment data and write staging tables in your Google Cloud project. You can set up the connection two ways: - Grant Permissions to a Statsig-owned Service Account - Provide Credentials for Your Own First-Party Service Account In both cases, you need: - Your BigQuery Project ID - The dataset Statsig uses to save temporary tables and materialized results After you choose your method, start by enabling the BigQuery source in your project settings. ## Grant permissions to Statsig's service account Grant Statsig access to your BigQuery data from your Google Cloud console. 1. In your BigQuery's [IAM & Admin settings](https://console.cloud.google.com/iam-admin/), add the Statsig service account you copied in the Statsig Console as a new principal for your project and give it the following roles: - `BigQuery User` ![BigQuery IAM permissions configuration](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/bigquery/198107543-b3bcc19a-3231-4128-be42-a5dd52fb168a.png) 2. Navigate to your [BigQuery SQL Workspace](https://console.cloud.google.com/bigquery), choose the dataset, click **+ Sharing** > **Permissions** > **Add Principal**, and give the same Statsig service account the "BigQuery Data Viewer" role. Repeat for any datasets you want the service user to access. ![BigQuery dataset permissions interface](https://docs.statsig.com/images/integrations/data-imports/bigquery/175113611-90e618ad-f6e8-4005-933e-2a5660a14466.png) 3. Repeat step 2 to give the "BigQuery Data Editor" role on the dataset Statsig uses for staging data. > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. The service account has the required permissions to run queries and materialize results. ## Using a first-party service account > **Warning:** > > Statsig doesn't recommend this method. Using service accounts is the [preferred option for enhanced security](https://docs.cloud.google.com/iam/docs/migrate-from-service-account-keys). 1. On the BQ service accounts page, click 'Manage Keys' for the service account you want to use. ![BQ 1st party service account](https://docs.statsig.com/images/1stprtybq.png) 2. Create a new JSON key (which downloads a JSON file). ![BQ 1st party service account](https://docs.statsig.com/images/1stprtybq2.png) ![BQ 1st party service account](https://docs.statsig.com/images/1stprtybq3.png) 3. In the **Statsig Settings** -> [Data Connection](https://console.statsig.com/data_connection/connection_setup) tab, paste the above key into the **Service Account Private Key** field under the **Advanced** toggle. ## Additional BigQuery resources ### BigQuery project ID Find your BigQuery Project ID: 1. Click on your Project Dropdown inside your Cloud Console. ![Frame 4](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/bigquery/187518062-7027f682-d1fd-445e-9947-897e44ea929e.png) 2. Copy and paste relevant Project ID from the modal pop-up. ![Frame 5](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/bigquery/187517901-9e7fd237-8325-4254-a1bd-c75f0ea08497.png) > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. ### Statsig Customer ID on BigQuery C01d5f80s ### IP addresses Statsig accesses data warehouses from [Go to FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) ### Additional setup for Warehouse Explorer Warehouse Explorer lets you find and bring data from any table into Statsig for ad-hoc analysis. Statsig reads from `INFORMATION_SCHEMA.COLUMNS`, which requires explicit permission to view table metadata. Grant access by repeating steps 1 and 2 from the [Grant Permissions](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/bigquery#grant-permissions-to-statsig%E2%80%99s-service-account) section for the "BigQuery Metadata Viewer" role. ================================================================================ # Databricks Connection URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/databricks Updated: 2025-09-18 ================================================================================ # Databricks Connection ## How Databricks connection works Connecting Databricks lets Statsig Warehouse Native read your experiment data and write staging tables in your Databricks workspace. To set up the connection, you need the following: - Your Databricks Server Hostname - An HTTP Path to a Cluster or SQL Warehouse - A staging database for writing results and intermediate tables into - An access token with read access on your experiment data and write access to the staging database - Use either Serverless SQL Warehouse or an always-on cluster. Statsig uses interactive queries during setup (and some analysis). These queries fail if the cluster takes several minutes to start. Start by enabling the Databricks source in your project settings. ## Databricks access considerations For users whose primary warehouse is a DBFS-based Delta Lake, Databricks permissions are simple to manage. For customers using Databricks as an intermediary to other data sources, ensure that Databricks and the Statsig service user have appropriate access to your storage. For example, Athena tables require access to S3. Permissions can be reset over time, which causes errors. To validate permissions, try creating tables through the Statsig console. ## Getting connection information 1. Follow the [Databricks documentation](https://docs.databricks.com/integrations/jdbc-odbc-bi.html#get-connection-details-for-a-cluster) to get the hostname and HTTP path of the cluster you use to run your experimental analysis. You may want to create a dedicated cluster for this purpose. ![credentials](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/databricks/242474157-e6329ea8-92ae-43af-95dc-7bce2a26a3e6.png) 2. Follow the [personal access token instructions](https://docs.databricks.com/dev-tools/auth.html#databricks-personal-access-tokens) to get the token used to calculate experiment results on your warehouse. Alternatively, follow the [service principal instructions](https://docs.databricks.com/en/administration-guide/users-groups/service-principals.html#manage-personal-access-tokens-for-a-service-principal) to get a token for a service principal. ![databricks info](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/databricks/188731186-ecdc0872-de06-4576-b387-fa08bdca447d.png) 3. Create or choose a database to use. For example, you could run this sql in a notebook: ```sql staging_database_name = '<my_name>' spark.sql(f"CREATE DATABASE IF NOT EXISTS {staging_database_name}") ``` > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. ### IP addresses Statsig accesses data warehouses from [Go to FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) ### Additional setup for Warehouse Explorer Warehouse Explorer lets you find and bring data from any table into Statsig for ad-hoc analysis. When you enable Unity Catalog, Statsig reads from `<CATALOG_NAME>.information_schema.columns`. You can provide the catalog name in Data Connection settings, under the Advanced section. You may also need to provide read access to the catalog and the `information_schema` schema: ```sql GRANT USE CATALOG ON CATALOG <CATALOG_NAME> TO <STATSIG_USER>; GRANT USE SCHEMA ON SCHEMA <CATALOG_NAME> .information_schema TO <STATSIG_USER>; ``` `<STATSIG_USER>` is the user associated with the access token you provided to Statsig. ================================================================================ # Redshift Connection URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/redshift Updated: 2025-09-18 ================================================================================ # Redshift Connection ## How Redshift connection works Statsig Warehouse Native connects to your Amazon Redshift cluster to read experiment data and write results to a staging schema you control. To set up the connection, Statsig needs the following information: - Cluster Endpoint - A service user Username - A service user Password - A staging schema that Statsig can write results to > **Note:** > > Statsig doesn't support SHA256 passwords. Use MD5 to avoid issues. Find this information in your AWS console within your specific cluster, as the image below shows. The service user must be able to read the required experiment data and write to the Statsig staging schema you specify. ![Frame 1](https://docs.statsig.com/images/statsig-warehouse-native/connecting-your-warehouse/redshift/187515405-17fa7d90-44e1-422f-87a7-cfde090637ed.png) When you save the connection, Statsig runs a series of test commands to validate permissions. For example, Statsig creates a temp table, runs a select/delete statement on that table, and drops the table. > **Note:** > > The provided Service Account requires the following attributes: `enable_case_sensitive_identifier`, `enable_case_sensitive_super_attribute`. If you haven't already set these, Statsig sets them to TRUE upon setup completion. ## SSH tunneling For Redshift connections, Statsig supports SSH tunneling into your Redshift cluster for more secure and private database access. To enable access, Statsig requires: - SSH Host - SSH Port - SSH User Statsig uses this information to generate an SSH key. Add this generated key to your `~/.ssh/authorized_keys` file on your SSH proxy machine to enable SSH tunneling. ### What IP addresses does Statsig access data warehouses from > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. [Go to FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) ### Additional setup for Warehouse Explorer Warehouse Explorer lets you find and bring data from any table into Statsig for ad-hoc analysis. To enable Warehouse Explorer, you may need to grant Statsig additional permission to query the `pg_table_def` metadata. Query results include only schemas that Statsig has read access to. A superuser or admin can grant access to additional relevant schemas and table metadata in `pg_table_def` by running: ```sql GRANT USAGE ON SCHEMA <RELEVANT_SCHEMA> TO <STATSIG_USER>; GRANT SELECT ON ALL TABLES IN SCHEMA <RELEVANT_SCHEMA> TO <STATSIG_USER>; ``` `<STATSIG_USER>` is the service user username you provided to Statsig. `<RELEVANT_SCHEMA>` is the name of the schema to include in Warehouse Explorer results. ================================================================================ # Other Warehouses URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/other Updated: 2025-09-18 ================================================================================ # Other Warehouses ## Other warehouses Statsig can connect to data warehouses beyond the ones with a dedicated setup guide. Statsig accesses your warehouse through API calls and needs your cluster address and authentication details, similar to running queries through DataGrip, Python, or other tools. Statsig is selective about which warehouses it supports long-term, but can discuss your needs and build a solution for your cloud provider. ## Permissions Statsig requires read permissions on any input tables for your analysis. Statsig also requires full CRUD (create/read/update/delete) permissions on a "sandbox" where Statsig stores staging data and intermediate data artifacts as part of experimentation pipelines. ### What IP addresses does Statsig access data warehouses from > **Info:** > > If your data warehouse is IP protected, you must include allowlisting of Statsig IP ranges in your setup steps. [Go to FAQ](https://docs.statsig.com/data-warehouse-ingestion/faq#what-ip-addresses-will-statsig-access-data-warehouses-from) ================================================================================ # Egress, Privacy, & Storage URL: https://docs.statsig.com/statsig-warehouse-native/analysis-tools/data-privacy Updated: 2025-09-18 ================================================================================ # Egress, Privacy, & Storage With Statsig Warehouse Native, user-level data stays in your warehouse: Statsig reads it directly from your source of truth without copying it or moving it out. Statsig needs only a limited set of permissions, reads small samples and aggregated results, and writes intermediate tables to a staging environment you control. ## Permissions The permissions Statsig requires are: - Job Access (where applicable) to run queries as a service user - Read Access on event, metric, and exposure data you want to use for experiment analysis - Statsig only selects from these tables - Read, Write, Delete access in a Statsig Staging environment you specify - In Bigquery this is a dataset - In Snowflake and Redshift this is a schema - In Databricks this is a database, or a database within a separate workspace with a scoped delta share to your production datasets Best practice is to create a new dataset for Statsig Staging to make sure this environment is isolated. Statsig only modifies tables it creates as part of analysis. ## What Statsig reads Statsig only reads two forms of data, both of which are very small (generally in Kilobytes). - Small samples used for validating setup in the following surfaces: - Metrics Tab - Metric Source Tab - Assignment Source Tab - (If using Statsig exposures) Users Tab - Aggregated results at the group or experiment level. This data doesn't contain user IDs and is rolled up at the group, metric, group/metric or experiment level. This includes: - Existing groups and group sizes for experiment setup - Pulse Results - Total exposure counts for power analysis - Daily total metric values - Experiment-level health checks (e.g. distinct metrics, count of exposures) ## Analysis flow During analysis, data stays in your warehouse. Statsig writes intermediate tables and results to the Statsig data staging set. When the results of Health Checks or Pulse become available, Statsig consumes those result sets and stores them on its servers as well (usually < 1000 rows): ![Analysis Flow](https://docs.statsig.com/images/statsig-warehouse-native/analysis-tools/data-privacy/264110212-b9e07098-cd3a-4107-aa3f-6740fc3d8b7a.png) ## Data retention in Statsig Statsig retains customer data in exposure events for a maximum of 30 days for diagnostics and debugging, when using the SDK for assignment. Statsig automatically removes this data after 30 days. ## Storage management Experimentation staging datasets can generate large amounts of data. The data grows with the number of experiments you run. For example, if you have user-day data and run 100 experiments that all expose every user, you get 100 copies of that data. The copies differ slightly based on when users were exposed to each experiment. Statsig includes a table management system to help control storage costs and visibility: - Statsig drops temporary artifacts (tables generated as part of explore queries or pulse results) 2-7 days after creation. This gives some buffer to debug, but Statsig doesn't maintain long-term copies of data. - When you finish an experiment by making a decision, Statsig prompts you to delete the tables. By default, Statsig leaves the result sets (on the order of kilobytes) in your warehouse for reference, but you can override this setting. - At any time, you can drop tables for your experiment from the three-dot menu in the experiment. ================================================================================ # Warehouse Storage URL: https://docs.statsig.com/statsig-warehouse-native/warehouse-management/storage Updated: 2026-08-24 ================================================================================ # Warehouse Storage ## How warehouse storage works Statsig uses its sandbox in your warehouse to cache intermediate tables and result tables. Caching enables incremental reloads (without recalculating metrics for every day of the experiment on each load) and allows you to use these tables for ad-hoc analysis. Statsig stores tables in the sandbox schema or dataset you configured. You can use this location to track storage footprint and manage permissions. ## Conventions and usage Statsig shards tables by entity ID. For example, the experiment `early_user_journey_acceleration` has that identifier in its associated table names for scorecard loads. This naming convention is a reliable way to look up tables for a given experiment. Statsig writes to special tables that appear in metric sources or assignment sources: - pipeline overview: performance statistics for the jobs Statsig runs - statsig\_forwarded\_events: events logged through statsig.log\_event - statsig\_forwarded\_exposures: exposures from experiments, gates, autotunes, and holdouts - statsig\_forwarded\_switchback\_exposures: switchback-formatted exposures - statsig\_daily\_results: rendered results with statistics like p-value Some of these tables have pre-set names; others you configure in data connection settings. Many users ingest these tables as part of internal pipelines. Statsig regularly updates data in these tables, and in some cases backfills up to several days when data delays or repairs occur. To prevent mutable data from causing issues, configure lookback windows. > **Note:** > > Exposures don't necessarily deduplicate. Fast-forwarded exposures duplicate records from daily exports, and Statsig retains only 30 days of history for warehouse native projects. After 30 days, Statsig treats a given unit's exposure as new and re-exports it. ## Volume Scorecard loads generate a varying number of tables depending on the number of metric sources accessed and the types of metrics loaded. Statsig may also materialize intermediate tables before or after large operations, which reduces compute cost. This process can produce a large number of artifacts. Customers running 300+ experiments have encountered default quota limits on vendors like Databricks. You can address quota limits by requesting a quota increase or configuring the TTLs described in the Management section. ## Management Transient tables have a short TTL, usually 1-2 days, and Statsig automatically cleans them up. Other tables are permanent by default. You can clean them up from the experiment in Statsig's console or as part of launching an experiment. You can also configure TTLs per table type in the data connection section of a project's settings. Plan to manage storage using your own warehouse tools in addition to Statsig's systems. For example, clean up entities that haven't been accessed or modified in the last month. Ideally, manual cleanup isn't necessary given TTLs, but there are known cases where Statsig's internal tracking can consider a table dropped when it still has a storage footprint. Statsig can't guarantee that it removes all tables. ### How TTLs work When Statsig creates or modifies a managed table, it schedules a cleanup at the current time plus the TTL. For example, if Statsig writes a Result table on 2024-06-01 and you configure Result tables with a 14-day TTL, Statsig schedules a deletion for 2024-06-15. If Statsig modifies that table on 2024-06-07 (for example, through a scorecard reload), it resets the deletion request to 2024-06-21, overwriting the existing one. This behavior means incremental updates on long-running experiments keep their staging data until the experiment stops. A TTL change doesn't retroactively affect existing tables' deletion requests. The new TTL applies at the next scorecard load for the relevant experiment. ### Types of tables for TTL - `Result Datasets`: the final tables Statsig creates at the end of an experiment or gate reload, containing aggregated group-metric level data. These are generally small (1 row per metric/day/group/dimension) and useful for post-hoc analysis. - `Intermediate Tables`: all other tables Statsig writes to during an experiment reload. These can be large because they contain user-level data. Statsig reuses them for incremental and metric reloads. - `Transient Datasets`: tables created for one-off queries (most commonly Explore queries and Power Analyses), or temporary datasets used while creating `Intermediate Tables` as a performance optimization. By default, Statsig drops these after 2-3 days unless you override them with a configured TTL. **Explore query dependencies**: Explore queries rely on permanent staging tables. These tables reduce the need to recompute data for analysis the scorecard run already performed. Unlike results tables (which Statsig caches locally on its servers), you must maintain permanent staging tables in your warehouse for Explore queries to function. Maintaining these tables avoids reprocessing large volumes of data that may contain PII or other sensitive information. ### Building your own cleanup job The safest deletion rule is per-experiment, not per-table-type: only delete tables belonging to experiments that have concluded. When matching tables to an experiment by name, match against your full experiment list rather than one loose pattern per experiment (a substring match like `%my_experiment_v1%` also catches `my_experiment_v10`), and note that hyphens in experiment names become underscores in table names. - Statsig doesn't write experiment status to any table in your warehouse. To check whether an experiment has concluded programmatically, use the Console API's [List Experiments](https://docs.statsig.com/api-reference/experiments/list-experiments) endpoint (`GET /console/v1/experiments`). Each experiment has a `status` of `setup`, `active`, `decision_made`, `abandoned`, or `archived`; treat `decision_made`, `abandoned`, and `archived` as concluded. - Don't delete tables for an experiment that still has a scheduled reload, even if its allocation window has ended. Scheduled reloads depend on existing staging tables and fail until a full reload recreates them. - Deleting conservatively is recoverable. Statsig caches the results shown in the console, and dropping staging tables doesn't affect them. If you later need Explore or a re-analysis on a concluded experiment, a full reload recreates its tables. - Never delete the special tables listed in [Conventions and usage](#conventions-and-usage), under the names configured in your data connection settings. Project TTLs never delete these tables, but your cleanup job should exclude them explicitly. ## Troubleshooting storage issues ### Missing data errors Warehouse Native users may encounter `TABLE_OR_VIEW_NOT_FOUND` errors when required data tables are missing from the warehouse. These errors typically occur when: - **Permanent staging tables have been dropped**: Explore queries and advanced analysis require permanent staging tables, not results or transient staging tables. - **TTL settings have expired tables**: Statsig automatically cleans up tables with configured time-to-live (TTL) settings. - **Incomplete data loads**: Initial experiment setup or data pipeline issues may prevent table creation. #### Resolution steps **For missing staging tables:** missing permanent staging tables require a full reload to recreate the staging dataset. **For general missing tables:** 1. Check your warehouse's TTL settings in the data connection configuration. 2. Verify that permanent staging tables exist in your configured sandbox schema. 3. If you manually dropped tables, trigger a full data reload. 4. Contact support if tables are still missing after reload, or if you didn't drop them. #### Storage dependencies Warehouse Native uses several types of tables with different storage patterns: - **Permanent staging tables**: required for Explore queries and advanced analysis. - **Transient staging tables**: short-lived intermediate tables with a mix of automatic cleanup (1-2 days TTL) and permanent storage (small tables useful for ad-hoc analysis like regression coefficients). - **Results tables**: output statistics from the pipeline, copied and cached locally on Statsig servers. > **Note:** > > Vacuum jobs don't affect staging tables used by Statsig. ================================================================================ # Pipeline Activity URL: https://docs.statsig.com/statsig-warehouse-native/warehouse-management/pipeline-activity ================================================================================ # Pipeline Activity Pipeline Activity reports the state of Statsig Warehouse Native pipeline runs: which runs are executing right now, which recent runs succeeded or failed, how long each one took, and the SQL each job sent to your warehouse. Open it at _Data > Pipeline Activity_ in the Statsig Console when a reload looks stuck, a Pulse result looks stale, or you want to know what the pipeline has been running in your warehouse over the last two weeks. Use Pipeline Activity for run status across every experiment and gate in the project. Use [Pipeline Overview](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview) instead when you want to understand the pipeline itself: the stages it runs, the tables it writes into your warehouse, and the metric source and dashboard Statsig provisions for it. For the exposure and metric health of a single experiment, go to [Experiment Diagnostics](https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment). Pipeline Activity covers warehouse-native projects. Projects that don't run a Statsig Warehouse Native pipeline have nothing to report, so the page doesn't apply to them. ## What the job list shows The job list holds one row per pipeline run. | Column | What it shows | | --- | --- | | Entity | The experiment or feature gate the run belongs to. | | Run type | The kind of [reload](https://docs.statsig.com/statsig-warehouse-native/features/reloads) the run performed. | | Run ID | The identifier for the run. | | Status | The outcome of a finished run: Success, Failed, Partial failure, or Cancelled. | | Jobs | The jobs that make up the run. The heading changes with the view you select. | | Currently running jobs | The jobs executing at the moment. This column appears only when you narrow the list to active runs. | | Started by | The person or process that triggered the run. | | Turbo mode | Whether the run used [Turbo](https://docs.statsig.com/statsig-warehouse-native/features/turbo). | | Run duration | Elapsed time from run creation to completion, or the time so far for an active run. Sortable. | | Days loaded | How many days of data the run covered. Sortable. | | Schedule | The reload schedule attached to the entity. | | Actions | Controls for the run, including Cancel. This column drops out of the completed-runs view. | > **Note:** > > Run duration is wall-clock time from the moment Statsig created the run, so it includes any time the run spent waiting. It isn't the warehouse execution time for the run's queries. ## Filter the job list Four controls narrow the list: - Run state: every run, or only the runs that are still active. - **Status**: Success, Failed, Partial failure, or Cancelled. - **Entity**: a single experiment or feature gate. This filter covers experiments and gates only. - **Started by**: the person or process that triggered the run. Changing any filter returns the list to the first page. The completed-runs list holds 25 runs per page. ## Read the job runtime chart A stacked bar chart sits at the top of the page and plots daily job runtime grouped by job type. The chart breaks out the largest job types and collects the rest into Other. It covers the last 14 days by default, accepts a range of up to 30 days, and excludes today. Three things shape how the bars add up: - Each bar sums the durations of the jobs that ran that day. Jobs inside a run execute in parallel, so a single day's bar can total more than 24 hours. Read a bar as total job effort, not as elapsed time. - Statsig attributes a run to the day it created the run, in your browser's timezone. A run that starts before midnight and finishes after it counts entirely on its start day. - Where a job has no recorded runtime, Statsig falls back to an estimate, so a bar can mix measured and estimated values. The chart range and the job list filters work independently. Changing the range doesn't filter the table, and filtering the table doesn't redraw the chart. ## Inspect a run 1. Find the run in the job list. 2. Click **View details**. 3. Select a view in the dialog that opens: - **SQL**: the queries the run sent to your warehouse. - **Details**: the run's metadata. - **DAG**: the job graph for the run. - **Timeline**: when each job in the run started and finished. The DAG and Timeline views appear only for runs that carry that data. From either one, click a job to jump straight to that job's SQL. ## Cancel an active run 1. Narrow the job list to active runs. 2. Find the run you want to stop. 3. In the Actions column, click **Cancel**. The job list doesn't poll for status changes. Only the elapsed-time clock advances on its own, so refresh the page or change a filter to pull current status, including after you cancel a run. ## Limitations > **Note:** > > - A clean run history isn't a freshness guarantee. Pipeline Activity reports the runs Statsig dispatched. It can't show a scheduled reload that never got dispatched, so an empty failure list doesn't prove that results reflect your latest warehouse data. Confirm freshness on the entity's Pulse Results. > - Runtime isn't cost. Statsig doesn't read your warehouse billing, so no figure on this page translates into a dollar amount. Compare the runtime trend against your warehouse's own usage and billing views. > - The page doesn't refresh itself. Statuses update when you reload the page or change a filter. ================================================================================ # Warehouse Costs URL: https://docs.statsig.com/statsig-warehouse-native/guides/costs Updated: 2025-09-18 ================================================================================ # Warehouse Costs Statsig Warehouse Native runs experiment analyses and analytics queries on the compute and storage you provide, which adds to your warehouse bill. This page explains how to estimate total cost of ownership, benchmark it against typical usage, and keep it under control. There is some overlap with the [best practices](https://docs.statsig.com/statsig-warehouse-native/guides/best-practices) page; treat that page as an implementation guide and this page as a high-level overview. ## Why do costs matter? Warehouse Native platforms require you to provide compute and storage to run data jobs like experiment analyses and analytics queries. This requirement is a cost center, and can meaningfully drive up your warehouse bill if queries are unoptimized or poorly integrated with your databases. Cost is a major concern for many customers considering a Warehouse Native solution for Experimentation or Analytics. Warehouse Native platforms are very flexible, but that flexibility can lead to unexpected data costs. Understanding total cost of ownership is important when evaluating a platform, as many platforms don't treat it as a primary focus. Statsig started as a cloud-only platform with a strong focus on cost efficiency. By continuously optimizing pipelines on the cloud side of its business, Statsig has developed expertise in cost-saving strategies that it passes on to Warehouse Native customers. ## Benchmarks ### Total cost of ownership Warehouse costs typically hover between 5% and 20% of customers' platform spend with Statsig. There are exceptions depending on usage, but these tend to be on the low end. To avoid selective reporting, the examples below are an anonymized list of the top 5 Statsig Warehouse Native customers on Snowflake, by total warehouse spend: | Company Profile | Experiments Run, 12 Months | Estimated % Contract Value Spent on Compute | | --- | --- | --- | | Multi-sided marketplace (e.g. job search / contracts), 100M-1B in Revenue | 120 | 12% | | Multinational B2C business, 5B-20B in revenue | 210 | 9% | | B2B SaaS, 100M-1B in Revenue | 250 | 11% | | Online Entertainment, 100M-1B in Revenue | 180 | 6% | | Online Services, 50-100M in Revenue | 130 | 20% | These figures are fairly representative of what you can expect using Statsig at scale with reasonable adherence to best practices. Costs do scale with number of experiments; companies running fewer experiments generally see a smaller relative TCO. Relative to experiment size, there is significant variation in spend depending on how many metrics you use, what kind of metrics, and how "dense" your metrics are. The table below shows typical costs when teams follow best practices: | Experiment Size | Cost per Experiment Load | Lifetime Cost per Experiment (4 Weeks with Daily Refreshes & Drilldowns) | Lifetime Cost Using [Turbo Mode](../features/turbo) | | --- | --- | --- | --- | | Small (50k or less units) | < $0.05 | $0.25 - $2.00 | $0.25 - $1.00 | | Medium | < $0.25 | $1.00 - $10.00 | $1.00 - $5.00 | | Large | $0.25 - $10.00 | $5.00 - $280.00 | $3.00 - $50.00 | | Extremely Large (500 Million+ experimental units) | Low Sample with only a handful of companies - Can't Generalize | " | " | > **Note:** > > [Turbo Mode](../features/turbo) is especially efficient for large-scale experiments. It dramatically reduces memory usage, keeping large jobs from spilling to disk and reducing the need for XL clusters to provide enough memory. ### Industry Statsig aims to be best-in-class for Warehouse Native experimentation costs. Customers who evaluate multiple vendors consistently report that Statsig is 50-66% of the cost of other platforms. In cases where Statsig has been more expensive than competitors, the team investigates quickly. For example, a recent customer accidentally used un-partitioned data for their Statsig proof of concept. This unpartitioned data drove up cost relative to another vendor whose tables were partitioned. Statsig followed up by building warnings when source data isn't partitioned. After partitioning, cost went from 120% of the other vendor's cost to under 60%. Multiple customers have migrated to Statsig from other Warehouse Native Experimentation platforms due to cost concerns. Reach out to the Sales team to run an evaluation of relative costs. If you have concerns, or another party claims their solution is more efficient, contact Statsig to discuss. ## Tools for understanding cost Statsig aims to be as transparent as possible about costs. Numerous tools throughout the product help in this regard: ### History In every loaded experiment or gate, you can quickly see the cost of each load. The metrics shown are relevant to your warehouse, for example, slot hours or bytes scanned for BigQuery, uptime for Snowflake, and so on. ![Pipeline History](https://docs.statsig.com/images/statsig-warehouse-native/guides/costs/d2009b64-bbf6-49bf-a3a0-df04b0b89619.png) ### Pipeline overview dashboard Statsig automatically creates a `Pipeline Overview` dashboard in its MEx platform. Statsig writes the underlying data to your warehouse, so you can investigate what is driving costs from Statsig. Many customers have built their own monitoring and alerting on top of this dataset and notify Statsig if they see any changes in cost. ![Pipeline Overview](https://docs.statsig.com/images/statsig-warehouse-native/guides/costs/0c1a1098-d345-458b-b7a0-2cc8bfc1ccfc.png) ### Vendor tooling Use standalone compute and storage resources for Statsig in your warehouse. This makes total cost of ownership easy to understand. Some cost information isn't visible to the platform without administrator rights on your warehouse. If there is a mismatch between Statsig's dashboard and your costs, reach out to support. Statsig takes this seriously and works to resolve the gap. ## Tools for managing cost ### Follow UI hints Statsig proactively flags to you if: - A data source is particularly slow. - A metric source is malformed (e.g. a view definition which is broken within your warehouse). - A data source isn't following best practices. Paying attention to these and flagging them quickly prevents wasted compute. In most cases where PoC customers had performance issues, the causes were unpartitioned temp tables for the PoC, or not using macros to filter tables with extremely long data retention. ### Access controls For large organizations, poorly optimized source tables or using the wrong source when pulling data cause most cost issues. Statsig offers access controls so that: - Your data team can control data sources and ensure they are well-behaved. - The console clearly indicates verified sources for end users. ### Following best practices The [best practices](https://docs.statsig.com/statsig-warehouse-native/guides/best-practices) cover most situations that lead to high warehouse costs on Statsig. In short, you should aim to: - Cluster or partition source tables. - Use Statsig date macros to guarantee filter push-down. - Use Statsig's [Turbo Mode](../features/turbo) to reduce redundant compute, especially for large or long experiments. ================================================================================ # Data Best Practices URL: https://docs.statsig.com/statsig-warehouse-native/guides/best-practices Updated: 2025-09-18 ================================================================================ # Data Best Practices ## Cost management Statsig's pipelines use many SQL best practices to reduce cost, and smaller customers can run month-long analyses for a few cents. Following these best practices helps keep costs under control and consistent. Go to [Compute Cost Transparency](https://docs.statsig.com/statsig-warehouse-native/guides/best-practices#compute-cost-transparency) to understand how much compute time your experiments use. ### Follow SQL best practices Statsig uses your SQL to connect to your source data. Common SQL issues include: - Avoid using `SELECT *`, and only select the columns you need - `SELECT *` leads to a lack of clarity in what you're pulling/require for other users - For warehouse like Bigquery and Snowflake, it can increase the scan/size of materialized assets like CTEs in snowflake - This leads to higher query runtime and higher warehouse bills - Filter to the data you need in your base query - This reduces the scan and amount of data required in future operations - You can use Statsig Macros (below) to dynamically prune date partitions in subqueries - Group common metric groups into a single Metric Source - Statsig filters your source to the minimal set of data and then creates materializations of experiment-tagged data. To maximize the effectiveness of this strategy, have metric sources that cover common suites of metrics you usually pull together. - Cluster/Partition tables to reduce query scope - Most warehouses offer some form of partitioning or indexing along frequently filtered keys. In warehouses with clustering, the recommended strategy is: - Partition/Cluster Assignment Source tables by date, and then your experiment\_id column so you can scope experiment-level queries to that experiment - Partition/Cluster Metric Source tables based on date, and then the fields you expect to use for filters These best practices are generally true across all warehouses, especially as the datasets you use for experimentation scale. ### Materialize tables/views Since Statsig offers a flexible and robust metric creation flow, it's common to write joins or other complex queries in a metric source. As tables and experimental velocity scale, these joins can become expensive because they run across every experiment analysis. To reduce the impact of this, best practice is to: - Materialize the results of the join and reference that in Statsig, so you only have to compute the join once - Use Statsig macros to make sure partitions are pruned before the join, and you only join the data you need ### Use incremental reloads Statsig offers both Full and Incremental reloads. Incremental reloads process only new data and can be significantly cheaper on long-running experiments. Advanced settings in the Pulse advanced settings section (also available as org-level defaults) help you make tradeoffs to reduce total compute cost. For example, the "Only calculate the latest day of experiment results" setting skips timeseries. This setting can run large full reloads (for example, one year on 100M users) in 5 minutes on a Large Snowflake cluster. ### Reload data ad hoc Depending on your warehouse and data size, Statsig Pulse results can appear in as little as 45 seconds. Because pipelines have flat costs, reloading 5 days isn't 5 times as expensive as loading one day. If cost is a concern, choosing which results to schedule versus load on-demand can significantly reduce the amount of processing your warehouse has to do. ### Use Statsig's advanced options By default, Statsig runs a thorough analysis including historical timeseries and context on your results. ### Use metric-level reloads Statsig offers Metric-level reloads; this allows you to add a new metric to an experiment and get its entire history, or restate a single metric after its definition has changed. This is cheaper than a full reload for experiments with many metrics, and is an easy way to check guardrails or analyze follow-up questions post-hoc. ### Use Statsig's macros In Metric and Assignment sources, you can use Statsig Macros to directly inject a DATE() type that is relative to the experiment period being loaded. - `{statsig_start_date}` - `{statsig_end_date}` For example, in an incremental reload from `2023-09-01` to `2023-09-03`, this query: ```sql SELECT user_id, event, ts, dt FROM log_table WHERE dt BETWEEN {statsig_start_date} AND {statsig_end_date} ``` resolves to ```sql SELECT user_id, event, ts, dt FROM log_table WHERE dt BETWEEN DATE('2023-09-01') AND DATE('2023-09-03') ``` This is a powerful tool since you can inject filters into queries with joins or CTEs and be confident that the initial scan is pruned. ### Avoid contention Resource contention is a common problem for Data Engineering teams. Large runs in the morning to calculate the previous day's data or reload tables are typical. On warehouses with flat resources or scaling limits, Pulse queries can be significantly slower during these windows, and can also slow down core business logic pipelines. The best practice is to assign a scoped resource to Statsig's service user. This has a few advantages: - Costs are easy to understand, because anything billed to that resource is attributable to Statsig. - You can control the maximum spend by controlling the size of the resource, and independently scale the resource as your experimentation velocity increases. - Statsig jobs don't affect your production jobs, and vice versa. If this isn't possible: - Schedule your Statsig runs after your main runs (this also ensures the data in your experiment analysis is fresh). - Use API triggers to launch Statsig analyses after the main run is finished. ## Analytics optimization When using Statsig’s Metric Explorer to visualize data in your warehouse, optimizing table layout and clustering configurations can greatly improve latency. This section describes best practices you can use to improve the performance of analytics queries, with recommendations for some of the most commonly used warehouses. ### BigQuery #### Table layout: partitioning and clustering Partition on event date and cluster on event when defining your events table. This improves performance because most queries filter for the event name and the time it was logged. When defining the partition on event date, truncate the timestamp to day-level granularity instead of using the raw timestamp (which would otherwise have millisecond precision, resulting in very high cardinality). ```sql -- Create an events table partitioned by date and clustered by event. CREATE TABLE dataset.events ( ts TIMESTAMP NOT NULL, event STRING NOT NULL, ... ) PARTITION BY DATE(ts) CLUSTER BY event; ``` BigQuery's support for applying a cluster to an existing table is limited. Adding a cluster to an existing table doesn't automatically recluster the data immediately. If you need to repartition on event date or add a cluster by event, create a new table with the correct partitions and clusters using your current table. ```sql -- Using an existing events table, create a new table that is partitioned by date and clustered by event. CREATE OR REPLACE TABLE dataset.events_new PARTITION BY DATE(ts) CLUSTER BY event AS SELECT * FROM dataset.events; -- (Optional) Swap the name of your new table with the old one for consistency. DROP TABLE dataset.events; ALTER TABLE dataset.events_new RENAME TO events; ``` ### Databricks #### (Preferred) Use liquid clustering When making clustering decisions in your events table layout, [liquid clustering](https://docs.databricks.com/aws/en/delta/clustering) provides a flexible approach that allows you to modify your clustering keys without needing to manually rewrite existing data. Use liquid clustering for your events table as follows: ```sql -- Enable liquid clustering for your events table. ALTER TABLE events SET TBLPROPERTIES ('delta.liquidClustering.enabled' = 'true'); -- Cluster on the event column. ALTER TABLE events ALTER CLUSTER BY (event); -- Trigger clustering using the OPTIMIZE command. OPTIMIZE events; ``` If you frequently update your events table, Databricks recommends scheduling `OPTIMIZE` jobs every 1-2 hours. This incrementally applies liquid clustering to your table. #### (Alternative) Partitioning and ZORDER If you choose not to use liquid clustering, partition on a single low-cardinality column such as the event date. Avoid adding more than one column on the partition unless necessary, and don't partition on a column with cardinality exceeding one thousand. Use a generated column to simplify pruning: ```sql -- Define a partition on the event date generated column. CREATE TABLE events (ts TIMESTAMP, event STRING, event_date DATE GENERATED ALWAYS AS (CAST(ts AS DATE))) USING DELTA PARTITIONED BY (event_date); ``` Use `ZORDER` to colocate similar values within a file for a high-cardinality column, which improves query performance through data skipping. Apply this to the event column: ```sql -- ZORDER by the event column to improve data skipping. OPTIMIZE events ZORDER BY (event); ``` Use a scheduled job that runs `OPTIMIZE` on the last week's event data to improve query performance by compacting small data files into fewer, larger files: ```sql -- Periodically optimize the events table based on the last week of data. OPTIMIZE events WHERE event_date >= current_date() - INTERVAL 7 DAYS; ``` Avoid partitioning on a combination of event date and event. Even for small queries, this combination creates significant overhead: with 500 events, a 30-day query hits 15,000 partitions. Instead, partition only by date and use `ZORDER` on the event. For extra parallelism without introducing too many partitions, `ZORDER` by an additional bucket column, defined as follows: ```sql -- Add bucket column for extra parallelism. ALTER TABLE events ADD COLUMN event_bucket INT GENERATED ALWAYS AS (pmod(hash(event), 16)); -- Rewrite data into new files based on this ZORDER key. OPTIMIZE events ZORDER BY (event_bucket); ``` #### Partition pruning Dynamic File Pruning enables Spark to prune partitions based on filter values at runtime. Enable it if possible using: ```sql -- Turn on Dynamic File Pruning. SET spark.databricks.optimizer.dynamicFilePruning = true; ``` #### Handling skew and joins To rebalance skew and adjust join strategy, turn on Adaptive Query Execution: ```sql -- Turn on Adapative Query Execution SET spark.sql.adaptive.enabled = true; ``` #### Compute choices The Photon query engine allows faster query execution with more efficient use of CPU and memory. If possible, enable it for your compute cluster or SQL warehouse. ### Redshift #### Table design: distribution style and sort key Because Redshift doesn't support partitioning by column, use a sort key instead. Most event tables are append-only and time-based, so use a compound sort key on (timestamp, event) to order data by time. Because all analytics queries filter on timestamp, this allows queries to read only the relevant blocks. Ordering secondarily by event groups rows by event within each time block, which can reduce scan size when filtering by event. Timestamp remains the first key so pruning is primarily on timestamp. Because there can be significant skew among event types, use an automatic distribution style rather than distributing on the event column. This allows Redshift to make distribution decisions based on the size of the table and query patterns. Create an events table with these recommendations as follows: ```sql -- Create an events table with an automatic distrbution style and sort key on timestamp, event. CREATE TABLE events ( event VARCHAR NOT NULL, ts TIMESTAMP NOT NULL, ... ) DISTSTYLE AUTO COMPOUND SORTKEY (ts, event); ``` If you already have an events table and want to use the recommended distribution style and sort key, you can't apply those changes by modifying the existing table. Instead, create a new table and copy over data: ```sql -- Create a new events table with the preferred distribution style and sort key. CREATE TABLE events_new ( event VARCHAR NOT NULL, ts TIMESTAMP NOT NULL, ... ) DISTSTYLE AUTO COMPOUND SORTKEY (ts, event); -- Copy over data from the old events table. INSERT INTO events_new (event, ts, ...) SELECT event_id, ts, ... FROM events; -- Rename the two tables in a single transaction. BEGIN; ALTER TABLE events RENAME TO events_old; ALTER TABLE events_new RENAME TO events; COMMIT; -- Drop the old table. DROP TABLE events_old; ``` ### Snowflake #### Clustering keys Because Snowflake doesn't allow explicit partitioning, use clustering keys on the event date and event to improve performance, as most queries filter for the event name and the time it was logged. Cluster on the timestamp truncated to day-level granularity instead of the raw timestamp (which would otherwise have millisecond precision, causing very high cardinality). ```sql -- Cluster events on the timestamp truncated to day and event. ALTER TABLE events CLUSTER BY (DATE_TRUNC('day', ts), event); ``` If you have a high cardinality of unique event types, it might be advisable to add a search optimization on event instead of clustering by that column. Go to the [next section](#managing-high-cardinality-columns) for details. #### Managing high cardinality columns If there are high-cardinality columns that you frequently reference in Metrics Explorer filters, consider using search optimization rather than clustering on those columns. Clustering on high-cardinality columns creates an overly large range of values for each micro-partition, making pruning inefficient. Search optimization generates an auxiliary index for fast lookups instead. ```sql -- Add search optimization for fast lookups. ALTER TABLE events ADD SEARCH OPTIMIZATION ON EQUALITY(some_column); ``` #### Monitoring clustering Use `SYSTEM$CLUSTERING_INFORMATION` to check whether your current clustering scheme is effective. Large values of `average_depth` and `average_overlaps` may indicate the existing table needs reclustering on different keys with lower cardinality. ```sql -- Given an events table clustered on event date and event, check the clustering information. SELECT SYSTEM$CLUSTERING_INFORMATION('YOUR_DATABASE.YOUR_SCHEMA.EVENTS', '(DATE_TRUNC(''day'', ts), event)'); ``` #### Timestamp column If possible, use the `TIMESTAMP_NTZ` (no timezone) type for your timestamp column. This saves space because Snowflake doesn't need to store offset metadata. It can also speed up queries by allowing Snowflake to skip timezone normalization during filtering and pruning of micro-partitions. ### Questions For additional support optimizing your warehouse configuration for analytics, reach out in the Slack support channel for your organization within Statsig Connect. ## Debugging Statsig shows you all the SQL being run and any errors that occur. These are generally caused by changes to underlying tables or Metric Sources that cause a metric query to fail. Here are some best practices for debugging Statsig queries. ### Use the queries from your Statsig console If a Pulse load fails, find all the SQL queries and associated error messages in the _Diagnostics_ tab. Select the copy button to run or debug the query in your warehouse. Common errors include: - A query attempting to access a field that no longer exists on a table. - A table not existing, usually because the Statsig user doesn't have permission on a new table. ## Turbo mode [Turbo Mode](../features/turbo) skips some enrichment calculations (in particular some time series rollups) to compute the latest snapshot of your data at low cost. Customers have run experiments on 150+ million users in less than 5 minutes on a Snowflake S cluster. ### Contact support Statsig's support team is responsive and can help you fix your issue and build tools to prevent it in the future, whether it's due to system or user error. ## Compute cost transparency Statsig Warehouse Native lets you get an overview of the compute time experiment analysis incurs in your warehouse. Break this down by experiment, metric source, or type of query to find what to optimize. Common questions the dashboard is designed to answer include: - Which Metric Sources take the most compute time? - What is the split of compute time between full loads, incremental loads, and custom queries? - How is compute time distributed across experiments? You can find this dashboard in the Left Nav under Analytics -> Dashboards -> Pipeline Overview ![Pipeline Overview dashboard interface](https://docs.statsig.com/images/statsig-warehouse-native/guides/best-practices/684ae633-8054-4f41-8443-7df63fe81253.png) Statsig builds this dashboard with Statsig Product Analytics. You can customize any of these charts or build new ones. A useful addition is to include your average compute cost, so you can convert slot time per experiment into dollar cost per experiment. At the end of every Pulse load / DAG, Statsig uploads a single row to the `pipeline_overview` table for each job executed as part of that run. This table has the following schema: | Column | Type | Description | | --- | --- | --- | | ts | timestamp | Timestamp at which the DAG was created. | | job\_type | string | Job type (see [Pipeline Overview](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview/)) | | metric\_source\_id | string | Only applicable for 'Unit-Day Calculations' jobs - the ID of the metric source | | assignment\_source\_id | string | The Assignment Source ID of the experiment for which Pulse was loaded. | | job\_status | string | The final state of the job (`fail` or `success`) | | metrics | string | Metrics processed by the job | | dag\_state | string | Final state of the DAG (`success`, `partial_failure`, or `failure`) | | dag\_type | string | Type of DAG (`full`, `incremental`, `metric`, `power`, `custom_query`, `autotune`, `assignment_source`, `stratified_sampling`) | | experiment\_id | string | ID of the experiment for which Pulse was loaded, if applicable | | dag\_start\_ds | string | Start of the date range being loaded | | dag\_end\_ds | string | End of the date range being loaded | | wall\_time | number | Total time elapsed between DAG start and finish, in milliseconds | | turbo\_mode | boolean | Whether the DAG was run in Turbo Mode | | dag\_id | string | Internal identifier for the DAG | | dag\_duration | number | Number of days in the date range being loaded | | is\_scheduled | boolean | Whether the DAG was triggered by a scheduled run | ================================================================================ # Data & Semantic Layer URL: https://docs.statsig.com/statsig-warehouse-native/configuration/data-and-semantic-layer Updated: 2025-09-18 ================================================================================ # Data & Semantic Layer In Statsig Warehouse Native, you configure metrics, experiments, and other schematized data objects that let Statsig run analysis on top of your warehouse. Together these definitions form a lightweight semantic layer that can integrate with tools like Cube or in-house YAML-based stores. ![SDK exposures flow from your application into the Statsig warehouse as experiment and feature gate exposures, then into an assignments table in your warehouse. That table, which can also receive in-house assignments, and your metric source tables and queries both feed the Stats Engine, which runs experiment reloads and Metrics Explorer in your warehouse.](https://docs.statsig.com/images/diagrams/whn-data-flow.svg) ![SDK exposures flow from your application into the Statsig warehouse as experiment and feature gate exposures, then into an assignments table in your warehouse. That table, which can also receive in-house assignments, and your metric source tables and queries both feed the Stats Engine, which runs experiment reloads and Metrics Explorer in your warehouse.](https://docs.statsig.com/images/diagrams/whn-data-flow.dark.svg) ================================================================================ # Metric Sources URL: https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources Updated: 2025-09-18 ================================================================================ # Metric Sources Metric Sources are how you schematize your warehouse data for Statsig, and they serve as the input data for metrics. ## What is a metric source A metric source is a key part of Statsig's semantic layer (and integrations to other Semantic Layers). A metric source consists of a data source, which is either: - A SQL Query that Statsig reads as a view - A warehouse table And configuration around the source: - **\[Required\]** identifier and timestamp columns - **\[Optional\]** Aliases, partition information - **\[Early Access\]** Data quality checks and configuration The metric source is the entry point for using your data in parameterized queries for experiment analysis, analytics, and more within the Statsig console. ## Data sources ### Getting data Statsig Metric Sources can use a query or a table as the source of their data. A query-based source reads a SQL query and uses it as a source of truth. Combined with Statsig's built-in [query macros](https://docs.statsig.com/statsig-warehouse-native/configuration/query-tools), this provides an efficient and flexible way to create experimental data sources. ![Query-based metric source configuration](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/2cec3d01-f852-4007-aa3b-de276418593b.png) For larger or managed datasets, use table sources. Table sources minimize data scan and provide a more 1:1 mapping of "data source" to "metric source". Statsig automatically applies date macros in each experiment result reload when you use table sources. ![Table-based metric source configuration](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/04cb0209-580c-4603-a5db-45a08f00f90b.png) ### Configuring data For any source, select which field to use for the timestamp of the logs or metrics you provide. Also select 1 to N user identifiers to join to experiment data. ![Interface for selecting timestamp and ID fields](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/9a972d93-3500-4947-89e7-c144b877887f.png) For table sources, you can optionally provide a partitioning column to reduce data scan, and provide aliases to make your column names more human-readable. ![Partition and alias settings for table source](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/4b388fac-1124-4606-88f6-a0615bd32b18.png) ### Types of data Statsig works natively with many different types and granularities of data. Common patterns are: #### 1. Raw event logging (event level data), using the log timestamp as the timestamp | `event_time` | `user_id` | `event_name` | `platform` | `value` | | --- | --- | --- | --- | --- | | 2024-03-01 10:05:12 | `u_123` | `page_view` | `web` | `null` | | 2024-03-01 10:05:45 | `u_123` | `button_click` | `web` | `null` | | 2024-03-01 10:07:02 | `u_456` | `purchase` | `ios` | 29.99 | _Metric examples with this source:_ _- Number of users with purchase: You can create a [UNIT COUNT](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-once) metric, with a filter of event\_name = 'purchase'._ _- % of users with page view who clicked: You can create a [RATIO](https://docs.statsig.com/statsig-warehouse-native/metrics/ratio) metric with this metric source in both denominator and numerator, and apply event\_name filter accordingly._ #### 2. Fact tables (one row per entity per day), using the date of the row as the timestamp | `order_date` | `order_id` | `user_id` | `order_status` | `items_count` | `revenue` | | --- | --- | --- | --- | --- | --- | | 2024-03-01 | `o_10001` | `u_123` | `completed` | 2 | 49.98 | | 2024-03-01 | `o_10002` | `u_456` | `completed` | 1 | 19.99 | | 2024-03-02 | `o_10003` | `u_123` | `refunded` | 1 | 19.99 | _Metric examples with this source:_ _- Revenue: You can create a [SUM](https://docs.statsig.com/statsig-warehouse-native/metrics/sum) metric on 'revenue' column, with any filters you need._ _- Average order value: You can create a [MEAN](https://docs.statsig.com/statsig-warehouse-native/metrics/mean) metric on 'revenue' column, with any filters you need._ #### 3. Aggregated fact tables at unit day granularity, using the date of the row as the timestamp | `date` | `user_id` | `sessions` | `purchases` | `revenue` | | --- | --- | --- | --- | --- | | 2024-03-01 | `u_123` | 3 | 1 | 29.99 | | 2024-03-01 | `u_456` | 1 | 0 | 0.00 | | 2024-03-02 | `u_123` | 2 | 0 | 0.00 | _Metric examples with this source:_ _- Revenue: You can create a [SUM](https://docs.statsig.com/statsig-warehouse-native/metrics/sum) metric on 'revenue' column, with any filters you need._ _- Number of users with purchase: You can create a [UNIT COUNT](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-once) metric, with a filter of purchase > 0._ ### Types of data that require transformation You may have a table that doesn’t fit the schemas above. For example, a wide user dimension table contains one row per user with pre-aggregated or derived behavioral attributes. | `user_id` | `signup_date` | `first_active_date` | `first_page_view_date` | `first_purchase_date` | `last_active_date` | `lifetime_revenue` | `is_power_user` | | --- | --- | --- | --- | --- | --- | --- | --- | | `u_123` | 2023-11-12 | 2023-11-12 | 2023-11-12 | 2023-11-20 | 2024-03-02 | 249.85 | `true` | | `u_456` | 2024-01-05 | 2024-01-06 | 2024-01-05 | 2024-02-10 | 2024-02-18 | 19.99 | `false` | | `u_789` | 2024-02-10 | 2024-02-10 | 2024-02-10 | `null` | 2024-03-01 | 89.97 | `false` | This table type isn’t compatible with Statsig because it doesn’t have a single timestamp column that you can consistently configure across all events (for example, `signup`, `first_active`, and `last_active`). Statsig’s stats engine relies on a timestamp column to join metric data with exposure timestamps. This join ensures that Statsig includes only metric events that occur after a user is exposed to an experiment. For example, suppose you configure `signup_date` as the timestamp column for this metric source. If you then attempt to build a funnel metric across multiple events (for example, `signup` → `first_active` → `first_purchase`), Statsig treats all funnel steps as occurring at the signup date. The metric source can only use a single configured timestamp column, so it applies that one timestamp to every step. As a result, Statsig ignores event-specific timestamps in other columns (such as `first_active_date` or `first_purchase_date`), and the funnel no longer reflects the true timing of each event. To address this, there are two recommended options: - **Use upstream tables as the metric source**: Define metrics directly from event logs or fact tables where each row represents a single event and includes a clear timestamp. - **Collapse the table into a long format**: Reshape the wide user table into a long table (for example, one row per user per event or per day) with a unified timestamp column that you can configure in Statsig. | `user_id` | `event_type` | `event_timestamp` | | --- | --- | --- | | `u_123` | `signup` | 2023-11-12 09:15:00 | | `u_123` | `first_active` | 2023-11-13 10:02:41 | | `u_123` | `last_active` | 2024-03-02 18:45:10 | | `u_456` | `signup` | 2024-01-05 14:22:09 | | `u_456` | `first_active` | 2024-01-06 08:11:54 | ## Managing metric sources In the metric source tab, you can see your metric sources and the metrics and experiments that use them. In some cases, it makes sense to have a broad metric source that you reuse across many metrics with different filters and aggregations. In others, a metric source may exist for one metric, such as a set of specific events for a funnel. ![Metric sources list showing usage across metrics](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/264087800-18970974-b639-4d73-8977-e54de752ae0a.png) Metric sources can also be archived when they're no longer in use. See [Archive a metric source](https://docs.statsig.com/metrics/archiving-metrics#archive-a-metric-source-warehouse-native). ### Programmatic updates You can create and modify metric sources through the API as part of your release flow for data systems. The API supports creating read-only artifacts. Refer to the [console API](https://docs.statsig.com/statsig-warehouse-native/configuration/console-api) and [Semantic Layer Sync](https://docs.statsig.com/statsig-warehouse-native/configuration/semantic-layer-sync) documentation. ### Governance If you're concerned about granting Statsig broad warehouse access, give Statsig access only to its own staging schema or dataset. In that location, create views or materialize staging tables for the data you want Statsig to read. ## Daily vs. realtime sources When specifying a timestamp, you can also specify if the metric source contains data at a daily or timestamp granularity by toggling the "Treat Timestamp as Date" setting. ![Timestamp granularity configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-sources/f0edfdaf-9531-4583-b440-d05f0f3c3618.png) When this setting is **not** enabled, the system performs a timestamp-based join. Statsig attributes events to the experiment results based on the exact time they occur relative to the exposure time. For example, if a user is exposed at `2024-01-01T11:00:00` and an event occurs at `2024-01-01T11:01:00`, Statsig attributes the event to the experiment because it occurred after the exposure. If the event occurs at `2024-01-01T10:59:00`, before the exposure, Statsig doesn't attribute it. When the "Treat Timestamp as Date" setting is enabled, the system performs a date-based join. Statsig includes all events occurring on the same calendar day as the exposure, regardless of time, in the experiment results. This includes data from the first day of exposures, ensuring Statsig doesn't omit day-1 metrics from the analysis. A date-based join affects each experiment type differently: - **A/B experiments**: Statsig joins on `metric date >= exposure timestamp::Date`, so when a metric event and an exposure fall on the same day, Statsig can't tell which came first and includes the metric event either way. Those pre-exposure events act as A/A data: their mean is 0, so they don't bias the result, but they add variance, which makes statistical significance harder to reach. Ignoring metric events on the day of exposure is usually worse, because many metric events happen that day. - **Switchback experiments**: with this setting enabled, the time window (how often the experiment alternates between control and treatment) must be at the day level. Hour-level windows don't work: a date-formatted timestamp places no metric events between 2:00 AM and 3:00 AM on January 1, so every metric event for the day lands in a single bucket and distorts attribution. - **Autotune experiments**: reallocation runs every hour, but a warehouse you write to once a day gives each run little new data to act on. The attribution window also needs to span days, for the same reason as switchbacks: an exposure at 2:00 AM with a four-hour attribution window has no metric events between 2:00 AM and 6:00 AM. Most sources enable this setting because they load daily, or aggregate daily to keep the table small, so 23 of the 24 hourly runs receive only new exposure data, and the one remaining run picks up the day's new metric data. In the other 23 runs, the only change is that some attribution windows close. Autotune accounts for both warehouse data delay and daily metric granularity when it determines whether an exposure window is complete, rather than relying on the job timestamp. All Statsig needs to create metrics is a timestamp or date, and a unit (or user) identifier. Context fields let you pull multiple metrics from the same base query, and select values to sum, mean, or group by. | Column Type | Description | Format/Rules | | --- | --- | --- | | timestamp | **Required** an identifier of when the metric data occurred | Castable to Timestamp/Date | | unit identifier | **Required** At least one entity to which this metric belongs | Generally a user ID or similar | | additional identifiers | _Optional_ Entity identifiers for reuse across identifier types | | | context columns | _Optional_ Fields you aggregate, filter, or group on | | For example, you could pull from event logging and aggregate the event-level data to create metrics: | timestamp | user\_id | company\_id | event | time\_to\_load | page\_route | | --- | --- | --- | --- | --- | --- | | 2023-10-10 00:01:01 | my\_user\_17503 | c\_22235455 | page\_load | 207.22 | / | | 2023-10-10 00:02:15 | my\_user\_18821 | c\_22235455 | page\_load | 522.38 | /search | | 2023-10-10 00:02:22 | my\_user\_18821 | c\_22235455 | serp\_click | null | /search | You could create an average TTL metric by averaging time\_to\_load, and group it by page route or filter to specific routes when creating your metric. As another example, you might pre-calculate some metrics at a user-day grain, either to match your source of truth exactly or to add more complex logical fields: | timestamp | user\_id | company\_id | country | page\_loads | satisfaction\_score | revenue\_usd | net\_revenue\_usd | | --- | --- | --- | --- | --- | --- | --- | --- | | 2023-10-10 | my\_user\_17503 | c\_22235455 | US | 13 | 9 | 130.21 | 112.33 | | 2023-10-10 | my\_user\_18821 | c\_22235455 | CA | 1 | 2 | 0 | 0 | | 2023-10-10 | my\_user\_18828 | c\_190887 | DE | 0 | null | 22.1 | 0 | You can create different metrics by summing and filtering on those daily fields. ## (Very) slow metric sources Statsig uses techniques like Statsig macros, push-down filters (predicate filters), and partition keys to make queries in your warehouse efficient. While metric sources can include joins or complex queries, they should be performant. If they aren't, any metrics based on that metric source become expensive or cause timeouts and failures. The same applies to assignment sources. Statsig flags a metric source as slow if it takes more than 30 seconds to retrieve a sample of up to 100 records from the table. If the query is expensive, consider the following steps in sequence to optimize your metric source: - Include filters based on the partition column. - Use [Statsig macros](https://docs.statsig.com/statsig-warehouse-native/guides/best-practices#use-statsigs-macros) in SQL. - Pre-calculate some of the metrics to avoid joins or complex queries. - Upgrade your computing resources if you're on a very small cluster. Do this cautiously. > **Note:** > > If Statsig flagged you for a slow assignment source, the same guidance applies. ================================================================================ # Metrics Overview URL: https://docs.statsig.com/statsig-warehouse-native/configuration/metrics Updated: 2025-09-18 ================================================================================ # Metrics Overview Metrics are measures of user or system behavior that serve as evaluation criteria for experiments and for performing analysis. Statsig organizes metrics within your Metrics Catalog. ![Metrics catalog dashboard](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metrics/8cc2781c-23ac-46d2-b270-0d5d359c8f5b.png) ## Creating metrics Metrics are a combination of a metric source, an aggregation, and optional filters and advanced settings. The metric source provides the raw data, and the aggregation defines how Statsig aggregates data across different granularities: user-level, group-level, or daily timeseries. Metrics can support multiple units of analysis. For example, you can use a revenue metric for a "User Level" and a "Store Level" experiment, as long as the metric source has a mapping for both ID types. Filters are also a core component of metrics. Statsig offers a rich set of filtering options, including SQL-based filters, so you can reuse the same metric source for many use cases. ![Metric creation flow with aggregation and filters](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metrics/fb7526f9-3ffa-4192-8184-1388e3e80db9.png) ## Using metrics You can use metrics for standalone analysis, as part of your experiment scorecard, or as guardrails for feature releases. You can also group them into collections using tags for easy addition across these surfaces. You can also configure metrics to send alerts globally if any experiment or gate causes a regression. Statsig recommends using tags extensively. A combination of team-level and surface- or product-level tags ensures easy discovery of metrics. To view details about a metric, navigate to the Metrics page to see its definition, related experiments, and a timeseries of the metric value. ![Metric detail page showing definition and timeseries](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metrics/f7023ab8-9d3d-4013-8595-b51325b7c954.png) In the [insights tab](https://docs.statsig.com/experiments/exploring-results/aggregated-impact) and in [meta-analysis](https://docs.statsig.com/statsig-warehouse-native/features/meta-analysis), you can perform more detailed analysis of how experiments have impacted a metric, and how the metric relates to other metrics in your catalog. ![Insights view summarizing aggregated impact](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metrics/94d40316-53bf-484e-8a73-57cc42e22ca6.png) ## Loading metrics Selecting **Reload Metric Data** causes Statsig to sync your latest data and display it on this page. The default loading window is 90 days, but you can configure a longer period if needed. ![Reload metric data button and schedule settings](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metrics/cc73bf53-13ec-44f3-aa2c-606db4a8d4da.png) To use metrics to measure topline impact, or for ongoing tracking in the metrics page, schedule loads of the metric values. You can trigger a load manually from the metric page, or schedule it from there (3-dot menu > edit scheduled reload). You can also configure this as a project-level setting under Data Connection in your project settings. ## Metric management Without a well-managed Metric Catalog, end users may not know whether they can trust a metric or understand how you define it. Statsig provides several tools to address this: - \[Verified Metrics\] and programmatic management allow you to vet your core metrics and make it clear which metrics set the gold standard. - \[[RBAC](https://docs.statsig.com/statsig-warehouse-native/features/roles-and-access) and Team Ownership\] let you limit the number of potential editors for Metrics, keeping control of core definitions in the experiment team's hands. - \[Local Metrics\] in Pulse or Explore queries allow you to make experiment-scoped and clearly-labeled changes to metric definitions without adding a large amount of single-user metrics to your metrics catalog. - Scorecard hover-over definitions make it trivial to discover, in-context, what settings apply to a metric and how Statsig performed the calculation. - [Archive and delete metrics](https://docs.statsig.com/metrics/archiving-metrics) lets you remove inactive metrics from active analyses or permanently delete them. ## Metric types Statsig offers the largest coverage of metric types of any enterprise platform. These fall into 4 categories: ### Aggregations Aggregations are basic unit-level counts or sums that measure user behavior. You can use them as inputs to ratios, especially for [cluster-based experiments](https://docs.statsig.com/metrics/different-id) where you want to normalize measures. Statsig computes aggregations at the unit level, then averages them across all units in the experiment during Pulse analysis. Supported aggregations are: - [Count](https://docs.statsig.com/statsig-warehouse-native/metrics/count) - [Sum](https://docs.statsig.com/statsig-warehouse-native/metrics/sum) - [Logged Sums and Counts](https://docs.statsig.com/statsig-warehouse-native/metrics/log) - [Count Distinct](https://docs.statsig.com/statsig-warehouse-native/metrics/count-distinct) - [First Value](https://docs.statsig.com/statsig-warehouse-native/metrics/latest-value#first-value) - [Latest Value](https://docs.statsig.com/statsig-warehouse-native/metrics/latest-value) - Thresholds - A special case of sum/count that measures a 1/0 flag for whether a user passed a threshold value during the experiment - e.g., "the number of users who spent more than $100" ### Unit counts, retention, and conversion Statsig offers many ways to count units in an experiment. This allows you to measure questions like: - Did users sign up more often? - Are more users currently subscribers at the end of the experiment? - How many users refunded in the first week of the experiment? These all fall under the "Unit Count" type, with rollups specifying calculation details. Unit counts produce a 1/0 flag or a sum of user-days at the user level, then Statsig averages them across all units in the experiment during Pulse analysis. Supported unit count types are: - [One-Time Event](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-once), measuring if a user performed an action at all during the experiment - [Windowed](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-window), measuring if a user performed an action within some time window after exposure - [Latest Participation](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-latest), measuring if a user fulfilled some criteria on their latest recorded record (e.g. is this user currently a subscriber) - [Daily Participation](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-rate), the rate at which units were daily active users during the experiment - [Retention](https://docs.statsig.com/statsig-warehouse-native/metrics/retention), the rolling rate of retention on an action or set of actions with a configurable time window ### Ratios and funnels Ratios and funnels measure rates or conversion. Statsig aggregates these differently: they measure the total of a numerator metric divided by the total of a denominator metric across each experiment group. They also apply the delta method to correct for covariance between the component metrics. [Ratio Metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/ratio) allow you to measure ratios of two different metrics, giving nuance to results and helping you to normalize results by another measure - for example: - B2C: Average purchase revenue (`SUM(Revenue) / COUNT(orders)`) - B2B: Revenue per User (`SUM(Revenue) / COUNT_DISTINCT(user_id)`) [Funnel Metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/funnel) allow you to analyze user conversion through multi-step flows at an overall and stepwise level. Funnel metrics help you identify dropoff points in user journeys and measure conversion rates. Statsig offers session-level funnels, which measure conversion within distinct checkout flows, support conversations, or viewing sessions. ### Performance metrics Teams working on performance problems use Statsig to analyze the impact of their changes at a system level. These metric types can also be useful for user behavior. The types you most commonly use here are: - [Percentile Metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/percentile) allow you to measure changes in values like the P99.9 - useful for measuring improvements or regressions in latency, TTL, or measuring median change when the mean is skewed - [Mean Metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/mean) are an easy shorthand for ratio metrics summing an event-level value and dividing by the total records ## Filters Statsig offers many ways to filter your data. You can write filters in SQL. However, a more flexible approach is to leave metric sources broad and let users construct filters in the UI or through semantic layer syncs. This approach gives greater no-code flexibility for metric creation and follow-up analysis, especially when using [local metrics](https://docs.statsig.com/metrics/local-metrics). ### Any of / None of These are the equivalent to a SQL `IN` or `NOT IN` statement, and you can also use them for equality/inequality. You can supply 1 to N values to the filter to include or exclude from your result set. ### Inequalities You can compare numerical values using `=`, `>`, `<`, `>=`, or `<=`. Equality can also compare non-numerical values, which Statsig evaluates as a string-casted comparison. ### Null checks Statsig supports checks for `Is Null` or `Non Null`, which can be useful for identifying if a flag was logged or for filtering out partial data. ### Contains/Does Not Contain/Starts With/Ends With These operators are similar to a SQL `LIKE` operator: - Contains checks for if a substring is in a string, e.g. \`field LIKE '%search\_string%' - Does Not Contain checks for if a substring is in a string, e.g. \`field not LIKE '%search\_string%' - Starts With checks for if a substring starts the field, e.g. \`field LIKE 'search\_string%' - Ends With checks for if a substring ends the field, e.g. \`field LIKE '%search\_string' ### Is After Exposure This filter allows you to specify a secondary date/timestamp field that has to come after the user's enrollment to the experiment. By default, Statsig only considers metric data where the primary metric timestamp is after the user first saw the experimental intervention. However, you might have another field like "first\_saw\_content\_at". You can use `Is After Exposure` to enforce that this secondary timestamp also takes place after the user's exposure. ### SQL filters SQL filters allow you to inject any SQL filter string into your metric definition, which Statsig validates before saving. SQL filters are flexible and let you interact with complex objects or do complex logic operations as needed to define your metrics. For example, Statsig adds the sql filter `(weight_lb)/pow(height_inches, 2) > 25` to your metric source query for this metric as: ```sql SELECT <columns> FROM <source_table> WHERE <other_filters> AND ((weight_lb)/pow(height_inches, 2) > 25) ``` ## Settings Each metric type's page has specific information on settings relevant to that metric. This section introduces common settings across metrics. ### Breakdowns Most aggregation-type metrics (sum, count, count distinct, unit count, means, ratios, percentiles, first/latest, min, max) allow you to generate a breakdown view of any column automatically. You can specify this column in the metric set up, and then click into the experiment result to see the breakdown. ### Cohorts Cohort settings allow you to specify a window for data collection after a unit's exposure. For example, a 4-6 day cohort window counts only actions from days 4, 5, and 6 after a unit was exposed to an experiment. Refer to the [cohort documentation](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) for full details. ### Baking Many metric types support baking. Statsig waits to calculate baked metrics and uses "old" data for them. This is appropriate for cases like credit card chargebacks, where you may adjust your payments dataset to account for chargebacks in a "net revenue" metric. For additional information, go to the [cohort documentation](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics). Statsig: - doesn't calculate baked metrics until the bake period has elapsed since the user's enrollment - pulls historical data that "just baked" as of that day on a given load - only calculates results for users whose bake window has elapsed to avoid diluting metrics This way, Statsig doesn't show incomplete data in Pulse (either because it's incomplete in the warehouse, or because of late-landing data). ### Thresholding Thresholding converts a sum, count, count-distinct, max/min, or first/latest metric into a 1/0 unit metric based on whether a user's total value meets a specified threshold. For example, to measure how many users spent at least $100 in their first week, specify a 0-6 day cohort metric that sums revenue with a threshold of $100. ### CUPED You can enable/disable CUPED per metric, and also specify the lookback window for which Statsig pulls users' pre-exposure data and uses it as an input to the CUPED regression. ### Winsorization Go to [winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization) for full details. Winsorization applies to aggregate metrics and allows you to specify an upper or lower percentile-based threshold, clamping data to that threshold. This reduces inflated variance or skewed means caused by outlier data or buggy logging. ### Capping Capping is an alternate outlier-control method that clamps values to a unit-day cap, specifiable per unit type. For example, you might clamp "total purchase count" to 100 on an auction platform to prevent resellers from skewing your metrics. This cap assumes 100 is a reasonable upper bound for typical users. ================================================================================ # Sum Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/sum Updated: 2025-09-18 ================================================================================ # Sum Metrics ## Use cases Sum metrics calculate the sum of a numeric column, which makes them well suited to comparing behavior across groups. Common examples are: - Totalling revenue by summing a `revenue` column from purchase logs - Totalling time spent by summing an aggregated `time_spent` metric on a user-day fact table ## Calculation At the unit level, sum metrics take the SUM of their input column. At the group level, Statsig calculates the mean as the SUM of the unit-level sums, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL for this calculation: ```sql -- Unit Level SELECT unit_id, group_id, SUM(value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes Sum metrics use the SQL SUM aggregation. Refer to the Options section below for many advanced options. ## Options - Metric Breakdowns: configure Metadata Columns to group results by for dimensional views in pulse results. - Multi Source: build sums from multiple metric sources, equivalent to a UNION in SQL. Useful when the same measure exists in sharded or disparate tables. - Winsorization: specify a lower and/or upper percentile bound. Statsig clamps all values below the lower threshold or above the upper threshold to reduce the impact of outliers. - Capping: specify an exact cap value (per unit type) to limit a unit's daily value. For example, cap daily purchases at 100 on an e-commerce site to exclude reseller behavior. - CUPED: enable CUPED and specify the lookback window for pre-experiment data inputs. - Thresholding: convert this metric into a 1/0 unit count metric that flags whether the unit's total sum meets or exceeds a given threshold. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics): specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after exposure. Select **Only include units with a completed window** to exclude units from pulse analysis until their cohort window has completed. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows): specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and calculates pulse results only after a unit's metric has matured. ================================================================================ # Count Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/count Updated: 2025-09-18 ================================================================================ # Count Metrics ### Use cases Count metrics commonly measure how often events occurred. Common examples are: - Counting click frequency by counting event logs filtered to the `click` event - Making a threshold metric of if a user read more than 2 articles ## Calculation At the unit level, count metrics run a COUNT(1) across their metric source. At the group level, Statsig calculates the mean as the SUM of the unit-level count, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL looks like the following: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, COUNT(1) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes Count metrics use the SQL COUNT aggregation. Count metrics offer many advanced options. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results. - Multi Source - You can build counts with inputs from multiple metric sources; think of this as a UNION in SQL. This can be useful if you have the same measure in sharded or disparate tables. - Winsorization - Specify a lower and/or upper percentile bound to winsorize at. Statsig clamps all values below the lower threshold, or above the upper threshold, to that threshold to reduce the outsized impact of outliers on your analysis. - Capping - Specify an exact cap value (per unit type) to limit a unit's daily value for the count. For example, you might want to cap daily purchases at a high value like 100 on an e-commerce site to ignore reseller behavior. - CUPED - Specify if you want to calculate CUPED, and the lookback window for CUPED's pre-experiment data inputs. - Thresholding - Turn this metric into a 1/0 unit count metric counting if the unit's total count equals to or surpasses (>=) a given threshold. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) let you specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and only calculates pulse results for that metric after a unit's metric has matured. ================================================================================ # Count Distinct Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/count-distinct Updated: 2025-09-18 ================================================================================ # Count Distinct Metrics ### Use cases Count distinct metrics calculate the number of unique values in a column of your metric source, counted per unit so the total is the number of unique unit-value pairs. They have two primary use cases: - Measuring interactions and surface area. For example, you might count the number of entities a user has engaged with on a video streaming platform, or measure if a new recommendation engine increases the diversity of products clicked. - As a denominator in ratio metrics, especially common when you want to normalize by a unit other than your experiment's unit of analysis. For example, a B2B experiment might run at the company level but measure "Clicks per USER" using a ratio metric of COUNT(clicks)/COUNT\_DISTINCT(user\_id). > **Warning:** > > Count-distinct metrics are more expensive to compute than [count](./count) or [unique unit count](./unit-count-once) metrics, especially for very long experiments. > > If you want to count distinct occurrences of the experiment's unit of assignment (e.g. the user\_id in a user\_id experiment), you should use a unit\_count metrics instead. A unit\_count metric achieves the same result but calculates and stores the metric data more efficiently. > > In many cases a count metric serves as a close proxy to count-distinct; you can also set up a data source to track unique instances of a key to avoid re-running the distinct operation across experiment analyses. ## Calculation At the unit level, count distinct metrics use COUNT\_DISTINCT on their input column. At the group level, Statsig calculates the mean as the SUM of the unit-level COUNT\_DISTINCTs, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL looks like the following: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, COUNT(distinct source_data.value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes In the metrics page view, Statsig uses APPROX\_COUNT\_DISTINCT (or equivalent) to avoid large compute jobs on analytical count distinct. The approximate error is acceptably small for topline estimates. For experiment result loads, the calculation is analytical and exact to avoid jitter or bias from approximation error. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results. - Winsorization - Specify a lower and/or upper percentile bound to winsorize at. Statsig clamps all values below the lower threshold, or above the upper threshold, to that threshold to reduce the outsized impact of outliers on your analysis. - CUPED - Specify if you want to calculate CUPED, and the lookback window for CUPED's pre-experiment data inputs. - Thresholding - Turn this metric into a 1/0 unit count metric counting if the unit's total count equals to or surpasses (>=) a given threshold. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. ## Limits Count distinct metrics work in most experiments, except for Switchbacks. ================================================================================ # Unit Count (One-Time Event) Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-once Updated: 2025-09-18 ================================================================================ # Unit Count (One-Time Event) Metrics ## Use cases Unit count (one-time event) metrics flag whether a unit performed an action any time after exposure to the experiment. Use them to measure participation rates among users in the experiment. ## Calculation At the unit level, unit count metrics create a 1/0 flag for if they participated. At the group level, Statsig calculates the mean as the SUM of the unit-level flags, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL for this calculation: ```sql -- Unit Level SELECT distinct source_data.unit_id, exposure_data.group_id, 1 as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp ; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes Statsig calculates daily and days-since-exposure views for user-day metrics per day. If a user is active on all 14 days of an experiment, they contribute 1 to the overall cumulative numerator, but 1 to each day of the daily view. The daily view doesn't deduplicate users. This behavior yields a more intuitive interpretation and produces less sparse timeseries data on long experiments. However, this behavior can also cause mix-shift effects, where the daily trend moves in the opposite direction of the cumulative timeseries. The mix-shift effect occurs because Statsig has already counted daily returning users, and those users don't add metric value to the cumulative view. Unit count metrics use the SQL SUM aggregation. Refer to the Options section below for many advanced options. ## Options - Metric Breakdowns: configure Metadata Columns to group results by for dimensional views in pulse results. - Multi Source: build metrics from multiple metric sources, equivalent to a UNION in SQL. Useful when the same measure exists in sharded or disparate tables. - Rollup Mode: controls the specific way that Statsig aggregates Unit Count metrics. ================================================================================ # Unit Count (Window) Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-window Updated: 2025-09-18 ================================================================================ # Unit Count (Window) Metrics ## Use cases Unit count (window) metrics flag whether a unit performed an action within a set time window after first exposure to the experiment. Use them to measure participation rates early in an experiment, or retention later in one, such as whether a user came back in their second week. ## Calculation At the unit level, unit count metrics create a 1/0 flag for if they participated during the time window. The time window is relative to the unit's first exposure. Statsig doesn't consider subsequent exposures. At the group level, Statsig calculates the mean as the SUM of the unit-level flags, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL for this calculation: ```sql -- Unit Level SELECT distinct source_data.unit_id, exposure_data.group_id, MAX(if(source_data.in_time_window, 1, 0)) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; ; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ## Options - Metric Breakdowns: configure Metadata Columns to group results by for dimensional views in pulse results. - Multi Source: build metrics from multiple metric sources, equivalent to a UNION in SQL. Useful when the same measure exists in sharded or disparate tables. - Rollup Mode: controls the specific way that Statsig aggregates Unit Count metrics. ================================================================================ # Unit Count (Latest Value) Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-latest Updated: 2025-09-18 ================================================================================ # Unit Count (Latest Value) Metrics ## Use cases Unit count (latest value) metrics flag whether a unit participated on the last observed day, which makes them useful for measuring state. For example, use them to determine whether a test variant has more active subscribers or active users than the control group. ## Calculation At the unit level, unit count metrics create a 1/0 flag for if they participated on a given day. Statsig carries the flag forward to the current date if data is behind. At the group level, Statsig calculates the mean as the SUM of the unit-level flags, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL for this calculation: ```sql -- Unit Level SELECT unit_id, group_id, if(passes_filter, 1, 0) as value FROM ( SELECT source_data.*, exposures_data.group_id, source_data.date = MAX(source_data.date) over (partition by source_data.unit_id) as is_latest_date FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp ) WHERE is_latest_date = 1 GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ## Options - Metric Breakdowns: configure Metadata Columns to group results by for dimensional views in pulse results. - Multi Source: build metrics from multiple metric sources, equivalent to a UNION in SQL. Useful when the same measure exists in sharded or disparate tables. - Rollup Mode: controls the specific way that Statsig aggregates Unit Count metrics. ================================================================================ # Unit Count (Daily Participation) Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-rate Updated: 2025-09-18 ================================================================================ # Unit Count (Daily Participation) Metrics ## Use cases Unit count (daily participation) metrics measure the fraction of days a unit performed an action during the experiment, comparable to DAU. Use them for growth accounting and for measuring ongoing usage and retention. ## Calculation At the unit level, unit count metrics create a 1/0 flag for if they participated on a given day. At the group level, Statsig calculates the mean as the SUM of the unit-level flags divided by each unit's days in the experiment. Statsig then divides that result by the count of UNIQUE UNITS exposed to the experiment. The SQL for this calculation: ```sql -- Unit Level SELECT distinct source_data.unit_id, exposure_data.group_id COUNT(distinct source_data.date) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, unit_id, date_diff(first_exposure_ds, today()) + 1 AS days_exposed FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value/days_exposed)/COUNT(distinct unit_id) as mean FROM unit_data JOIN group_data USING (group_id, unit_id) GROUP BY group_id; ``` ## Options - Metric Breakdowns: configure Metadata Columns to group results by for dimensional views in pulse results. - Multi Source: build metrics from multiple metric sources, equivalent to a UNION in SQL. Useful when the same measure exists in sharded or disparate tables. - Rollup Mode: controls the specific way that Statsig aggregates Unit Count metrics. ================================================================================ # Mean Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/mean Updated: 2025-09-18 ================================================================================ # Mean Metrics ### Use cases Mean metrics calculate the mean value of a numeric column in your metric source. You most often use them on event-level data, for example to measure "Average Time to Load" or "Average Purchase Value". ## Calculation At the unit level, mean metrics SUM their value column, and COUNT records where the value column is non-null. At the group level, Statsig calculates the mean as the SUM of the unit-level sums, and the SUM of the unit-level counts. The SQL looks like the following: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, SUM(source_data.value_column) as value, COUNT(source_data.value_column) as records FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp WHERE value_column IS NOT NULL GROUP BY source_data.unit_id, exposure_data.group_id; -- Group Level SELECT group_id, SUM(value)/SUM(records) as mean FROM unit_data GROUP BY group_id; ``` ### Methodology notes Internally, mean metrics function like a SUM/COUNT [Ratio](./ratio) metric. Statsig applies the delta method to mean metrics to account for covariance between unit-level numerators and denominators. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results. - Winsorization - Specify a lower and/or upper percentile bound to winsorize at. Statsig clamps all values below the lower threshold, or above the upper threshold, to that threshold to reduce the outsized impact of outliers on your analysis. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) let you specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and only calculates pulse results for that metric after a unit's metric has matured. ================================================================================ # Ratio Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/ratio Updated: 2025-09-18 ================================================================================ # Ratio Metrics ## Use cases Ratio metrics measure one metric divided by another (Count, Sum, Count Distinct, or Unit Count). Use them for a more nuanced understanding: revenue went up and purchase volume increased, but did revenue per purchase increase in a meaningful way? Ratio metrics also normalize metrics. For example, if you rent out devices like scooters, you might run a scooter-level experiment but want to measure average revenue per distinct rider. You can create a metric of SUM(revenue)/COUNT\_DISTINCT(rider\_id) to calculate this normalized metric and reduce the influence of scooters in popular areas that get many riders. ## Calculation At the unit level, ratio metrics calculate the unit-level aggregation of both component metrics. At the group level, the mean is the total group value of the first metric divided by the total group value of the second metric. > **Note:** > > The denominator isn't the number of units in the experiment; the normalization is by the denominator metric. The SQL for this calculation: ```sql -- Denominator (Checkouts) SELECT source_data.unit_id, exposure_data.group_id, COUNT(1) as denominator FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Numerator (Revenue) SELECT unit_id, group_id, SUM(revenue) as numerator FROM source_data GROUP BY unit_id, group_id; -- Group Level SELECT group_id, SUM(numerator)/SUM(denominator) as mean FROM denominator -- full outer join depending on settings LEFT JOIN numerator USING (group_id) GROUP BY group_id; ``` ### Methodology notes Ratio metrics require adjustment because the numerator and denominator may covary at the unit level. Statsig uses the delta method to estimate this adjustment. By default, Statsig treats ratio metrics as a conversion rate (unordered), counting numerator events only for units that also performed the denominator event. In Statsig Warehouse Native, you can configure this behavior through Advanced settings at the metric level. ## Options - Treat as conversion rate (unordered): includes numerator events only if the unit also performed the denominator event, regardless of order. Uncheck for a simple ratio, which counts numerator events for all units even if they never performed the denominator event. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) (Numerator and Denominator): specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after exposure. - Winsorization: specify a lower and/or upper percentile bound. You can set thresholds independently for the numerator and denominator. Statsig clamps all values below the lower threshold or above the upper threshold to reduce the impact of outliers. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows): specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and calculates pulse results only after a unit's metric has matured. ================================================================================ # Funnel++ URL: https://docs.statsig.com/statsig-warehouse-native/metrics/funnel Updated: 2025-09-18 ================================================================================ # Funnel++ Funnel++ measures how users convert through a defined sequence of steps in an experiment, so you can see completion rates and where users drop off between steps. Funnel++ extends standard funnel analysis with per-step completion windows, session-level conversion, and built-in tolerance for timestamp noise, all within the statistical framework Statsig uses for Pulse analysis. > **Info:** > > Funnel++ is a Statsig Warehouse Native feature. ## How funnel metrics work Funnel metrics measure user journeys through a series of steps. For configuration guidance, refer to [funnel metrics](https://docs.statsig.com/statsig-warehouse-native/features/funnel-metrics). Statsig provides advanced capabilities within the statistical framework used in pulse analysis. These include: - Configurable completion windows per-step - Session controls - going beyond user-based conversion - Built-in allowance for timestamp noise ### Use cases Use funnel metrics to understand how users move through your product. For example, you might want to measure: - User conversion through a subscription flow, for example Start -> Description Page -> Payment Info -> Confirm, to measure if an experiment causes users to drop off less, and at which steps. - User conversion from "logged out visitor" to "first logged-in-article-read" using Statsig's [ID Resolution](https://docs.statsig.com/statsig-warehouse-native/features/funnel-metrics). - Session-level conversion for checking out a vacation property, to understand conversion for every unique checkout flow, not only at the user level. ## Calculation At the unit level, funnel metrics calculate, for each step of the funnel, if the unit completed that step some time after completing all previous steps in order. This creates a series of step flags. If using session funnels, those step flags are instead counts of unique sessions. At the group level, Statsig calculates the stepwise mean as the units for the next step divided by the units for the current step. Statsig calculates the overall mean as the units/sessions that completed the funnel divided by the unit/sessions that started the funnel. > **Note:** > > For each step, Statsig treats the _first_ occurrence after the previous step as the canonical trigger and timestamp for that event in subsequent timestamp comparisons. The SQL looks like the following: ```sql -- Unit Level, per step SELECT distinct source_data.unit_id, source_data.funnel_session_id, -- optional source_data.funnel_step_id, IF(`<Completed All Steps Up to Current Step In Order>`, 1, 0) as numerator, IF(`<Completed Previous Steps In Order>`, 1, 0) as denominator FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp ; --Group Level SELECT group_id, funnel_step_id, SUM(numerator)/SUM(denominator) as mean FROM unit_data GROUP BY group_id; ``` ### Methodology notes Conversion metrics require adjustment due to potential unit-level covariance between the numerator and the denominator. Statsig uses the delta method to estimate this adjustment. By default, Statsig only includes numerators from metrics with non-null, non-zero denominators. You can configure this behavior in the advanced settings. In experiment analysis, funnels enforce strict ordering. For example, in the funnel A->B->C, all subsequent timestamp comparisons use the FIRST occurrence of A. Consider a user who has an A event on day 0 with no other events, and then completes A, B, and C in order on day 5. If the conversion window from A->B is 1 day, this funnel won't count as completed, because the time from the first A to the first B is 5 days. ## Options - Conversion window - A step-level setting specifying how long this step has to occur after the previous step. For example, in the funnel A->B->C, if B has a conversion window of one hour, Statsig only counts it if it occurs within 1 hour of A. - Use Strict Event Ordering - Whether to use >= or > when comparing step timestamps. Strict mode allows you to have two subsequent steps of the same event without it "automatically" passing. - Timestamp Allowance - Allow some amount of buffer, in milliseconds, between funnel steps. Event logs can have noise on timestamps, so sometimes events may be logged slightly out of order. This setting helps to correct for this issue. - Count Distinct Mode - Whether to count sessions or units. For sessions, you must provide a session identifier field on each step. - Calculation window (optional) - How long a unit has to complete the funnel after starting, and whether the funnel starts when the unit is exposed to the experiment or when they trigger the first event in the funnel - Treat Exposure as Initial Funnel Event - With this setting enabled, the first step of the funnel is the exposure event of the experiment. This makes it easy to measure the conversion rate to the first event, and additionally normalizes the final outcome per experiment-user. This setting is incompatible with session-based funnels. - Measure time to complete - Switches the funnel mode into measuring the average time for users to complete a funnel. This creates a ratio metric, where the numerator is the sum of funnel seconds-to-complete, and the denominator is the number of completed funnels. This can be useful in isolation, or when paired with a conversion measurement to understand the change to both completion rate and time to complete. ## Visualization In addition to breaking down lift by funnel steps, you can create funnel visualizations by step. ![Funnel visualization by step breakdown](https://docs.statsig.com/images/statsig-warehouse-native/metrics/funnel/c38ca372-5323-408f-89b6-121300b4e60c.png) ![Funnel step analysis chart](https://docs.statsig.com/images/statsig-warehouse-native/metrics/funnel/8e10442f-be78-455e-84a3-053e4a61434a.png) ================================================================================ # Percentile Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/percentile Updated: 2025-09-18 ================================================================================ # Percentile Metrics ### Use cases Percentile metrics calculate a customizable Nth percentile (for example, p50, p90, or p99) of a numeric column across experiment groups. Use them when the mean of a metric can be acceptable while the tail end, such as the 99th percentile, is not. Consider a website with an average TTL of 300ms but a p99 TTL of 1 minute. A small portion of the population has an unusable experience that doesn't appear in the mean, making it difficult to measure whether the p99 value changed with traditional A/B/n metrics. Percentile metrics are common as guardrail metrics for performance regression, and for measuring improvements from investments in performance and infrastructure. ## Calculation For percentile metrics, there is no unit-level calculation; Statsig runs the analysis at the group level. The SQL looks like the following: ```sql -- Group Level SELECT exposures_data.group_id, PERCENTILE(user_data.value, percentile_level) as value, COUNT(distinct user_data.user_id) as population FROM user_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp WHERE value IS NOT NULL GROUP BY group_id; ``` ### Methodology notes Percentile metrics use the outer CI method to estimate a confidence interval and significance. Deng et al. describe the methodology in section 4 of [this paper](https://arxiv.org/pdf/1803.06336). > **Note:** > > Some metrics aren't well-formed for this approach, because the method assumes the underlying distribution is continuous. For example, if your data has 1/3 of rows with a value of 0, 1/3 with a value of 5, and 1/3 with a value of 10, Statsig doesn't calculate significance for a median or p99 metric because there is no local variability. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results ================================================================================ # Log Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/log Updated: 2025-09-18 ================================================================================ # Log Metrics ### Use cases Log metrics are useful for understanding if the distribution of a log-normal or tail-driven metric has shifted. Statsig calculates the metric as a conditional mean: a ratio metric where the numerator is the sum of unit-level log values and the denominator is 1 for units with a valid log. Statsig filters out records with a 0 denominator, because imputing 0s for logs doesn't work without a treatment such as an inverse hyperbolic sine function. Common uses include revenue, time spent, or other metrics where a small portion of users drives most of the value but bulk improvements matter. Log metrics measure relative change per unit: an increase of 1 corresponds to a multiplication by the log's base. ## Calculation At the unit level, count metrics run a COUNT(1) or SUM(`value`) across their metric source. At the group level, Statsig calculates the mean as the SUM of the log of the unit-level value, divided by the count of units with a unit-level value that log is valid for (exists, and is greater than 0). The SQL for a count metric looks like the following: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, COUNT(1) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY unit_id, group_id; -- Group Level SELECT group_id, -- divide the sum of the logged values by the count of participating units SUM(LOG(value, <base>))/COUNT(1) as mean FROM unit_data WHERE value > 0 -- the filter is implicit from the CTE, but let's make it explicit -- a sum metric might have negative values GROUP BY group_id; ``` ### Methodology notes Log metrics can be difficult to interpret and to extrapolate to topline values. Use log metrics together with the raw or winsorized SUM and COUNT metric. There are a few ways to handle 0s in a log metric. A transformation like [IHS](https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions) can approximate the behavior of log for large values while accepting 0s as inputs. Alternatively, you can scope the analysis to non-zero units. Statsig uses the second approach for ease of interpretation, because people broadly understand log properties. Scoping to non-zero units introduces a potential confounding factor: participation rate. To mitigate this confounding factor, Statsig presents results the same as for [ratio](https://docs.statsig.com/statsig-warehouse-native/metrics/ratio) metrics, including statistics for the overall result and the implicit numerators and denominators. ## Options Non-log options depend on whether the metric is a Sum or Count. - Custom log Base - You can configure a custom base for the log operation. Defaults to LN. ================================================================================ # First or Latest Value Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/latest-value Updated: 2025-09-18 ================================================================================ # First or Latest Value Metrics ## Use cases ### First Value First value metrics track the initial experience a user has with your product. Examples include first purchase value, initial time-to-load, or any other initial result you expect to influence with your change. ### Latest Value Latest value metrics track how an experiment is impacting the state of your population. For example, you might want to measure if the test group has a higher net account balance, or if the current loyalty rewards balance is higher for users in one arm of an experiment. You can use latest value metrics to approximate user statuses, such as "is\_subscriber", if you have a Metric Source with a 1/0 flag for all users. Statsig recommends the [unit count](./unit-count-latest) equivalent for this use case, because you can filter on a sparse dataset and Statsig handles imputing and tracking 0s. ## Calculation At the unit level, first value metrics calculate each day's first non-null value within cohort bounds. Similarly, latest value metrics calculate each day's latest non-null value within any cohort bounds. For pulse, Statsig carries the first value forward from the first date with data, and determines the latest value by taking the latest value from the latest day available. At the group level, Statsig calculates the mean as the SUM of the unit-level values, divided by the count of UNIQUE UNITS exposed to the experiment. The SQL looks like the following: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, LATEST_VALUE(source_data.value_field) as value -- or FIRST_VALUE FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp WHERE value_field IS NOT NULL GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes Statsig treats users without a value as 0s. If an existing value is present, the user retains that value unless you provide a 0 or a new value later. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. - [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) - Specify if you want to calculate CUPED, and the lookback window for CUPED's pre-experiment data inputs. ### Special case: surrogate metrics You can use latest value metrics to implement surrogate metrics. Surrogate metrics (also called proxy metrics or predictive metrics) predict a long-term metric that's impractical to measure over the duration of an experiment. Surrogate metrics have some inherent prediction error from the model used to derive the metric values. In advanced settings for latest value metrics, you can indicate a metric as a surrogate metric with a mean squared error (MSE). Statsig then accounts for prediction accuracy in variance calculation, which adjusts p-values and confidence intervals accordingly. Consider the variable X to be the true north metric that the surrogate metric S predicts. Assume the surrogate metric S is an unbiased estimator with an error term $\epsilon$. $$ \mu_{X} = \mu_{S} = \overline{S} $$ $$ Var(X) = Var(S + \epsilon) = Var(S) + MSE $$ $$ Var(\overline{X}) = \frac{Var(X)}{n} = \frac{Var(S) + MSE}{n} $$ ================================================================================ # Retention Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/retention Updated: 2025-09-18 ================================================================================ # Retention Metrics ## Use cases Retention metrics measure user stickiness, conversion, and growth over the duration of experiments and holdouts. For example, a retention metric can evaluate changes in "Current User Retention", "Notification Retention", or "Video Viewer Retention" over an experiment, broken down in timeseries and days-since-exposure views. Many platforms limit retention metrics to checking if a unit was active between days X and X+Y since exposure. This approach is useful for new-user or marketing experiments but is less useful for experiments targeted at an existing user base. [This article in Lenny's newsletter](https://www.lennysnewsletter.com/p/how-duolingo-reignited-user-growth) shows how teams use these metrics to drive user growth. Use this metric type for any change aimed at increasing user stickiness, such as changes to notifications, reactivation campaigns, or quality improvements. ## Setup and definition You define retention metrics with a duration and a lookback window. Statsig measures the period backwards from the end. For example, "Lookback = 7, Duration = 14" (L7D14) measures the week ending 14 days after the start event. ![Retention Setup](https://docs.statsig.com/images/statsig-warehouse-native/metrics/retention/cce09282-0a9b-4218-b823-7416f03ef387.png) The retention metric uses a rolling calculation. Each day a user triggers the start event, the metric denominator increments by 1. If the user is active in the corresponding completion window, the numerator is 1 for that day. Statsig includes only days with completed windows in pulse. For example, if the duration is 7, Statsig excludes the last week of data from pulse to avoid diluting the metric. An L3D7 metric would always have a numerator of 0 for those days. The `allow cohort metrics to mature after experiment end` setting in advanced experiment settings allows post-experiment data to complete the analysis. As a result, Statsig includes units exposed later in the experiment. Use this setting when the treatment is one-time and you don't need to re-apply it to affect users. ![Retention Explanation](https://docs.statsig.com/images/statsig-warehouse-native/metrics/retention/2a9d8731-1c28-4c59-a0fe-3c1e7586c129.gif) ## Calculation ```sql -- Denominator - 1/0 flag for activity on a day WITH denominator AS ( SELECT source_data.unit_id, source_data.date, exposure_data.group_id, MAX(1) as denominator FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp WHERE <start_filter> GROUP BY ALL; ), -- Numerator Candidates - 1/0 flag for success activity on a day -- Note by default this is equivalent to the denominator CTE numerator_candidates AS ( SELECT source_data.unit_id, source_data.date, exposure_data.group_id, MAX(1) as denominator FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp WHERE <success_filter> GROUP BY ALL ), -- Numerators, deduplicated - 1/0 flag for success per denominator -- Now we have a 1-0 numerator flag per denominator-day joined_data AS ( SELECT denominator.unit_id, denominator.date, den.group_id, 1 as denominator MAX(CASE WHEN numerator_candidates.unit_id IS NOT NULL THEN 1 ELSE 0 END) as numerator FROM denominator LEFT JOIN numerator_candidates ON denominator.unit_id = numerator_candidates.unit_id AND numerator_candidates.date BETWEEN denominator.date + INTERVAL '<END - (LENGTH - 1)>' DAY AND denominator.date + INTERVAL '<LENGTH>' DAY GROUP BY ALL ) -- Group Level SELECT group_id, SUM(denominator) as unit_days_started, SUM(numerator) as unit_days_completed, SUM(numerator)/SUM(denominator) as mean FROM joined_data GROUP BY ALL ``` ### Methodology notes Statsig treats retention metrics as [ratio metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/ratio) for pulse calculations. The only distinction is that Statsig attributes the metric date to the denominator date. The ratio components for retention metrics reflect the rolling metric definition: - the denominator is the average number of days per user where the user triggered the "retention start" event. - the numerator is the average number of days per user where a "retention start" event had a corresponding "retention end" event in its retention period. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results - Retention Lookback Window (Days) - The length of the "Completion Event" collection window - Retention Period End (Days) - When to stop measuring retention completion events - Use a different start and completion event for retention calculations: choose a secondary event for completion windows. By default, retention measures a behavior's retention against itself. This option lets you measure a secondary event instead. For example, with user accounting flags, you can measure "IS CHURNED" -> "IS REACTIVATED" and "IS REACTIVATED" -> "IS CHURNED" to track both reactivation and falloff of a long-term marketing test. ================================================================================ # Max/Min Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/max-min Updated: 2025-09-18 ================================================================================ # Max/Min Metrics ### Use cases Max/min metrics track users' extremes during an experiment. Common examples are: - Measuring the impact of performance changes on users' worst experiences by analyzing the maximum latency per user. - Measuring the effect of game changes on user performance by calculating the peak high score per user. - Counting the number of users who ever left a 2-star review or lower by applying MIN(review\_score) with a threshold condition. ## Calculation for max/min At the unit level, max/min metrics take the max/min of their input column. At the group level, Statsig calculates the max/min as the MEAN of the unit-level sums, divided by the count of UNIQUE UNITS exposed to the experiment. The MAX looks like the SQL below: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, MAX(source_data.value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` The MIN looks like the SQL below: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, MIN(source_data.value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ### Methodology notes Max/min metrics are simple to use and offer many advanced options. ## Options - Metric Breakdowns - You can configure Metadata Columns to group results by, getting easy access to dimensional views in pulse results. - Winsorization - Specify a lower and/or upper percentile bound to winsorize at. Statsig clamps all values below the lower threshold, or above the upper threshold, to that threshold to reduce the outsized impact of outliers on your analysis. - CUPED - Specify if you want to calculate CUPED, and the lookback window for CUPED's pre-experiment data inputs. - Thresholding - Turn this metric into a 1/0 unit count metric counting if the unit's max/min equals to or surpasses (>=) a given threshold. - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) let you specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and only calculates pulse results for that metric after a unit's metric has matured. ================================================================================ # Composite Metrics URL: https://docs.statsig.com/statsig-warehouse-native/metrics/composite ================================================================================ # Composite Metrics ### Use cases Composite metrics are a flexible metric type designed to sum aggregated metric sources at the user level. Use them when you need to add or subtract two or more aggregated values into a single signal, such as: - Net value (e.g., revenue minus refunds) - Unit-level experiment change (latestvalue minus first value) ## Calculation At the unit level, composite metrics first compute the aggregations of each component. Statsig then adds or subtracts the aggregated results according to the formula specified (for example: `A + B` or `A - B + C`). Statsig performs this calculation at a daily, 7-day, and cumulative level during experiment analysis. > **Note:** > > Composite metrics don't support daily rollups in turbo mode. At the group level, Statsig calculates the mean as the average of the unit-level composite aggregation. ### Example If you define a composite gap metric as `Max Price - Min Price`, Statsig computes `Max Price` and `Min Price` for each user, then subtracts to get each user's net value. The experiment group mean is the average of those per-user results. The SQL for the individual components looks like the following: MAX Component: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, MAX(source_data.value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` MIN Component: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, MIN(source_data.value_column) as value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` Composite Aggregation: ```sql -- Unit Level SELECT source_data.unit_id, exposure_data.group_id, MAX(source_data.value_column) - MIN(source_data.value_column) AS value FROM source_data JOIN exposure_data ON -- Only include users who saw the experiment source_data.unit_id = exposure_data.unit_id -- Only include data from after the user saw the experiment -- In this case exposure_data is already deduped to the "first exposure" AND source_data.timestamp >= exposure_data.timestamp GROUP BY source_data.unit_id, exposure_data.group_id; -- Experiment SELECT group_id, COUNT(distinct unit_id) total_units FROM exposure_data GROUP BY group_id; -- Group Level SELECT group_id, SUM(value)/SUM(total_units) as mean FROM unit_data JOIN group_data USING (group_id) GROUP BY group_id; ``` ## Options - [Cohort Windows](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics) - You can specify a window for data collection after a unit's exposure. For example, a 0-1 day cohort window counts only actions from days 0 and 1 after a unit is exposed to an experiment. - Select **Only include units with a completed window** to remove units from pulse analysis for this metric until the cohort window has completed. - [Winsorization](https://docs.statsig.com/experiments/statistical-methods/methodologies/winsorization) - Specify a lower and/or upper percentile bound to winsorize at. Statsig applies these bounds separately to the top-level metric and its individual components. - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) - [Baked Metrics](https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics#metric-bake-windows) let you specify how long a metric needs to mature. Metric maturation is common for chargebacks or cancellations. Statsig delays loading the data until the window has elapsed, and only calculates pulse results for that metric after the unit's metric has matured. ================================================================================ # Metric Examples URL: https://docs.statsig.com/statsig-warehouse-native/configuration/metric-examples Updated: 2025-09-18 ================================================================================ # Metric Examples Statsig Warehouse Native supports common metric types including revenue, account value, participation, funnel, and retention metrics. These examples show the SQL and metric-source setup for each type and explain how Statsig calculates them in experiments. Use them as templates when you set up your own metrics against your warehouse tables. If you're transitioning from another warehouse-native vendor, the metric format is similar. Customers have generally been able to use APIs to fetch remote configurations, translate them, and post them to Statsig without issue. If you're migrating from an in-house system, there may be differences between how you define experiment metrics internally and how Statsig handles them. ## Average user revenue from a wide table In many cases, companies have a primary source-of-truth table about user engagement with one row per user-day and many columns representing actions taken or other values. This table type integrates directly with Statsig. First, enter the table path and optionally a partition column to use for date partitioning: ![Metric source setup specifying table path and date partition](https://docs.statsig.com/images/whn/metric_examples_configuration.png) Then, configure your timestamp field and ID types. Add any custom SQL aliases, for example, dividing revenue by 100 to convert from cents to dollars. ![Timestamp and ID type configuration with revenue alias](https://docs.statsig.com/images/whn/metric_examples_initials.png) Go to the metrics tab, press create, configure your name/source, and then configure a sum metric on the column with the revenue value. ![Create metric dialog selecting revenue source](https://docs.statsig.com/images/whn/metric_examples_create_revenue.png) ![Sum metric configuration for revenue column](https://docs.statsig.com/images/whn/metric_examples_configure_revenue.png) ### How it works in experiments First, Statsig aggregates each unit-level record across the days they are enrolled in the experiment. Then, Statsig calculates the mean unit-level revenue per experiment group, imputing 0s for all exposed users with no revenue. Statsig provides a description of this in-product for any user who wants to learn more: ![Inline description explaining aggregation behavior](https://docs.statsig.com/images/whn/metric_examples_configuration.png) ## Average current account value Often, you want to understand if your experiment has altered the state of users. For example, you may want to know whether users in test vs. control have grown their account value. To measure this, provide a table or query that tracks users' account values each day. Then, set up a metric source pointing to that table or query. Go to the metrics tab, press create, configure your metric name & source, and then configure a latest value metric on the column with the account value. ![Create metric form for latest account value](https://docs.statsig.com/images/whn/metric_examples_create_account.png) ![Latest value metric configuration using account column](https://docs.statsig.com/images/whn/metric_examples_configure_account.png) ### How it works in experiments First, at unit level, Statsig calculates each day's latest non-null value within any cohort bounds and takes the latest value from the latest day available. Then, Statsig calculates the mean unit-level value per experiment group on each day, imputing 0s for all exposed users with no value. Statsig provides a description of this in-product for any user who wants to learn more: ![Product tooltip describing latest value aggregation logic](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/7fe6af8f-02a9-45f4-ae3f-5c682757e571.png) ## Users' D7 participation rate A common metric in experimentation is measuring whether exposed users take specific actions within a defined time window. Provide an event table that records user actions with essential columns such as user\_id, timestamp, and event type. Configure your timestamp field and ID types as the previous sections describe. ![Event table metric source definition for participation rate](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/148469b7-df7b-4f39-af87-1ee9dd5ee431.png) ![ID type configuration for participation event data](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/5bd9fcc7-54e1-4a15-a8c4-8d9950631d24.png) Navigate to the metric catalog and create a unit count metric using the defined metric source. Use the 'Add Filter' option to focus on specific events relevant to your metric. ![Unit count metric creation with filters for specific event](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/04712a16-8dac-4c1f-a327-1854fd15d2aa.png) When defining the metric, you can choose from several rollup modes: - Daily Participation Rate: measures the days a unit was active after exposure, divided by its total days in the experiment - On-Time Event: measures whether a unit performed an action any time after exposure - Latest Value: measures whether a unit passed metric filters on their last observed record - Custom Attribution Window: includes data for each unit within a specified time window after exposure ![Metric source selection during creation flow](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/959c5dbd-eecf-4797-bc87-7970ccda4947.png) To measure user participation within 7 days, select 'Custom Attribution Window' as your rollup mode and set start = 0, end = 6 to define a 7-day window. Enable 'Only include units with a completed window' to exclude users who haven't yet reached the full 7-day period from your analysis. ![Rollup mode options for participation metrics](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/0632de2f-dc8c-44c0-85c1-39e8a6a6f070.png) ### How it works in experiments First, at unit level, Statsig creates a 0/1 flag if the event triggers during the specified time window. Then, at the group level, Statsig calculates the mean as the SUM of the unit-level flags, divided by the count of UNIQUE UNITS exposed to the experiment. Refer to [Unit Count (Window) Metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/unit-count-window) for more details about how Statsig calculates these metrics. ## User funnel metric A common analysis in experimentation is understanding how a new feature impacts dropoff rates at each step of a user funnel. To create a funnel metric in Statsig, you need an event table that records each step of the events you want to track. The setup for your metric source follows the same process that previous sections describe. Navigate to the metric catalog, and select 'Funnel' as your metric type. Choose the unit level for your funnel steps: a distinct count of users or sessions, depending on what you want to measure. ![Average session count metric configuration](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/76c815a1-14a6-4d8c-853e-10460f38d4a6.png) Then, define your funnel steps, specifying the sequence of events users go through. ![Example showing multi-event participation configuration](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/91d50945-ba23-47d0-b0e4-85308a0e404c.png) In the Advanced Settings, you can further customize your funnel metric. Options include specifying a calculation window, measuring time to convert, and treating exposure as the initial funnel event. ![Metric filters applied to isolate specific event values](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/a6de4690-83ad-49ed-af9a-4eef9c6a9700.png) ### How it works in experiments First, at unit level, Statsig constructs a 1/0 (or session-count number for session funnels) metric for each step of the funnel. This flag is 1 if the unit completed that step some time after the unit completed all previous steps in order. If using a session-level funnel, it's the number of sessions where that is true, e.g. the unit completed all previous steps in order for that session key. Then, at the group level, Statsig calculates the stepwise mean as the total of each step's metric divided by the total metric from the previous step. Statsig calculates the overall mean as the units/sessions that completed the funnel divided by the unit/sessions that started the funnel. Statsig provides a description of this in-product for any user who wants to learn more: ![Metric catalog entry summarizing event-based conversion metric](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/84c22973-af41-495d-a943-f0f7436050ee.png) ## User retention rate A retention metric measures changes in user stickiness and product growth. To create a retention metric in Statsig, you need an event table that captures the key activities indicating user retention. The setup for your metric source follows the same process that previous sections describe. Navigate to the metric catalog and select 'Retention' as your metric type. Configure the retention period and lookback window. For example, suppose you set 'Retention Period End' to 14 and the retention lookback window to 7. Statsig then measures retention as whether the user triggered the retention event between day 8 and day 14. ![Configuration UI for retention-style rollup](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/e418815e-505c-4356-9922-d706bebb053c.png) Enable "Use a different start and completion event for retention calculations" if you want to use a starting event other than exposure. You can also enable it to define a specific subset of events as your retention event. For example, based on the setup in the screenshots, this measures the week 2 retention rate of users who made a purchase in week 1. ![Metric details view describing rollup logic](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/d3e12922-3767-4a05-987b-e16df126ea41.png) In the Advanced Settings, you can configure the ID type for your retention metric. ![Metric result example for session count](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/cdf184a4-cd3a-4622-8669-0d029b1e76dc.png) ### How it works in experiments First, for each unit per day, Statsig checks if the retention start event triggers and assigns a 0/1 flag, which serves as the denominator of the calculation. Next, Statsig checks if the retention completion event occurs within the specified time window and assigns a 0/1 flag, which serves as the numerator of the calculation. Finally, at the group level, Statsig calculates retention as sum(numerator) / sum(denominator) to determine the overall retention rate. Statsig provides a description of this in-product for any user who wants to learn more: ![Example of metric insight card for participation rate](https://docs.statsig.com/images/statsig-warehouse-native/configuration/metric-examples/94843265-ed43-4bce-954f-3f64ec2d380f.png) ================================================================================ # Cohort Metrics URL: https://docs.statsig.com/statsig-warehouse-native/features/cohort-metrics Updated: 2025-09-18 ================================================================================ # Cohort Metrics Cohort metrics analyze an experiment's impact within a fixed time window relative to each unit's exposure. Common use cases include: - Ensuring all users have equal periods for data collection creates a direct comparison across users enrolled early or late in the experiment (which often corresponds to power or occasional users), and across different time periods that may have extrinsic factors like holidays. - If you analyze an unbounded period, experimental units' variance in the population can increase over time. This variance increase leads to a scenario where error bars don't converge toward 0 even as you run the experiment longer. - Cohort metrics let you skip noisy early metrics, or focus on outcomes after users might churn. For example, they can capture "week-2 engagement" if a product has a 1-week trial period. - You can also use cohort metrics to capture "one-shot retention". [Retention metrics](https://docs.statsig.com/statsig-warehouse-native/metrics/retention) capture rolling, ongoing retention. A user metric with a window from day X to day Y is a good way to check if an experiment is causing more users to retain at least X days. The downsides of cohort metrics are that: - They don't capture any long-term impact, or how impact evolves over time. Cohort analysis is purely a point-in-time analysis and may not be appropriate for measuring complex, evolving behaviors. - They make topline impact estimates lossier and harder to trust. Some practitioners have made compelling arguments that cohort metrics are a better "standard" metric for organizations to use in analysis. Statsig believes that using cohorts depends on business context. Consider whether cohorts should be at least part of an experiment's measurement. For example, measure topline revenue as an overall evaluation criteria, but also measure 7-day revenue alongside it for additional context. This page explains the available settings, what they do, and how they interact so you know what Statsig measures. ## Basic cohort windows Basic cohort windows are a filter on metric data with a time range relative to the unit's time of exposure. For example, a cohort window from day 1 to day 6 filters to events from 24 hours until 168 hours after exposure. > **Note:** > > Statsig calculates this as a timestamp comparison; a unit enrolled at 12pm has exactly 24 hours until it reaches the end of a 0-1 day cohort. For metrics from data sources marked as daily data, Statsig truncates the cohort comparison to a date so that day-0 data behaves as expected (e.g. a user exposed on `2025-01-05T09:00` includes the date-based data from `2025-01-05` instead of truncating to times "after 9:00am"). ## Waiting for maturation By default, cohort metrics can have a mix of maturation levels in the experimental population. For a 1-week cohort, users enrolled in the final week have a mix of maturities during analysis. This yields the maximum sample but can dilute the analysis with partial cohort windows. To prevent this, mark the metric as "Wait for cohort window to complete". This setting drops units' metric data from analysis and removes them from the experiment analysis population. In the examples below, one metric forces cohorts to complete. It has fewer units in the analysis, because many units don't have a complete window. It has a lower total because of the small unit count. It has a higher mean, because the units it includes have completed their window and have a longer data collection period on average. ![Metric that did not wait to mature](https://docs.statsig.com/images/whn/basic_cohort_metric.png) ![Metric that waited to Mature](https://docs.statsig.com/images/whn/wait_to_mature_metric.png) This setting can lead to different populations between metrics. It also filters out the last few days of an experiment's data in the daily time series, because new cohorts' data is not yet complete. View a metric's cohort settings by hovering over the metric name in the experiment scorecard. ## Visual examples This is what data collection looks like for a standard cohort metric with a 0-6 day window. This collects data for **7 days** because it's 0-indexed. ![Timeline from January 5 to 15. A user is exposed midday on January 5, and the 0-6 day cohort window covers days 0 through 6, ending midday on January 12 and capturing five user events. The experiment ends on January 12, after the window closes, so two later events fall outside the window.](https://docs.statsig.com/images/diagrams/cohort-window-basic.svg) ![Timeline from January 5 to 15. A user is exposed midday on January 5, and the 0-6 day cohort window covers days 0 through 6, ending midday on January 12 and capturing five user events. The experiment ends on January 12, after the window closes, so two later events fall outside the window.](https://docs.statsig.com/images/diagrams/cohort-window-basic.dark.svg) If the cohort period extends past the end of the experiment, Statsig truncates data collection to the end of the experiment by default. ![Timeline from January 5 to 15. A user is exposed midday on January 5, so the 0-9 day cohort window would run past the experiment end on January 12. Statsig truncates data collection at the experiment end, giving this unit between 7 and 8 days of collected data and five captured events.](https://docs.statsig.com/images/diagrams/cohort-window-truncated-at-end.svg) ![Timeline from January 5 to 15. A user is exposed midday on January 5, so the 0-9 day cohort window would run past the experiment end on January 12. Statsig truncates data collection at the experiment end, giving this unit between 7 and 8 days of collected data and five captured events.](https://docs.statsig.com/images/diagrams/cohort-window-truncated-at-end.dark.svg) If you configure the metric to allow only completed cohort windows, Statsig excludes the unit from the analysis. Statsig doesn't include excluded units in the denominator for the average value of a sum or count metric, and filters their metric data from the analysis. ![Timeline from January 5 to 15. A user is exposed midday on January 5 and the experiment ends about 7.5 days later, on January 12, before the 0-9 day cohort window completes. Because the metric only includes units with a completed window, this unit and its events are excluded from the analysis.](https://docs.statsig.com/images/diagrams/cohort-window-incomplete-excluded.svg) ![Timeline from January 5 to 15. A user is exposed midday on January 5 and the experiment ends about 7.5 days later, on January 12, before the 0-9 day cohort window completes. Because the metric only includes units with a completed window, this unit and its events are excluded from the analysis.](https://docs.statsig.com/images/diagrams/cohort-window-incomplete-excluded.dark.svg) If you configure mature after end in the experiment, data collection continues after the experiment ends, regardless of whether you enable "wait for mature". ![Timeline from January 5 to 15. A user is exposed midday on January 5. Because the experiment allows cohort metrics to mature after it ends, the 0-9 day window continues past the January 12 experiment end and captures six events, one of which occurs after the experiment ended.](https://docs.statsig.com/images/diagrams/cohort-window-matures-after-end.svg) ![Timeline from January 5 to 15. A user is exposed midday on January 5. Because the experiment allows cohort metrics to mature after it ends, the 0-9 day window continues past the January 12 experiment end and captures six events, one of which occurs after the experiment ended.](https://docs.statsig.com/images/diagrams/cohort-window-matures-after-end.dark.svg) ## Experiment-based cohort settings Statsig also provides cohort controls at the experiment level. The relevance of these settings depends on the kind of experiment you run, as the following sections describe. ### Allow post-experiment cohort data Checking **Allow Cohort Metrics to Mature After Experiment End** allows Statsig to collect metrics after the experiment ends. Statsig recommends this for one-time interventions, such as a new signup page, because post-experiment signal from units that received the intervention provides additional statistical power. ![Allow Cohorts to Mature](https://docs.statsig.com/images/whn/allow_cohorts_to_mature.png) Statsig **doesn't** recommend this for continuous interventions, such as a ranking change, because post-experiment data can become diluted. For example, test users may receive the control experience during their post-experiment period, which dilutes results. Statsig extends the analysis past the experiment end by the length of the longest cohort window across all metrics. Statsig constrains non-cohorted metrics to the analysis period and filters cohort metrics to the experiment end plus their cohort window. ### Fixed duration On the **Experiment Population** section of the experiment setup page, **Configure Analysis Period** with Analysis Type **Fixed Duration** counts metrics only for a specified period after **experiment start**. This is useful for experiments with a fixed enrollment point, such as email campaigns. ![Analysis Period Settings](https://docs.statsig.com/images/whn/configure_analysis_period.png) You can use this setting only for assign and analyze experiments. ### Cohorted duration On the **Experiment Population** section of the experiment setup page, **Configure Analysis Period** with Analysis Type **Cohorted Duration** applies allocation-based cohorting globally to all metrics in the experiment analysis. This is the same as the metric-based cohort but applied experiment-wide. This is useful for new user experiments. > **Note:** > > When you use this with metric cohorts, Statsig uses the minimal end of the cohort window. For example, if you set a metric cohort to end at 7 days and the experiment at 10 days, Statsig uses 7. If you set the metric cohort to end at 7 days and the experiment at 5 days, Statsig uses 5. You can also specify the **only include units with a completed cohort window** setting at the experiment level, and it applies to all metrics in the experiment when set. If not checked, Statsig applies the setting on a metric-by-metric basis. ## Metric bake windows In some cases, a metric in your warehouse may not be mature until a certain time has passed, after which you care about the daily value. Statsig provides the option to specify a bake window for your metrics. Statsig excludes metrics that haven't reached the end of their bake window from the numerator and denominator of the metric in the analysis. Daily revenue is an example of a metric that may not be immediately mature. If a user makes a purchase and refunds it a few days later, their daily revenue retroactively changes to reflect the refund. A 28-day refund period aligns naturally with a 28-day bake window for revenue metrics. ![Metric Bake Example](https://docs.statsig.com/images/statsig-warehouse-native/features/cohort-metrics/7c0ca9e7-ae49-4213-96aa-e0815a46940e.png) In the example above, the revenue metric covers the last 28 days. Rather than calculating a partial result, Statsig excludes users from the analysis until their data has had 28 days to mature. Partial results can occur because, when a metric bakes over a long period, part of the metric values come from before the experimental intervention and dilute the results. For a user exposed 1 day ago, 27 of 28 days of their revenue metric are from the pre-intervention period, diluting the experiment results. ================================================================================ # Dimension Analysis URL: https://docs.statsig.com/statsig-warehouse-native/configuration/dimensional-analysis Updated: 2025-09-18 ================================================================================ # Dimension Analysis ![dimension example](https://docs.statsig.com/images/statsig-warehouse-native/configuration/dimensional-analysis/550ac5d6-5e83-42aa-9db7-8618c200beef.png) Dimension analysis breaks down an experiment result by unit or action so you can see who or what drives a metric movement. Statsig groups results either by unit-level attributes (unit dimensions) or by values within a metric (metric dimensions), so you can filter or split any Pulse result. To view the Pulse result breakdowns for all categories within a metric, select the (+) sign next to the metric. You can also configure [Differential Impact Detection](https://docs.statsig.com/experiments/exploring-results/differential-impact-detection) to help Statsig automatically flag when different classes of users are responding differently to your experiments. ## Unit dimensions Unit dimensions are unit-level attributes from one of three sources: the user object you log to Statsig, your [assignment data](https://docs.statsig.com/statsig-warehouse-native/configuration/assignment-sources), or an [Entity Property](https://docs.statsig.com/statsig-warehouse-native/configuration/entity-properties). Examples of these attributes are operating system, country, region, or user segments. Using [explore queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries), you can filter to specific unit dimensions or group results by a dimension. For example, you can view results for users in the US, or view results for users on iOS grouped by their country. Statsig chooses the dimension based on the last available record at or before exposure. Statsig doesn't use information from after the unit is exposed to a given experiment in the experiment analysis. Using post-exposure data can lead to data leakage and imbalanced comparisons. ## Metric dimensions Metric dimensions break down a metric's results based on the values in columns from your [metric source](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources) for a given metric. You configure these breakdowns per-metric, after which Statsig calculates them for that metric across all pulse results. Unlike Unit Dimensions, Metric Dimensions aren't mutually exclusive. For example, with a unit dimension, a user can only be from one country for the purpose of pulse analysis. But with a metric dimension, a user on an e-commerce website could buy "clothes", "books", and "snacks" within a "total purchases" metric. That user contributes to each of those dimensions as well as the overall value. ## Default behavior By default, dimensional analysis: - only considers dimensions with at least 100 units in the experiment that participated (had a non-zero value). - chooses the top 10 dimensions by total value, and puts all others into an "OTHER" bucket. These defaults serve three purposes: - prevent extreme results - avoid cases where centrality assumptions fail due to low sample sizes on a specific dimension - limit excessive multiple comparisons on the tail end of dimensional breakdowns These defaults are configurable. Contact Statsig support to evaluate whether your use case warrants a change. ## Precomputed dimension loading timing For precomputed user dimensions that you configure and run on a schedule, Statsig processes dimension data asynchronously. The dimension data may take a few minutes to become available after the main experiment results load. You may temporarily see "No dimensions available for this time range" messages while Statsig processes the data, especially after the first reload of the day. This delay is expected. Wait a few minutes and refresh the page to see the dimensional breakdowns. > **Note:** > > This timing behavior only affects precomputed user dimensions. User-triggered dimensional analysis doesn't experience this delay. ================================================================================ # Assignment Sources URL: https://docs.statsig.com/statsig-warehouse-native/configuration/assignment-sources Updated: 2025-09-18 ================================================================================ # Assignment Sources Assignment Sources define the schema for your assignment data in Statsig. They serve as the input for determining which users are in an experiment and which treatment each user received. ## Creating an assignment source To create an assignment source, navigate to the data tab in Statsig and open the Assignment Sources pane. An Assignment Source is a SQL query and a mapping of the output columns to specific fields Statsig requires (user identifiers, a `timestamp`, an experiment identifier, and a group identifier). ![Assignment Source](https://docs.statsig.com/images/statsig-warehouse-native/configuration/assignment-sources/264100295-05d71c64-9b31-4531-b371-03b6cb692446.png) ## Scanning assignment sources Statsig scans assignment sources on-demand or on a schedule to find experiment data. These jobs run quickly and identify unique groups, the ID types present in the experiment, and the estimated number of users per group. After the scan is complete, you can view and create experiments from the assignment source. The assignment data also populates the Experiment creation flow. ![Assignment source scan results showing detected experiments](https://docs.statsig.com/images/statsig-warehouse-native/configuration/assignment-sources/87fac269-75bc-4a65-a660-339486605e24.png) ## Manage assignment sources In the Assignment Source tab, you can see your Assignment sources and the experiments that use them. ![Assignment Source Tab](https://docs.statsig.com/images/statsig-warehouse-native/configuration/assignment-sources/264100297-c41cd747-089c-4ccf-8b45-b70a1b4e264a.png) ## Example data For experiment assignment sources, Statsig requires the following information: which users received an exposure, when, and to which experiment: | Column Type | Description | Format/Rules | | --- | --- | --- | | timestamp | **Required** an identifier of when the experiment exposure occurred | Castable to Timestamp/Date | | unit identifier | **Required** at least one entity to which this metric belongs | Generally a user ID or similar | | experiment identifier | **Required** the experiment the exposure was for | Usually an experiment name | | group identifier | **Required** the experimental variant the user was assigned to | Usually a group name | | additional identifiers | _Optional_ Entity identifiers for reuse across identifier types | | | context columns | _Optional_ Fields you can use to group by and filter results in exploratory queries | | For example, you could pull from exposure event logging directly: | timestamp | user\_id | company\_id | experiment\_name | group\_name | country | | --- | --- | --- | --- | --- | --- | | 2023-10-10 00:01:01 | my\_user\_17503 | c\_22235455 | ranking\_v1\_vs\_v2 | v1 | US | | 2023-10-10 00:02:15 | my\_user\_18821 | c\_22235455 | ranking\_v1\_vs\_v2 | v2 | CA | | 2023-10-10 00:02:22 | my\_user\_18821 | c\_22235455 | search UI revamp | control | CA | ================================================================================ # Entity Properties URL: https://docs.statsig.com/statsig-warehouse-native/configuration/entity-properties Updated: 2025-09-18 ================================================================================ # Entity Properties Entity properties are categorical details about an entity, such as a user, that you can reuse across all experiments to filter or group results. You can provide detail that doesn't typically change, such as a user's home country. You can also provide a property that may change during an experiment, such as Subscriber Status: True/False. For dynamic properties, you provide a timestamp field that Statsig uses to identify the most recent value before the user's exposure. Using the pre-exposure value prevents imbalanced groups and biased results when an experimental treatment impacts the property, for example if the treatment increased the subscription rate. ![Entity Properties configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/configuration/entity-properties/7fcac725-54b4-46be-bb68-52fcc308fe5f.png) ![Entity Properties setup screen with timestamp configuration](https://docs.statsig.com/images/statsig-warehouse-native/configuration/entity-properties/6c151cf4-d343-4750-8bfd-a6d48afd6e10.png) ## Example data For property sources, Statsig only needs a user\_id and property fields. Property sources can define fixed properties (for example, a user's country of origin) or dynamic properties. For dynamic properties, provide a timestamp so Statsig can identify the most recent pre-exposure record. | Column Type | Description | Format/Rules | | --- | --- | --- | | timestamp | _Optional_ an identifier of when you define the property. Required for dynamic properties | Castable to Timestamp/Date | | unit identifier | **Required** At least one entity to which this metric belongs | Generally a user ID or similar | | property columns | **Required** Fields you can use to group by and filter results in exploratory queries | | For example, a static property source could be: | user\_id | company\_id | country | | --- | --- | --- | | my\_user\_17503 | c\_22235455 | US | | my\_user\_18821 | c\_22235455 | CA | You can use this source to filter and group results in any experiment that exposed either user\_id or company\_id. For a dynamic property, it might look like this: | user\_id | timestamp | company\_id | intent\_segment | spend\_segment | | --- | --- | --- | --- | --- | | my\_user\_17503 | 2023-10-10 | c\_22235455 | high\_intent | high | | my\_user\_17503 | 2023-10-11 | c\_22235455 | high\_intent | high | | my\_user\_17503 | 2023-10-12 | c\_22235455 | mid\_intent | high | | my\_user\_18821 | 2023-10-10 | c\_22235455 | low\_intent | low | | my\_user\_18821 | 2023-10-11 | c\_22235455 | low\_intent | mid | | my\_user\_18821 | 2023-10-12 | c\_22235455 | low\_intent | mid | The first user in this example has their intent\_segment property change on `2023-10-12`. Because Statsig uses the intent\_segment value before the user's exposure, this user may have different intent\_segment values across different experiments. ================================================================================ # Qualifying Events URL: https://docs.statsig.com/statsig-warehouse-native/configuration/qualifying-events Updated: 2025-09-18 ================================================================================ # Qualifying Events ## Using qualifying events Statsig uses qualifying events to simulate exposures for power analysis, and to filter exposures to users who triggered a specific event. Setting up a Qualifying Event is identical to setting up an Assignment Source, except they don't require experimental information. > **Info:** > > The qualifying event must occur after the exposure, as their respective timestamps indicate. You can use context columns to filter the qualifying event for power analysis. For example, you might have a Qualifying Event for page load and filter to different page identifiers for power analyses of experiments on different surfaces. ## Filter by qualifying events Statsig provides controls for using qualifying events to filter exposures in an experiment in cases of over-exposure. ![qualifying event filter](https://docs.statsig.com/images/whn/qe_filter.png) In the image above: - Forwarded SDK events from Statsig filter the exposures. This could also be a single-event source or any data source. - The configuration replaces the actual exposure timestamp with the first observed qualifying event, which makes metric timelines and cohort timelines more accurate. - The configuration counts only qualifying events from within an hour of an exposure event, which helps avoid issues with late-landing attribution. - A filter limits events to the `www.statsig.com` domain. Some customers prefer this flexibility, and many set up qualifying events as individual events to use in their analyses. You can often identify over-exposed experiments by observing uniformly low participation rate on all metrics. ## Power analysis Use qualifying events in power analysis to estimate your experimentation population based on how many users historically triggered your proposed trigger event. ![power analysis with qualifying event](https://docs.statsig.com/images/whn/pac_qe.png) You can filter these by event attributes, or by entity properties (e.g. users who triggered this event and are also in a segment or country). ## Example data | Column Type | Description | Format/Rules | | --- | --- | --- | | timestamp | **Required** an identifier of when the qualifying event occurred | Castable to Timestamp/Date | | unit identifier | **Required** At least one entity to which this metric belongs | Generally a user ID or similar | | additional identifiers | _Optional_ Entity identifiers for reuse across identifier types | | | context columns | _Optional_ Fields you can use to group by and filter results in exploratory queries | | For example, you could pull from page load event logging directly and save it as a qualifying event called `Page Load`: | timestamp | user\_id | company\_id | page\_route | | --- | --- | --- | --- | | 2023-10-10 00:01:01 | my\_user\_17503 | c\_22235455 | / | | 2023-10-10 00:02:15 | my\_user\_18821 | c\_22235455 | /search | | 2023-10-10 00:03:12 | my\_user\_22251 | c\_9928 | /profile | ================================================================================ # Tags & Teams URL: https://docs.statsig.com/statsig-warehouse-native/configuration/tags-and-teams Updated: 2025-09-18 ================================================================================ # Tags & Teams Statsig offers tools to enrich data sources, metrics, and entities with team ownership and tags. These provide a useful way to organize your data configuration, and also feed into advanced analytics tools like [meta-analysis](https://docs.statsig.com/statsig-warehouse-native/features/meta-analysis). ## Tags You can tag Experiments, Metrics, and Sources for easy discovery, search, and context. You can bulk-add metrics that share a tag to scorecard or guardrail metric sets. Statsig also provides a Core tag, which identifies company key metrics to use as guardrail metrics across experiments. Go to the [tags page](https://docs.statsig.com/metrics/create-metric-tags) for more information. ## Teams For larger organizations, the Teams feature adds an organizational and permissions layer on top of a Project. You configure teams at the Project (not Organization) level, and all Project Admins can edit them by default. After you configure teams and assign a user to a team, any configuration (gates, experiments, metrics, and so on) they create associates with their team and inherits that team's settings. Users who belong to multiple teams can choose which team to associate their configuration with at creation time. This is useful for managing ownership and review practices. Go to [Teams](https://docs.statsig.com/access-management/teams) to learn more. ================================================================================ # Roles URL: https://docs.statsig.com/statsig-warehouse-native/features/roles-and-access Updated: 2025-09-18 ================================================================================ # Roles Statsig has custom, configurable RBAC (role-based access control) across the console. RBAC is especially useful for Warehouse Native customers, because you can control who can update which metrics and who can view raw data. ================================================================================ # Verified Metrics URL: https://docs.statsig.com/metrics/verified ================================================================================ # Verified Metrics Verified metrics identify metrics that your company curates and considers trustworthy. When users set up experiments and search for metrics, a verified icon appears next to verified metrics. > **Info:** > > This is an Enterprise feature. Contact the support team, your sales contact, or the [Slack community](https://statsig.com/slack) to enable the feature. ![Verified metrics interface showing verified icon](https://docs.statsig.com/images/metrics/verified-metrics-interface.png) To verify a metric, use the overflow menu on the metric. ![Metric overflow menu with verify option](https://docs.statsig.com/images/metrics/metric-overflow-verify-option.png) Admins can control which roles can verify metrics. ![Admin role permissions for metric verification](https://docs.statsig.com/images/metrics/verified/437645df-dd63-4fd4-841d-1517126e1531.png) ================================================================================ # Macros URL: https://docs.statsig.com/statsig-warehouse-native/configuration/query-tools Updated: 2025-09-18 ================================================================================ # Macros In **Metric** and **Assignment sources**, you can use Statsig Macros to directly inject a DATE() type that is relative to the experiment period Statsig loads. - `{statsig_start_date}` - `{statsig_end_date}` For example, in an incremental reload from `2023-09-01` to `2023-09-03`, this query: ```sql SELECT user_id, event, ts, dt FROM log_table WHERE dt BETWEEN `{statsig_start_date}` AND `{statsig_end_date}` ``` resolves to ```sql SELECT user_id, event, ts, dt FROM log_table WHERE dt BETWEEN DATE('2023-09-01') AND DATE('2023-09-03') ``` Macros are useful here because you can inject filters into queries with joins or CTEs and confirm that Statsig prunes the initial scan. Statsig adjusts the range as necessary in some cases. For example, in entity properties, Statsig adds a pre-experiment buffer to allow for late-landing property data, then selects the most recent value as of each unit's exposure. For CUPED, Statsig adjusts the range to include the pre-experiment window for CUPED calculations. ## Timezone note All timestamps in Warehouse Native from Statsig are in UTC, and Statsig assumes timestamps in the warehouse are timezone-less/UTC as well. ## Advanced macros - `{statsig_start_date_int}` - `{statsig_end_date_int}` Int versions of the above for use with number based partitioning - e.g. '2025-03-01' => 20250301 - `{statsig_experiment_start_timestamp}` Only available for metric sources and entity property sources; this resolves to the start timestamp of the experiment. In non-experiment contexts, it resolves to `TIMESTAMP('1970-01-01')`. This is useful for generating entity properties such as "30d revenue before the experiment started". ================================================================================ # Metric Family URL: https://docs.statsig.com/metrics/metric-family ================================================================================ # Metric Family Metric Families let you create metric variants as child metrics of a parent metric. When you update a parent metric, the changes cascade automatically to its child metrics, keeping all related metric definitions consistent. Use a Metric Family to manage a large catalog of near-identical metric variants without editing each one manually. > **Info:** > > Child metrics of **SUM** and **COUNT** parent metrics support these modifiable configs: > > - Add metric source filter > - Outlier Management > - Variance Reduction > - Cohorts and Delayed Data ## Create a child metric To create a child metric, select the **Create Child Metric** option in the dropdown menu in the top right corner of a metric. ![Creating a child metric](https://docs.statsig.com/images/metrics/metric-family/create-child.png) You can track the child metrics for a given parent metric using the metric family icon in the top right. ![Tracking tree of child metrics](https://docs.statsig.com/images/metrics/metric-family/tree-child.png) ## Deleting and archiving When you delete or archive a parent metric, Statsig deletes or archives all of its child metrics as well. When you re-enable the parent, Statsig automatically restores those child metrics. You can't restore child metrics disabled through the parent individually; you can only re-enable them by restoring the parent metric. ![Metric deletion confirmation message](https://docs.statsig.com/images/metrics/metric-family/delete.png) If you delete or archive a child metric independently of its parent, you can restore the child metric on its own. The restored child metric returns as a standalone metric without its original parent-child relationship. ## In experiments When you select a Parent Metric in Experiment setup, Statsig adds all of its child metrics as well. You can remove any metrics you don’t need in the experiment. ![Adding parent metric to an experiment will add all child metrics with it](https://docs.statsig.com/images/metrics/metric-family/in-experiment.png) ================================================================================ # WHN Console API URL: https://docs.statsig.com/statsig-warehouse-native/configuration/console-api Updated: 2025-09-18 ================================================================================ # WHN Console API Statsig's console API allows you to programmatically perform CRUD operations on all configuration objects. Use the API for bulk edits, or to sync your definitions into Statsig as a triggered or scheduled job. You can also use this API to trigger pulse results and manage workflows in Statsig. [Go to the full Console API Docs.](https://docs.statsig.com/console-api/introduction) ================================================================================ # Semantic Layer Sync URL: https://docs.statsig.com/statsig-warehouse-native/configuration/semantic-layer-sync Updated: 2025-09-18 ================================================================================ # Semantic Layer Sync If you have centrally defined metrics, Statsig can sync your data sources and metrics as part of your data version management workflow. Using Statsig's [Console API](https://docs.statsig.com/console-api/introduction), you can automatically sync changes to matching definitions in Statsig, and optionally make the metrics read-only in the Statsig console. A demonstration [GitHub repository](https://github.com/statsig-io/semantic_layer) uses [a script](https://github.com/statsig-io/semantic_layer/blob/main/.github/scripts/statsig_sync.py) that [a GitHub Action](https://github.com/statsig-io/semantic_layer/blob/main/.github/workflows/statsig_sync.yml) executes. This setup automatically synchronizes changes to .yml files in the /metrics or /metric\_sources directories in the repo. After you create or update these files, the script updates existing metrics or metric sources in Statsig, or creates new ones accordingly. To use this example template, follow these steps: 1. Fork [this repository](https://github.com/statsig-io/semantic_layer) to get started. 2. In your forked repository, add your Statsig Console API Key to GitHub Secrets. 3. Update the metric definitions to match your data needs. 4. Validate the automation by modifying relevant files and observing the triggered GitHub Action. ## Detailed guide ### Forking the repository 1. **Fork this repository** to create a copy in your GitHub account. ![Untitled](https://docs.statsig.com/images/statsig-warehouse-native/configuration/semantic-layer-sync/79652104-6e13-467a-b4ef-dbbac83e15c9.png) ### Adding the Statsig Console API Key 2. Navigate to `Settings > Secrets and variables > Actions` in your repository settings. Create a new secret named `STATSIG_API_KEY` with your Statsig Console API key as its value. This key authenticates the synchronization process with the Statsig Console API. ![Untitled](https://docs.statsig.com/images/statsig-warehouse-native/configuration/semantic-layer-sync/0a627a98-3772-4c36-89d1-7587e3950e84.png) ### Customizing metric definitions 3. Metric definitions are in the `./metrics` directory, and metric source definitions are in the `./metric_sources/` directory. To customize: - Use the Statsig Console API to fetch an existing **metric\_source** or **metric** using GET requests for [metric sources](https://docs.statsig.com/console-api/introduction#post-/metrics/metric_source/-name-) and [metrics](https://docs.statsig.com/console-api/introduction#get-/metrics/-metric_id-). - Remove the provided example metrics and metric sources, and replace them with your definitions in `./metric_sources/*.yml` and `./metrics/*.yml`. For readability, the examples use `metric.metricDefinition[]` instead of `metric.warehouseNative[]`. You can view this change [in the sync script](https://github.com/statsig-io/semantic_layer/blob/1611a68703caf18d7fa32088ff06d568d8b3b03a/.github/scripts/statsig_sync.py#L38). Adjust the mapping or revert to `metric.warehouseNative[]` in your definitions as needed. ### Verifying automation 4. To test, edit a metric or metric source description in your repository. This triggers the GitHub Action, visible under the `Actions` tab. The process then creates or updates your metrics and metric sources in Statsig based on the repository's semantic definitions. ![Untitled](https://docs.statsig.com/images/statsig-warehouse-native/configuration/semantic-layer-sync/2dcf8961-3591-4021-88fe-984994177f35.png) ![Untitled](https://docs.statsig.com/images/statsig-warehouse-native/configuration/semantic-layer-sync/04a084d6-ef6c-4b3f-aee9-41663ed47a60.png) ![Untitled](https://docs.statsig.com/images/statsig-warehouse-native/configuration/semantic-layer-sync/4442dd9d-313f-4b16-a978-59513e4e8469.png) This example is a basic template. Test and extend it to meet production standards. Share feedback or improvements with the Statsig support team, your sales contact, or in the [Slack community](https://statsig.com/slack). ================================================================================ # Understanding Experiments URL: https://docs.statsig.com/statsig-warehouse-native/features/understanding-experiments Updated: 2025-09-18 ================================================================================ # Understanding Experiments Statsig Warehouse Native structures an experiment around date ranges and exposure timing, then turns each unit's exposures and metric data into scorecard results. Statsig abstracts much of the statistical complexity of experiment analysis, which commonly leads to questions like the following: - What do different date ranges mean? - What metric data is included in the calculation? This page gives an overview of the basic settings in Statsig and what they mean for the analysis that runs. For more advanced settings, refer to [experiment configuration](./experiment-options) ## Date ranges The date range of an experiment controls the filters used when querying both exposure and metric data. For example, an experiment with a start date of `2025-02-01` and an end date of `2025-02-14` queries both assignment data and metric data between those two dates. There are a few exceptions: - Metric Bake Windows or Cohort Windows with `wait for...` enabled: Statsig excludes cohorts that haven't been in the experiment for the duration of their cohort/bake window. Statsig excludes these cohorts from both the exposure count and the metric data for the metric in question. - If `allow cohort metrics to bake after experiment end` is enabled: Statsig extends the end date of analysis artificially (only for cohort metrics) to maximize data collection. This extension applies to experiments with a one-time intervention where you expect the experiment effect to persist after you turn off the treatment. ### Exposure timing Statsig includes a given experimental unit’s (for example, a user’s) data only after that unit triggers the experiment. For example, if you're testing a new notification, Statsig shouldn't include metric data from before a given user sees the notification in the experimental analysis. There is an exception: if a metric source uses a date column as its timestamp, Statsig doesn't include metric data from the day of exposure in the calculation. This happens because a timestamp cast from a date defaults to the first second of that date (00:00:00), which falls before the exposure time. To address this, the metric source has a setting called `Treat timestamp as date`: - If checked: Statsig includes day-0 data by converting the join condition to use the cast date (ignoring time). - If unchecked: Statsig excludes day-0 data from the join between exposure and metric for the reason described above. Statsig recommends including day-0 data (checking `measure timestamp as day`) if you've preprocessed the data at a daily grain. ### Explore query dates Explore queries can filter metric data or assignment data independently. The default filtering option is metric data. This filtering allows you to exclude certain dates with buggy or non-representative data, or to scope an analysis to recent periods. For example, you might scope to recent periods if your hypothesis is that the treatment effect takes a long time to develop. Under the advanced tab, it's also possible to: - filter to exposures in a date range (or outside of) - filter to exposures within a certain cohort (e.g. X-Y days since exposure) ### Selecting dates Regardless of [turbo mode](https://docs.statsig.com/statsig-warehouse-native/features/turbo) when using incremental reloads, you can use the date picker next to pulse to view pulse "as of" a certain date. This is useful for reviewing historical discussion of an experiment or understanding how results have evolved over time. You can also view this data through the time series views in Statsig. > **Note:** > > Don't use this feature to cherry-pick dates with favorable results. ## How experiment calculations work For every experiment analysis, the basic flow is: - Identifying when units first saw or enrolled into the experiment. - Identifying what those units did (metric data: events or other rollups) after seeing the experimental variant Statsig assigned them to, up until the end of the experiment. This results in a tagged dataset where Statsig associates metric data with a group. - Aggregating that metric data over the experiment duration. Go to the [metrics documentation](https://docs.statsig.com/statsig-warehouse-native/configuration/metrics) for descriptions and SQL snippets describing this step. - Calculating group-level statistics for use in the final scorecard analysis. At a high level, the analysis requires the observed totals/means per group, and the variance, which Statsig uses to understand how meaningful that difference is. This measure of meaningfulness is typically statistical significance in frequentist analysis, or probability of best in Bayesian analysis. - Statsig normalizes means per unit. For basic aggregations this imputes 0s: the calculation is the total value over the count of units exposed. For ratios and means, Statsig computes the means as the sum of the numerator over the sum of the denominator. ================================================================================ # Configuring Experiments URL: https://docs.statsig.com/statsig-warehouse-native/features/experiment-options Updated: 2025-09-18 ================================================================================ # Configuring Experiments ## Configuration Advanced experiment settings in Statsig Warehouse Native tune how an experiment measures impact, so you can maximize statistical power and measure exactly what you intend. Default options still produce trustworthy statistical analysis, and each setting has tradeoffs to weigh before you change it. ## Experiment settings ## Basic settings ### Hypothesis Statsig requires a hypothesis to run experiments. Hypotheses should specify what an experiment aims to accomplish and how you measure that. ### Primary and secondary metrics These are the metrics used as the evaluation criteria for your experiment. Generally, Statsig recommends a small number of primary metrics as your overall evaluation criteria, and putting guardrails and exploratory metrics into Secondary. Statsig provides project-level configuration of the maximum number of primary/secondary metrics. The appropriate number varies by company and industry, as well as the complexity of the space you're measuring. ### Experiment duration In experiment setup there are fields for _Experiment Measured In_ and _Target_. These configure how long your experiment runs, influencing sequential testing as well as notifications/timeline alerts. > **Note:** > > Statsig's [power analysis tools](https://docs.statsig.com/statsig-warehouse-native/features/power-analysis) are the best way to determine the target duration. You can attach a power analysis to an experiment to add context on the duration. ### Experiment configuration ### Assignment source and groups For analysis-only experiments, Statsig pre-fills this section from the observed data in the data warehouse. You can configure images and descriptions. Statsig infers group sizes, but you should review and correct them if they don't match the intended traffic split. To update these settings, reset the experiment from the decision menu after it has started. ### Groups and parameters For end-to-end experiments (experiments using Statsig for both assignment and analysis), this section is where you configure targeting, layers, and the groups and associated parameters. Statsig automatically associates exposures generated from the setup with this experiment for analysis. For end-to-end experiments that use Statsig exposure forwarding, the daily export excludes groups at 0% or 100% traffic share by default. This is each group's share, not the experiment's overall allocation. If you need these experiment exposures, contact Statsig Support. For forwarding requirements, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). ### Advanced settings Statsig provides many advanced settings for customizing analysis. These can have complex interactions with data. ### Pre-computed user dimensions Configure dimensions as default breakdowns in pulse. For example, specify a user dimension such as country here to make it available in the scorecard results with daily loads. This lets you skip scheduled explore queries for this dimension, and the results appear inline in the scorecard. ### Stratified sampling Stratified Sampling lets you balance experiments across behavior or segments. Statsig tests random salts and picks the one that best balances user attributions. You can partially achieve this during analysis using [CURE](https://docs.statsig.com/statsig-warehouse-native/cure/introduction). Refer to [Stratified Sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling) for more details. ### ID type and secondary ID type You configure the ID type, which is the unit of randomization for an experiment, when setting up the experiment. This is a critical field that represents the kind of entity you're experimenting on. For example, if splitting traffic randomly per user, this should be `User ID`. If splitting traffic by company, this should be `Company ID`. Secondary ID types associate metrics from a different ID with the unit of randomization. For example, consider an experiment on a logged-out cookie ID. Specifying `UserID` as a secondary ID allows analysis of `UserID` metrics like revenue while keeping `Cookie ID`s as the unit of analysis (for example, the denominator in means). This lets you understand the downstream impact of experiments without introducing survivorship bias or other bias to the analysis. This mapping can come directly from the assignment source. If multiple exposures exist for a given unit, and at least one has both ID types, Statsig identifies that these two IDs map to each other. Alternatively, you can specify mappings in an Entity Property Source: provide a mapping table of `ID1` to `ID2` and Statsig connects the data during analysis. You can configure secondary ID mapping as an enforced 1:1 mapping or as first-touch attribution. Refer to the [ID Resolution documentation](https://docs.statsig.com/statsig-warehouse-native/features/id-resolution) for more details. ### Allocation and cohorting **Configure Allocation Duration** If using a persistent assignment SDK ([docs](https://docs.statsig.com/client/concepts/persistent_assignment)), this setting controls when to stop enrolling users into the experiment. You can also use this setting without a persistent assignment SDK to filter out users exposed after the duration period. This is useful for enforcing even cohorts across a user base. For example, suppose a metric takes 7 days to mature and stopping the experiment halts its effect. Set the allocation duration to 14 days and run the experiment for 21 days. This analyzes the first 14 days of exposed units while capturing all 7 days of the last cohort's metric behavior. **Configure Analysis Period** This setting controls the dates from which Statsig collects metric data. It's useful for truncating the analysis window while continuing to run an experiment. **Allow cohort metrics to mature after experiment end** This setting allows cohort or baked metrics that take time to mature to continue collecting data after the end of an experiment. Statsig recommends this only if an experiment is a one-time intervention. For example, consider a 14-day experiment on new users that modifies a signup page. Removing the changes to the signup page doesn't impact users who already saw it. To maximize data for the "first-week revenue" metric, enable this setting. Data then continues to collect after the experiment ends on day 14: for users enrolled on day 14, until day 21; for users enrolled on day 10, until day 17. ### CURE covariates This section lets you configure covariates for CURE. Configure strong defaults in the project settings, and use this section to add relevant/domain-specific covariates. Refer to the [CURE](https://docs.statsig.com/statsig-warehouse-native/cure/introduction) documentation for more details. ### Analysis settings **Analytics type** Whether to use Frequentist or Bayesian analysis. You can't change this once an experiment starts, to avoid cherry-picking methodology. **Apply Sequential Testing \[Frequentist Only\]** Controls whether Statsig applies [sequential testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing). Statsig recommends this setting to avoid false positives from peeking. **Bonferroni/Benjamini-Hochberg \[Frequentist Only\]** Configures multiple-comparisons corrections, either controlling the false positive rate or false discovery rate. Refer to the more detailed documentation for [Bonferroni](https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/bonferroni-correction) and [Benjamini-Hochberg](https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/benjamini-hochberg-procedure). **Default Confidence Interval/Chance to Beat Threshold** The confidence level used for this experiment. The default is 95%, which is the recommended industry standard. Depending on the risk profile of the experiment, a stricter or less strict setting may be appropriate. **Use Informative Priors \[Bayesian Only\]** For bayesian experiments, whether to use informed priors in analysis, and the configuration for them. **Turbo Mode** Whether to use [Turbo Mode](https://docs.statsig.com/statsig-warehouse-native/features/turbo) to run experiment reloads more quickly. **Filter Exposures by Qualifying Event** This setting allows filtering exposures to experimental units that did (or did not) trigger a secondary event beyond exposure. This is useful for analysis-only experiments on web experimentation platforms that over-expose heavily. For end-to-end experiments, use Statsig to expose only at the point of intervention. This setting has a few inputs: - A qualifying event, which Statsig joins to exposures to determine if users triggered an event - **Exclude Matching Units**: if you toggle it, Statsig drops units that triggered this event from the analysis. If you leave it unchecked, Statsig filters the analysis to units that triggered the event. - **Use qualifying event timestamp for first exposures**: if you check it, Statsig replaces units' exposure timestamp with the qualifying event's timestamp. This is useful for small cohort windows, for example, measuring whether something happened within 10 minutes of the intervention. If the intervention occurred several minutes after the original exposure event, using the actual time the user saw the intervention can be helpful. - **Filter events by time window**: only consider qualifying events for the inclusion/exclusion filters that occurred within a certain time from the exposure. This is useful if a user may return and re-trigger the qualifying event when it's no longer relevant to the exposure. **Filter Assignment Source** This setting controls additional filters applied to the exposure data for this experiment. This can be useful to filter out bad dates with data known to be biased or non-representative, or to filter to a specific subset of interest for the scorecard results. **Default Date Filter** Statsig calculates results across multiple rollups, including Cumulative, 7 days, and 1 day. Cumulative is almost always the correct choice for this setting because it maximizes statistical power. You can select other views in the scorecard. ## Explore (custom) query settings Explore queries enable drilldown, filtering, grouping, and more advanced ways to cut metric data by user and metric properties. They provide a way to analyze experiment results in depth. Explore queries run with the same statistics as the scorecard; with no filters or other settings applied, results match the scorecard results. ## Metrics Pick the metrics to run the explore or drilldown analysis on. This can include tags and local metrics. ## Group By This setting is the primary tool for explore and custom queries. It allows drilldowns into user segments to understand differentiated performance. You can combine it with [differential impact detection](https://docs.statsig.com/experiments/exploring-results/differential-impact-detection) to analyze experiment results beyond topline averages. By default, Statsig shows only the top 10 dimension levels with over 100 units per segment in results. Statsig groups the rest into an OTHER category. This prevents inflated false positive rates and keeps statistical analysis rigorous. Contact the Statsig team in Slack if you need this limit adjusted. ## Filter Use filters to include or exclude certain cohorts of units in an explore analysis by specifying the property and a filter set. ## Time range for metric data This setting filters metric data to a specific date period, for example the three days from 2024-04-10 to 2024-04-12. This is useful for investigating data anomalies, analyzing a recent cohort when results have changed significantly, or running drill-down analyses. ## Filter by exposure date In some cases it's useful to filter to units that entered the experiment on a specific date, or to exclude them (for example, units exposed on a holiday may behave atypically). You can specify filters based on user exposure date. By switching the mode to Days Since First Exposure, you can also drill down into each cohort's behavior during a specific window after exposure. This is a useful way to understand behaviors observed in the days-since-first-exposure timeline view. ## Scheduling After running a query, you can schedule it. Scheduled queries run daily after any scheduled pulse load to update results. You can also add scheduled queries to the experiment Summary page as part of the experiment writeup and downloadable summary. ## Interaction effect detection Explore queries can trigger [interaction effect detection](https://docs.statsig.com/experiments/exploring-results/interaction-detection) analyses to determine whether two experiments are interacting in a synergistic or harmful way. ================================================================================ # Configuring Experiments URL: https://docs.statsig.com/statsig-warehouse-native/features/configure-an-experiment Updated: 2025-09-18 ================================================================================ # Configuring Experiments A Warehouse Native experiment runs in one of two modes: connect to existing assignment data in your warehouse, or configure the experiment in Statsig, generate exposures with the Statsig SDK, and analyze them in your warehouse. For most A/B/n experiments, the default settings produce a standard, powerful analysis. ## Creating an experiment To create an experiment, go to the experiments tab in your console and click the create button. There are two types of experiments in Statsig Warehouse Native: - Analyze: these are for 3rd-party or in-house exposure sources. - Assign & Analyze: these are Statsig-configured experiments. You can set up all of the configuration here, implement it through Statsig SDKs, and track results. ![Experiment type selection interface](https://docs.statsig.com/images/statsig-warehouse-native/features/configure-an-experiment/30954be6-7c2e-48f4-8072-f196349adbc3.png) Next, give the experiment a name, specify your hypothesis, and select the experiment from your exposure sources. Sync sources if your exposure isn't available in the dropdown. Specify the control group and the ID type the experiment uses. ![Configure Experiment](https://docs.statsig.com/images/statsig-warehouse-native/features/configure-an-experiment/7984bdd3-e2bf-4322-8230-18e3222077e9.png) ## Choose metrics On the experiment setup page, refine your hypothesis and add the Primary and Secondary metrics for your experiment. - Primary metrics: a short list (1-3) of metrics that define your overall evaluation criteria. Typically one target metric and one first-mile metric, such as revenue and checkout clicks. - Secondary metrics: guardrail and explanatory metrics. These are observational in nature and are less conclusive. Applying Bonferroni corrections is one way to formalize this approach, though it can be overly conservative. ![Choose Metrics](https://docs.statsig.com/images/statsig-warehouse-native/features/configure-an-experiment/264101219-396f00f6-fbdc-4944-94c0-62354eaa2980.png) ## Choose groups Statsig infers the groups and group splits in your experiment. Check and correct the splits to ensure SRM checks work as intended. You can also rename groups or delete irrelevant groups. ![Choose Groups](https://docs.statsig.com/images/statsig-warehouse-native/features/configure-an-experiment/33de7e4f-a0f8-4fcd-bde0-850a57055b71.png) ## Advanced settings Statsig has many configurable settings for experiments. You can set defaults at the org level. Available settings include: - Frequentist vs. Bayesian analysis - Target duration of the experiment - Whether to apply [Sequential Testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) adjustments - Allocation Duration - Stop enrolling new users into the experiment after X days > **Note:** > > You need to set up [Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment) to retain already-enrolled users to stay in the same group - Cohort Duration - Specify a timeline for collecting metric data - Include only units with a completed duration, so Statsig doesn't include units with incomplete data in Pulse - Whether to allow cohort metrics to mature after experiment end > **Note:** > > After you configure this value, it overwrites the `only include units with a completed duration` setting above. - [ID stitching](https://docs.statsig.com/statsig-warehouse-native/features/id-resolution) - Whether and how to apply [Bonferroni Correction](https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction) - Default Confidence Intervals - Default rollup windows for result readouts (cumulative, 1, 7, 14, or 28 days from the analysis date) - Turbo Mode - Skip time series calculations to reduce cost and runtime when you only need the overall effect - Filter exposures by qualifying event - Only applicable in Analyze-only experiments - Filter assignment source - Add optional filters on the experiment's assignment source. By default, Statsig filters the assignment source to the experiment and groups you're analyzing. Use this setting to exclude known bad actors from the primary scorecard or to analyze a sub-population in the main scorecard. ## Testing in a lower environment After you launch experiments, you can't edit the groups without restarting the experiment, because Statsig has already allocated users to each group. Test each experiment in lower environments before starting. Click the **Test** button on the experiment setup page, then select **Enable for Environments**. These environments should match your [SDK environment setup](https://docs.statsig.com/guides/using-environments/#configuring-environments). Testing in a lower environment and using [overrides](https://docs.statsig.com/experiments/setup/overrides) lets you manually set your experiment group to test each variant. ![Experiment test button interface](https://docs.statsig.com/images/experiments/experiment_test_button.png) When you enable an experiment for lower environments, Warehouse Native customers can check exposure logs to troubleshoot exposures. Lower environments don't provide experiment results or cumulative exposures. ## Start the experiment After completing setup, click **Save and Analyze** to start the experiment. Statsig prompts you to finalize the dates, experiment status, and optionally configure a schedule to reload experiment results. ![Schedule](https://docs.statsig.com/images/statsig-warehouse-native/features/configure-an-experiment/264101192-1626481b-3c45-4622-b7c8-1e9638436a8d.png) When you click **Load Data**, a Pulse analysis starts and Statsig takes you to the results page. ## Data freshness For a Statsig-configured experiment using the Statsig SDKs to generate exposures, Statsig batches, deduplicates, and writes exposures to your warehouse once a day by default. Early in an experiment, that daily cadence can be too slow to catch crashes or significant bugs. So when you load Pulse, Statsig first performs a just-in-time update of exposures in your warehouse. For the first 24 hours after the experiment starts, that update draws from the most recently logged exposures, which lets you see Pulse results as fresh as approximately 15 minutes, assuming events and metrics arrive at the same speed. After 24 hours the just-in-time update still runs, but draws from batched data, so results are less current. The just-in-time update applies while an experiment has fewer than 1 million exposures. Above that threshold, Statsig writes exposures on the daily cadence only. Statsig exports custom event logs from the Statsig SDKs to your warehouse hourly, plus a short processing delay. When you load Pulse, metrics derived from those events can be as fresh as approximately 1 hour. > **Note:** > > Statsig only writes exposure information to your warehouse that it uses for experiment analysis. Statsig doesn't write exposures from pre-production environments or overrides, because it doesn't use them in analysis. ================================================================================ # Types of Experiments URL: https://docs.statsig.com/statsig-warehouse-native/features/types-of-experiments Updated: 2025-09-18 ================================================================================ # Types of Experiments ## Analysis only ### A/B/n Analysis-only A/B/n tests run analysis on top of assignment and metric data from your warehouse. In these experiments, Statsig operates as a statistics engine to help make analyses more reproducible. ## Assign and analyze ### A/B/n The most common Assign-and-Analyze experiments are A/B/n tests that integrate warehouse data with Statsig's live SDK. In these experiments, Statsig operates as an assignment tool, a real-time diagnostics tool, and as a statistics engine. Assignment related features supported include: > #### [Stratified Sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling) > > Dividing your population into homogeneous groups (based on a metric or classification). > #### Configurable Allocation Duration > > You can enroll users for a subset of an experiment's duration. If you're experimenting on a one-time experience (such as signup flows), you need no additional configuration. If the experience isn't one-time (you must keep assigning enrolled users), configure your SDKs to use Persistent Assignment. You provide a store to save user enrollment states, and the SDK manages this state. Go to Persistent Assignment for [Client](https://docs.statsig.com/client/concepts/persistent_assignment) and [Server](https://docs.statsig.com/server/concepts/persistent_assignment) SDKs. ### Switchback experiments Statsig offers [Switchback V2](https://docs.statsig.com/experiments/types/switchback-v2) experiments for systems with meaningful network effects, where changing an experience for one group affects other groups. For example, in a ride-service app, changing prices for some users changes driver demand for all users. Instead of splitting users, a switchback experiment alternates clusters of users between control and treatment on a fixed schedule, then compares time windows. You configure clusters, window size, and burn-in and burn-out periods in Statsig's console. Statsig runs a regression analysis that accounts for factors such as time of day and cluster attributes to estimate lift and confidence intervals. ### Geo testing Statsig offers [Geotesting](https://docs.statsig.com/statsig-warehouse-native/geotests/introduction) to support marketing and product causal inference techniques where you can't run a traditional A/B test. Geotesting treats geographic units (such as postal codes and DMAs) as the unit of analysis. This approach enables new experimental methodologies like rigorous testing of paid marketing or search on platforms like Google and Facebook Ads. Geotesting uses Synthetic Control methodologies built on GeoLift, an open-source package from Meta. All existing metrics and metric sources are available, with the addition of geographic labels. ### MABs - [Autotune](https://docs.statsig.com/statsig-warehouse-native/features/autotune) is Statsig's multi-armed bandit solution. It balances explore and exploit to deliver the optimal global treatment to users, making it useful for evaluating many options and dynamically adjusting traffic to avoid over-delivering underperforming variants. - Statsig also offers a [Contextual Multi-Armed Bandit](https://docs.statsig.com/statsig-warehouse-native/features/contextual-bandit). This bandit extends the multi-armed bandit by personalizing the experience served to users based on "context" (user or event attributes provided to the Statsig SDK). The Contextual Multi-Armed Bandit balances explore and exploit by optimizing for potential upside in its predictions. You invoke both MAB types through Statsig's `getExperiment` call. For the CMAB approach, provide relevant attributes to the user object. Contact the Statsig support team, your sales contact, or the [Slack community](https://statsig.com/slack) for assistance with Contextual Multi-Armed Bandits. ================================================================================ # Switchback V2 URL: https://docs.statsig.com/experiments/types/switchback-v2 ================================================================================ # Switchback V2 A switchback experiment alternates an entire cluster of users between control and treatment on a fixed schedule, then compares time windows instead of user groups. Use it when treating one user changes what other users experience, such as pricing in a marketplace or a shared ranking model. For example, on a rideshare platform, offering lower prices to a treatment group can increase demand for cars and indirectly affect control riders; a switchback experiment measures the impact over time instead of splitting users. If user experiences are independent, run a standard [A/B test](https://docs.statsig.com/guides/abn-tests) instead. Switchback V2 is available in Statsig Warehouse Native. Statsig Cloud projects run [switchback tests](https://docs.statsig.com/experiments/types/switchback-tests). ## How switchback experiments work 1. **Define clusters and their schedule**: A cluster is a group of users that switch between experiences on the same cadence. For example, all users in New York and Chicago follow the same hourly schedule. 2. **Aggregate data by time buckets**: A bucket is a single window of time during which the user experience stays constant. The analysis treats each bucket as one data point. 3. **Run regression analysis**: Statistical models account for factors such as time of day, day of week, or cluster attributes when estimating the difference between treatment and control. 4. **Compare results**: The final output resembles a traditional A/B test, including metrics such as estimated lift and confidence intervals. The following schedule for the New York and Chicago cluster produces four buckets: two for control and two for treatment. | Bucket | Window | Group | | --- | --- | --- | | 1 | 9:00 to 10:00 AM | Control | | 2 | 10:00 to 11:00 AM | Treatment | | 3 | 11:00 AM to 12:00 PM | Control | | 4 | 12:00 to 1:00 PM | Treatment | ## Set up a switchback experiment Defining the hypothesis, metrics, groups, targeting, and parameters follows the same workflow as a traditional A/B test. A switchback experiment adds three configurations: clusters, scheduling, and analysis configuration. ## Define clusters Clusters are groups of users who follow the same experience cadence. In a traditional A/B test, the selected ID type is both the randomization unit and the unit at which Statsig calculates metrics. In a switchback experiment, the ID type defines only the unit for metric calculation, and clusters determine which experience a user receives over time. Statsig provides three ways to define a cluster. | Method | Description | Inputs | | --- | --- | --- | | Single | One cluster in which all users eligible for the experiment follow the same cadence. | **Start With**: The experience (control or treatment) that starts the switchback. | | Auto | Two clusters. Statsig automatically assigns users to each cluster based on the specified inputs. | **Cluster ID Type**: A custom ID from the exposure user object that Statsig uses to split users into clusters. For example, if `server_id` is present on the user object, Statsig randomly assigns `server_id` values to each cluster and groups users by their `server_id`. | | Manual | Two clusters. You assign users to each cluster manually. | **Cluster Field**: A field from the exposure user object that Statsig uses to assign users to clusters. For example, if you select Country as the cluster field, you can assign specific countries to either Cluster 1 or Cluster 2. Statsig then places users into clusters based on the value of that field. | You can use the Cluster ID Type (Auto) and Cluster Field (Manual) fields as covariates in the regression analysis, and to break down metric data in the results section. ## Define the schedule After you configure the clusters, define the schedule for experiences within each cluster. ![Switchback schedule configuration with window size, start date, and target duration](https://docs.statsig.com/images/Screenshot2026-02-25at9.45.50AM.png) ### Schedule fields | Field | Description | | --- | --- | | Window Size / Unit | The length of each window during which a user's experience stays constant. | | Experiment Start Date / Time / Timezone | The date and time when the switchback experiment begins. All clusters start at the same time. The start date and time must be in the future when you start the experiment. | | Target Duration | The intended length of the experiment. By default, the experiment doesn't stop when it reaches this duration, and users continue to receive the switched experiences on the configured schedule. If you turn on **Stop Experiment at target duration**, the experiment stops automatically at the end of the duration, and Statsig serves users the default experiment value configured in code. | ## Define analysis configuration You can configure how Statsig handles exposures and metrics during the transition periods between switchback windows. For example, a rideshare marketplace might switch from control to treatment at 9 AM. The system can still show lingering effects from the control period, such as drivers on active trips or riders still in the queue from earlier periods. In these cases, you can exclude exposures and metric data recorded shortly after the switch. Configure burn-in and burn-out periods in the _Analysis Configuration_ section to exclude these transition exposures. ![Analysis configuration section with burn-in and burn-out period fields](https://docs.statsig.com/images/Screenshot2026-02-25at2.26.44PM.png) ### Analysis configuration fields | Field | Description | | --- | --- | | Burn-in Period | The amount of time at the beginning of each window that Statsig excludes from analysis. | | Burn-out Period | The amount of time at the end of each window that Statsig excludes from analysis. | | Metric Calculation | How Statsig attributes metric events to an exposure and aggregates metrics within each switchback window. Choose one of the metric calculation options. | | Exposure Calculation | How Statsig handles exposures logged during switchback windows in the analysis. Choose one of the exposure calculation options. | Metric calculation options: ![Metric Calculation drop-down with the three aggregation options](https://docs.statsig.com/images/Screenshot2026-02-25at2.44.24PM.png) | Option | Description | | --- | --- | | Period from first exposure | Aggregates metric data for a specified period of time after the user's first exposure. | | Entire window | Aggregates metric data across the full switchback window. | | Period between burn-in and burn-out | Aggregates metric data only within the portion of the window between the burn-in and burn-out periods. | Exposure calculation options: ![Exposure Calculation drop-down with include and exclude options](https://docs.statsig.com/images/Screenshot2026-02-25at2.50.36PM.png) | Option | Description | | --- | --- | | Include exposures in burn periods | Considers all exposures recorded during the switchback window, including those within the burn-in and burn-out periods. | | Exclude exposures in burn periods | Considers only exposures recorded between the burn-in and burn-out periods. | > **Info:** > > Coming soon: pre-computed user dimensions. You can configure user dimensions from the exposure user properties or entity properties to break down experiment results in the results section. ================================================================================ # Power Analysis URL: https://docs.statsig.com/statsig-warehouse-native/features/power-analysis Updated: 2026-10-27 ================================================================================ # Power Analysis Power analysis estimates the exposures and run time needed to detect a change in a metric. The smallest change you want to detect is the minimum detectable effect (MDE). Statsig Warehouse Native uses historical traffic and metric statistics from your warehouse to make this estimate. Run a power analysis before launching an experiment to choose its target duration and traffic allocation. For fixed-horizon analysis, the target duration establishes when you can draw a conclusion from the results. After launch, use the experiment's [Results](https://docs.statsig.com/experiments/interpreting-results/read-results) to interpret the observed effect. The estimate is most useful when the historical population resembles the planned experiment's users. ## Choose a representative population The population determines both the historical exposure count and the metric mean and variance used in the estimate. Choose one of these sources: | Population | Use it when | | --- | --- | | Previous Experiment | A prior experiment reached users similar to your planned audience. | | Qualifying Event | A recorded event identifies the users you plan to reach. | | Metric Source | A warehouse source identifies the users you plan to reach. | If users enter your planned experiment after clicking a checkout button, choose a qualifying event or metric source that represents those clicks. Historical traffic from a broader population can make the estimated duration too short or too long. ## Run a power analysis Open _Experimentation > Power Analysis_. On the _Calculator_ tab: 1. Under _Population_, choose **Previous Experiment**, **Qualifying Event**, or **Metric Source**. For a previous experiment, select an experiment in **Data Source**. 2. For a qualifying event or metric source, select the **ID Type** and source. Add filters and choose a historical date range that represents your planned audience. 3. Under _Metrics_, select one or more evaluation metrics. 4. Adjust the analysis period or CUPED option in the form's experiment settings if needed. 5. Click **Run Power Analysis**. ![Warehouse Native power analysis calculator with a previous experiment and optional settings](https://docs.statsig.com/images/statsig-warehouse-native/features/power-analysis/warehouse-native-calculator-settings.png) The analysis runs in the background. You can leave the page while it runs. ## Find and attach past analyses Open _Past Analyses_ to find and reopen a report. The list works the same way as the [Past Analyses view shown in the Cloud guide](https://docs.statsig.com/experiments/power-analysis#find-and-attach-past-analyses). To associate a report with an experiment, choose **Attach to Experiment** from its actions menu or **Attach Experiment** in the open report. To change the population or metrics, update the inputs and click **Re-Run Analysis**. ## Read the results Choose a metric in **Target Metric**, then select a results tab based on what you know about the planned experiment. Each available week uses that week's historical exposures and metric statistics. The result views are shared with the Cloud calculator. See the illustrated [Week by Week breakdown](https://docs.statsig.com/experiments/power-analysis#week-by-week-breakdown) and [Scenario Matrix](https://docs.statsig.com/experiments/power-analysis#scenario-matrix) for examples. ### Week by Week breakdown Use _Week by Week breakdown_ when you know the experiment's allocation and want to see the detectable MDE over time. Select a week to see estimated control and test exposures. Enter a target MDE to highlight weeks that meet your goal. The target is a planning threshold, not a predicted effect. ### Scenario Matrix Use _Scenario Matrix_ when you know the effect size you need to detect. It estimates the weeks needed for different group sizes and target MDEs. Select a cell to see estimated control and test exposures. You can add a custom group size or MDE. Scenario Matrix uses historical traffic to estimate future weeks. Treat estimates beyond observed history as planning estimates. If there isn't enough history, Statsig can't estimate a duration for a scenario. For the shared calculation method, refer to [Calculation details](https://docs.statsig.com/experiments/power-analysis#calculation-details). ## Adjust the experiment setup Expand _Experiment Setup_ below the results to match the estimate to the experiment you plan to run: - **Number of Groups**: Count the control group and every test group. - **Group Split**: Choose an equal split or set a different control group percentage. - **Allocation (% of eligible traffic)**: Set the share of eligible users who can enter the experiment. - **Significance Level (α)** and **Statistical Power (1-β)**: Set the thresholds used in the estimate. - **CUPED**: The setting reflects the choice made before running the Warehouse Native analysis. To change CUPED, update the form input and click **Re-Run Analysis**. - **Stats Method** and **Apply Bonferroni Correction Per Variant**: Choose the test and whether to correct for multiple comparisons. Changes recalculate the displayed results from the saved historical analysis. Click **Save Changes** to keep your settings. Expand _Advanced Statistics_ to inspect the historical metric statistics. For an illustrated view of these panels, see [Experiment Setup options](https://docs.statsig.com/experiments/power-analysis#experiment-setup-options) in the Cloud guide. ================================================================================ # Stratified Sampling URL: https://docs.statsig.com/statsig-warehouse-native/features/stratified-sampling ================================================================================ # Stratified Sampling ## What is stratified sampling Stratified sampling divides the entire population into homogeneous groups called strata (singular: stratum), then selects random samples from each stratum. For example, if you have XS and XL customers and randomize them into Control and Test groups, both groups should end up balanced across XS and XL customers. You can also stratify based on a metric like Revenue/User. With large populations, randomization typically achieves this balance. In B2B scenarios and other low-volume or high-variance situations, stratified sampling ensures the balance explicitly. Statsig supports both automated and manual stratified sampling. When a small number of power users drive a large portion of an overall metric value, stratified sampling meaningfully reduces false positive rates and produces more consistent, reliable results. Statsig simulations showed approximately a 50% decrease in the variance of reported results. ## Automated stratified sampling ### How it works The Statsig SDKs use a _salt_ to randomize or bucket experiment subjects ([how bucketing works](https://docs.statsig.com/faq#how-does-bucketing-within-the-statsig-sdks-work)). When you enable stratified sampling, Statsig tries 100 different salts and evaluates how balanced the resulting groups are. Statsig evaluates balance using either a metric or an attribute you provide that describes your experiment subjects. Statsig selects and saves the best salt from this set. [Learn more about stratified sampling](https://statsig.com/blog/introducing-stratified-sampling). ![Stratified sampling algorithm diagram](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/99f72b83-9f14-45a3-aa6e-ffcbd6211ec7.png) The selection space for salts is large enough that stratifying multiple experiments on the same metric doesn't result in overlap. In Statsig simulations, the groups were as independent as the literature predicts. ### Enabling stratified sampling You can enable stratified sampling under Advanced Settings on the experiment setup page. There are two ways to stratify on Statsig. If you choose a metric to stratify on, Statsig uses that metric to balance the groups. ![Stratified sampling metric selection interface](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/0cfc499d-4fdf-44a8-ba2a-3537ba5bb904.png) If you instead choose an attribute or classification (for example, S, M, L, XL), Statsig uses that to balance the groups. - On Statsig Cloud, you upload a CSV (in Early Access) - On Statsig Warehouse Native, you use Entity Properties ![Entity properties configuration for stratified sampling](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/102a839f-37fd-4443-807a-4b269f137490.png) After you select Stratify, Statsig analyzes a set of salts and picks the best one. ![Stratification analysis results interface](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/412f5c78-8c4f-4f16-88d3-60d3d3555ffd.png) ## FAQ and best practices - **What population does Statsig use when balancing?** - When evaluating salts, Statsig computes balance using pre-experiment data for the entire targeted population of the experiment’s unit type (e.g., all `userID`s or all `customerID`s) over the selected lookback window. There is no filtering on exposure because the experiment hasn't started yet. - **How does Statsig handle new units after stratification?** - Units that weren't present in the pre-experiment data still receive deterministic assignment from the chosen salt, i.e., effectively at random with respect to the balancing metric. They don't influence the salt selection and may introduce some drift from the initial balance. - **Should I use stratified sampling for every experiment?** - Not necessarily. It’s most useful when you expect imbalance due to heterogeneous units (e.g., “whales”) or skewed metrics. The tradeoff is time/compute cost that scales with the number of units and adds steps before starting an experiment. If you don’t expect meaningful imbalance, Statsig generally recommends a standard random split. - **Does salt evaluation assume 100% allocation? What about running at less than 100%?** - Yes. Statsig evaluates all candidate salts assuming 100% allocation of the targeted population. If you then run the experiment at an allocation below 100%, random sampling of that subset can reintroduce imbalance. For example, by chance, some high-impact units may fall disproportionately into one arm. For the period you care most about inference, prefer 100% allocation to preserve the intended balance. Use lower allocations briefly for safe rollouts rather than for the full experiment duration. - **Across candidate salts, does Statsig evaluate the same set of users?** - Yes. Statsig assesses candidate salts over the same targeted population; only the randomization induced by the salt changes. - **How long does stratification take?** - Duration depends on the number of units and the metric/source being queried. There is no fixed SLA; larger populations take longer. ## Manual assignment for stratified sampling When setting up an experiment, you can configure overrides (for example, force user X or Segment A into Control, force user Y or Segment B into Test). Overrides are for testing; Statsig excludes overridden users from experimental analysis in Pulse results. To include manually assigned users in stratified sampling analysis, select the **Include Overrides in Pulse** checkbox. This includes overridden users in all metric lift analyses. You can assign 100% of experiment participants manually, or assign a subset manually and randomly assign the rest. > **Note:** > > You can add overrides for an ID type that differs from the experiment's ID type, but Statsig won't resolve those ID evaluations to the experiment's ID type and they won't contribute to Pulse results. When you use the Statsig SDK for assignment, the SDK handles randomization. When you control assignment of users, you're responsible for balancing users across experiment groups. ![Manual assignment override configuration](https://docs.statsig.com/images/snippets/stats-methods/stratifiedSampling/230964234-8cc81f66-f4f8-4f37-b6df-6d36d0d7ab98.png) ## Additional reading [Morgan and Rubin 2012](https://projecteuclid.org/journals/annals-of-statistics/volume-40/issue-2/Rerandomization-to-improve-covariate-balance-in-experiments/10.1214/12-AOS1008.full) covers the history, philosophy, and proofs of re-randomization, including how re-randomization reduces the randomization variance of the difference in means. The paper notes that "standard asymptotic-based analysis procedures that do not take the re-randomization into account will be statistically conservative." Statsig remains conservative with the t-test to maintain consistent and comparable results across methods. [Lin & Ding 2019](https://arxiv.org/abs/1906.11291) is additional reference reading on this topic. ================================================================================ # Differential Impact Detection URL: https://docs.statsig.com/statsig-warehouse-native/features/differential-impact ================================================================================ # Differential Impact Detection Differential Impact Detection flags an experiment when its effect on one configured user segment, such as a browser, operating system, or country, differs sharply from its effect on all other users. Experiments can affect sub-populations in ways the topline result hides: a bug might affect only one browser, or a segment's lift might cancel out against other changes. Statsig analyzes experiments for differential impact when Pulse loads after Day 1, after Day 3, and when the experiment reaches its Target Duration, and it flags extreme differential impacts for any segment you configure. This feature is also called Heterogeneous Treatment Effect or Segments of Interest. ![Differential impact detection alert in Pulse results](https://docs.statsig.com/images/snippets/whn/differentialImpact/9783ba7a-812b-4fea-97af-4e3344f8345f.png) ## Configure segments of interest Configure the Segments of Interest that Statsig evaluates for Differential Impact Detection. On Statsig Cloud, segments are user properties in the [User Object](https://docs.statsig.com/concepts/user) that you set when you use the Statsig SDK. On Statsig Warehouse Native, you can also configure segments as an [Entity Property](https://docs.statsig.com/statsig-warehouse-native/features/entity-properties). ![Segments of Interest configuration interface](https://docs.statsig.com/images/snippets/whn/differentialImpact/c9bb5e56-dbc8-4fc2-a33b-92974f867120.png) ## How Statsig flags differential impacts If Statsig finds extreme outliers for a segment you configured, it flags the experiment when you view Pulse results. The Explore section of your Pulse results shows the data broken out by segment. ![Pulse results showing differential impact by segments](https://docs.statsig.com/images/snippets/whn/differentialImpact/5e5a3907-ff67-404c-a94f-2f986262008e.png) ## Methodology Statsig uses a Welch's t-test to compare the treatment effect for one segment of users with the treatment effect for all other users. Welch's t-test suits this comparison because user segments can have unequal population variances. Statsig calculates the average treatment effect as follows: $$ \overline{TE} = \overline{X_t} - \overline{X_c} $$ Statsig calculates the variance in treatment effect as follows: $$ var(TE) = var(X_t) + var(X_c) $$ Statsig calculates the n of the treatment effect as follows: $$ n_{TE} = min(n_t, n_c) $$ With these values, Statsig determines the t-statistic and degrees of freedom as it does for any experiment that uses [Welch's t-test](https://docs.statsig.com/stats-engine/p-value#welchs-t-test). Statsig then applies a Bonferroni Correction to adjust alpha and avoid false positives. The correction sets two thresholds: a high likelihood of heterogeneous treatment effect and some likelihood of heterogeneous treatment effect. For the Bonferroni Correction, one "comparison" is the calculation of one dimension against the rest, for one metric, for one test variant against control. $$ \text{high chance of HTE, } \alpha = \frac{0.01}{\text{number of comparisons}} $$ $$ \text{some chance of HTE, } \alpha = \frac{0.05}{\text{number of comparisons}} $$ ## View historical differential impact analyses To view all historical analyses, go to the _Explore_ tab of your experiment and filter to the Differential Impact Detection query type. ================================================================================ # Targeting URL: https://docs.statsig.com/statsig-warehouse-native/features/targeting Updated: 2025-09-18 ================================================================================ # Targeting ## How to target experiments Experiments integrate natively with Statsig's Feature Gates product to target interventions. Feature gates provide a rich language for targeting users by properties or segments. You can give an experiment a targeting gate to restrict an intervention to units that pass that gate. Go to [Feature Gates](https://docs.statsig.com/feature-flags/overview) for more information. ## When to target an experiment Targeting an experiment makes sense when - You want to gradually release the experiment to tiers of users - Part of your hypothesis is that the experiment intervention only works for a target subset of users, e.g. mobile users ================================================================================ # ID Resolution (ID Stitching) URL: https://docs.statsig.com/statsig-warehouse-native/features/id-resolution Updated: 2025-10-21 ================================================================================ # ID Resolution (ID Stitching) Statsig Warehouse Native resolves multiple IDs to one identified user. You can expose an experiment on one identifier and analyze data from one or more mapped identities associated with that experimental unit. Common scenarios include: - Exposing logged-out users and analyzing logged-in metrics like revenue, or a funnel from a logged-out marketing page landing to a logged-in subscription purchase. - Using one-to-many relationships, for example when a single user owns multiple accounts. ID resolution lets you aggregate metrics from the user's mapped accounts. This approach reduces statistical power but is statistically sound. ID resolution is a common need in experimentation. Without it, the responsibility for identity mapping typically falls on data users or PMs, which leads to inconsistent results and expensive query logic. Advanced ID Resolution centralizes this process, making it consistent and performant, and allowing all users to reference trusted identity tables. ## The challenge: connecting user identifiers A common challenge in experimentation is linking user identifiers before and after an event boundary, most often signups. Experimenters typically have a logged-out ID (for example, a cookie or Statsig stableID) and, for users who sign up, a userID created afterward. Because teams typically compute business metrics at the userID level, they often want to randomize on logged-out identifiers but measure outcomes on logged-in metrics like revenue or LTV. Most platforms require manual joins or preprocessing to connect these identifiers, leading to complex, error-prone queries that must reconcile exposures across time and mapping tables. Statsig Warehouse Native provides an automatic, no-code way to connect identifiers across these boundaries. The approach is centralized, consistent, and reproducible. ![Docs_IDresolution_TheProblem_111224b](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/05cb4f49-14a2-4b51-a0e0-63f127838ce4.png) ## Mapping modes When using ID resolution, you can choose from one of three modes: - Strict 1:1 mapping enforces that identities have a singular mapping. If you have a mapping between two IDs that are always 1:1, this mode enforces that the mapping is singular. Statsig warns you if the data contains records where that isn't the case. Users with a single identity can use downstream metrics from the secondary identity. Statsig considers multi-mapped users corrupted and discards them from the analysis. - First-touch mapping attributes activities of secondary IDs to one primary ID based on the user's first exposure to the experiment. - Last-touch mapping attributes activities of secondary IDs to one primary ID based on the user's most recent exposure to the experiment. ### Strict 1:1 mapping ![Enforced1to1Mapping](https://docs.statsig.com/images/whn/Docs_IDresolution_Enforced1to1Mapping_111324.gif) Statsig collects all potential mappings between identifiers within the experiment date range, on the exposed population. If the primary ID has multiple secondary IDs, or vice versa, Statsig considers the record polluted and drops it from the analysis. Choosing this mode changes the exposures on the primary ID because it disqualifies any records outside of a 1:1 mapping. ### First touch mapping (mixed population) ![Enforced1to1Mapping](https://docs.statsig.com/images/whn/Docs_IDresolution_FirstTouchAttribution_111324.gif) The experiment determines the direction of first-touch mapping; all secondary IDs resolve to 1 primary ID, and a single primary ID can have multiple mapped secondary IDs. Statsig attributes data to the group of the first associated primary ID seen in the exposure. If a secondary ID has multiple associated primary IDs, Statsig uses the group of the first primary ID. Statsig doesn't discard users that cross groups from analysis; instead, it assigns them based on their first experience. Statsig drops primary ID records that are associated with another primary ID but aren't the first observed records from the analysis. If a user is exposed twice on different primary IDs that resolve to the same secondary IDs, Statsig keeps only the primary ID metrics from the first-exposed user. ### Last touch mapping (mixed population) ![LastTouchAttribution](https://docs.statsig.com/images/whn/Docs_IDresolution_LastTouchAttribution.gif) Same as first touch but Statsig attributes data to the most recent primary ID. ### What mixed population means ![MixedPopulation](https://docs.statsig.com/images/whn/Docs_IDresolution_Primary_Population.gif) Both first-touch and last-touch mapping show pulse results based on a mixed population. Each metric uses the corresponding population for its unit type. For example, consider an experiment that randomizes on Stable ID, where the scorecard metrics include both Stable ID and User ID metrics. Pulse uses the raw exposure population for Stable ID metrics, to stay true to the randomization process. For User ID metrics, Pulse uses the resolved population, depending on the mapping mode. ### Explanation of methodology 1. Statsig prefers primary IDs over secondary IDs if present in the data. The unit type of analysis should match that of randomization. Statsig always prefers the primary ID when it's present in the data. If the primary ID isn't present, Statsig uses the most recent secondary ID. 2. Statsig uses secondary IDs only to join metrics to exposures, but the unit of analysis is still the primary ID. Statsig calculates the unit counts of each metric's results using the primary ID. 3. Statsig handles many (primary) to one (secondary) mapping by attributing the secondary ID to ONE primary ID. 4. Statsig implicitly handles one (primary) to many (secondary) mapping by treating all secondary IDs as the same unit. For example, Statsig adds the metric value in a sum metric or counts it in a count metric. 5. Statsig supports a mixture of primary and secondary IDs in the same experiment. You can use both primary and secondary IDs in the same experiment. For example, when you run a signup experiment, you can measure session-level metrics for the primary ID and user-level metrics for the secondary ID. To do this, Statsig maintains two populations: one for the primary ID and one for the secondary ID. The primary ID population is the same as if you had only used the primary ID. ## How to enable ID resolution in a Statsig experiment To set up identity resolution in Statsig, either log or join data to provide both IDs on your assignment source, or provide one ID in the assignment source along with a mapping table in the form of an Entity Property Source. ### Using property source To use Identity Resolution across experiments in your project, you need a lookup table that has both the ID you're exposing on and the selected target ID. Configure this table by setting up an Entity Property Source with both IDs present. After you do that, select this source when configuring your secondary ID type, and Statsig handles the join for you. ![ID resolution source configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/3fc0422d-ed96-4fe6-9e52-05e24a6cc2a2.png) If you want to use a Statsig SDK to populate this table, you can log an event (for example, a "Signup" event) that has both the logged-out identifier and the user ID on the same event. Statsig writes events sent through the SDK into your warehouse, and you can configure an Identity Resolution source on top of that: ![Identity resolution configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/6b2a3d0e-a1ad-446b-a604-43dd050f05fa.png) ### Using assignment source When creating an assignment source, provide a column for both ID types. Statsig expects the Primary ID to be non-null for exposure records. The secondary ID can be null. If the secondary ID is sparse (some records are null due to logging), Statsig back-attributes any identified secondary ID to other records from the same primary ID. ![ID Resolution Assignment Source](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/8cbdd8cc-2ea6-4bf8-a620-0428051989d1.png) When you create an analysis-only experiment or power analysis with this ID type, you can optionally select a Secondary ID. If you do so, you can now use metrics from either ID type in your analysis. For E2E experiments that use the Statsig SDK, you can configure this on the experiment setup page, under Advanced settings. Internally: - For metric sources with the primary ID, Statsig joins metrics to exposures based on that primary ID. - For metric sources with only the secondary ID, Statsig joins metrics to exposures based on that secondary ID. - In strict mode, Statsig drops users with a duplicate mapping from analysis. In first-touch mode, units use their first exposure record and merge data from all mapped secondary IDs. This works natively across Metric Sources, so you can set up funnel or ratio metrics across the two ID types. Analysis uses the primary ID. This process associates metric values from the secondary ID with the corresponding primary ID records. ### Mapping changes If you change the entity property source or assignment source's definition or underlying data, Statsig reflects those changes on the next reload. This is why you need a full reload, since otherwise historical changes to the mapping can lead to inconsistent data on incremental reloads or explore queries. ### Best practices Statsig recommends using an [Entity Property Source](https://docs.statsig.com/statsig-warehouse-native/configuration/entity-properties) to provide a cleaned unit mapping from your warehouse. You can also provide mappings on your exposure source by logging multiple identifiers in the exposure data. Statsig uses all available identifiers to match across records. For both modes, an experiment can only have one mapped ID type, for example secondary\_id->user\_id or secondary\_id->account\_id, but not both. All modes require a full reload to prevent data inconsistency when you change historical mappings or introduce new mappings. Statsig filters the property source or assignment source used to provide mappings to records within the experiment's date range. If a mapping is "evergreen", or not scoped to a specific time period, you can omit the timestamp on the entity property source. #### Example of a supported schema if your assignment source data contains: `{stableID: 'unknown_123', exp_id: 'PDP Test', test_group: 'Control'}` and your metric sources contain data that represents a metric as: `{userID: 'known_abc', event: 'page_load'}` Your Entity Source or Assignment source must contain the secondary identity (in this case, `userID`) that enables Statsig to join your assignment data with your metric data: `{stableID: 'unknown_123', userID: 'known_abc', country: 'USA'}` ## Considerations Deduplicating records can lead to biased results, so Statsig performs two extra health checks on this kind of experiment. - Statsig checks your deduplication rate and warns you if it's unusually high. Expect some secondary IDs to have multiple logged-out IDs due to users using different devices or clearing browser history. - Statsig performs a chi-squared test to evaluate whether the deduplication rate is identical across arms of the experiment. In some cases, an experiment may cause more users to return (for example, an email re-engagement campaign), in which case duplicates are likely more frequent in that arm and can be a positive outcome. In this case, you can use first-touch attribution to maintain a common identifier. Statsig supports breakdowns of metric dimensions for experiment results only on properties associated with primary ID types. Statsig doesn't support secondary ID type dimension breakdown for experiment results and custom queries due to high risk of post-exposure data leaking into the group-by's or filters. ================================================================================ # ID Resolution (ID Stitching) URL: https://docs.statsig.com/statsig-warehouse-native/features/id-resolution-legacy Updated: 2025-10-21 ================================================================================ # ID Resolution (ID Stitching) ID resolution (also called ID stitching) maps cross-platform IDs in experiment analysis so you can connect a user's logged-out and logged-in activity to the same experiment result. Use ID resolution to analyze experiments where exposure and metrics happen at different ID grains. For example, exposure happens at a device or logged-out ID, while metrics land at an account or user ID. At the earliest, Statsig will update its ID resolution methodology to reflect mixed population on November 15th. ## Mapping modes When using Advanced ID resolution, you can choose between modes: - Strict 1:1 mapping enforces that identities have a singular mapping. If you have a mapping between two IDs that are always 1:1, this mode enforces that the mapping is singular. Statsig warns you if the data contains records where that isn't the case. Users with a single identity can use downstream metrics from the secondary identity. Statsig considers multi-mapped users corrupted and discards them from the analysis. - First-touch mapping applies when units might have multiple mappings in either direction. For example, a single user may have multiple "profiles", or someone may have logged into the same account from several devices or web sessions. In this case, units use the experiment group of their first exposure for analysis and aggregate metrics from all of their associated secondary IDs. | Strict 1:1 Mapping | First Touch Mapping | | --- | --- | | ![Enforced1to1Mapping](https://docs.statsig.com/images/whn/Docs_IDresolution_Enforced1to1Mapping_111324.gif) | ![FirstTouchAttribution](https://docs.statsig.com/images/whn/Docs_IDresolution_FirstTouchAttribution_111324.gif) | ### Strict 1:1 mapping Statsig collects all potential mappings between identifiers within the experiment date range, on the exposed population. If the primary ID has multiple secondary IDs, or vice versa, Statsig considers it polluted and drops it from the analysis. ### First touch mapping The experiment determines the direction of first-touch mapping; all secondary IDs resolve to 1 primary ID, and a single primary ID can have multiple mapped secondary IDs. If your aim is to only have one secondary ID, you can manage that logic inside the entity property source today. Contact support if you want to request specific logic. Statsig attributes data to the group of the first associated primary ID seen in the exposure. If a secondary ID has multiple associated primary IDs, Statsig uses the group of the first primary ID. Statsig doesn't discard users that cross groups from analysis; instead, it assigns them based on their first experience. Statsig drops primary ID records that are associated with another Primary ID but aren't the first observed records from the analysis. If a user is exposed twice on different primary IDs that resolve to the same secondary IDs, Statsig keeps only the primary ID metrics from the first-exposed user. ### Last touch mapping Same as first touch but Statsig attributes data to the most recent primary ID. ### Note on ID stitching Multiple secondary IDs attached to one primary ID still count as "one" experimental primary ID. Statsig merges the metric values across records from the different secondary IDs, for example added in a sum metric or counted in a count metric. > **Info:** > > Statsig is interested in supporting more complex 1-to-many relationships of identities and is eager to partner with customers to develop these capabilities if you need a more advanced use-case. ## How it works To set up identity resolution in Statsig, either log or join data to provide both IDs on your assignment source, or provide one ID in the assignment source along with a mapping table in the form of an Entity Property Source. ### Using property source To use Identity Resolution across experiments in your project, you need a lookup table that has both the ID you're exposing on and the selected target ID. Configure this table by setting up an Entity Property Source with both IDs present. After you do that, select this source when configuring your secondary ID type, and Statsig handles the join for you. ![ID resolution source configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/3fc0422d-ed96-4fe6-9e52-05e24a6cc2a2.png) If you want to use a Statsig SDK to populate this table, you can log an event (for example, a "Signup" event) that has both the logged-out identifier and the user ID on the same event. Statsig writes events sent through the SDK into your warehouse, and you can configure an Identity Resolution source on top of that: ![Identity resolution configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/6b2a3d0e-a1ad-446b-a604-43dd050f05fa.png) ### Using assignment source When creating an assignment source, provide a column for both ID types. Statsig expects the Primary ID to be non-null for exposure records. Your secondary ID can be null. If your secondary ID is sparse (some records are null, and some are not due to logging), Statsig back-attributes any identified secondary ID to other records from the same Primary ID. ![ID Resolution Assignment Source](https://docs.statsig.com/images/statsig-warehouse-native/features/id-resolution/8cbdd8cc-2ea6-4bf8-a620-0428051989d1.png) When you create an analysis-only experiment or power analysis with this ID type, you can optionally select a Secondary ID. If you do so, you can now use metrics from either ID type in your analysis. For E2E experiments that use the Statsig SDK, you can configure this on the experiment setup page, under Advanced settings. Internally: - For metric sources with the primary ID, Statsig joins metrics to exposures based on that primary ID. - For metric sources with only the secondary ID, Statsig joins metrics to exposures based on that secondary ID. - In strict mode, Statsig drops users with a duplicate mapping from analysis. In first-touch mode, units use their first exposure record and merge data from all mapped secondary IDs. This works natively across Metric Sources, so you can set up funnel or ratio metrics across the two ID types. Analysis uses the primary ID. This process associates metric values from the secondary ID with the corresponding primary ID records. ### Mapping changes If you change the entity property source or assignment source's definition or underlying data, Statsig reflects those changes on the next reload. This is why you need a full reload, since otherwise historical changes to the mapping can lead to inconsistent data on incremental reloads or explore queries. ### Best practices Statsig recommends using an [Entity Property Source](https://docs.statsig.com/statsig-warehouse-native/configuration/entity-properties) to provide a cleaned unit mapping from your warehouse. You can also provide mappings on your exposure source by logging multiple identifiers in the exposure data. Statsig uses all available identifiers to match across records. For both modes, an experiment can only have one mapped ID type, for example secondary\_id->user\_id or secondary\_id->account\_id, but not both. All modes require a full reload to prevent data inconsistency when you change historical mappings or introduce new mappings. Statsig filters the property source or assignment source used to provide mappings to records within the experiment's date range. If a mapping is "evergreen", or not scoped to a specific time period, you can omit the timestamp on the entity property source. #### Example of a supported schema if your assignment source data contains: `{stableID: 'unknown_123', exp_id: 'PDP Test', test_group: 'Control'}` and your metric sources contain data that represents a metric as: `{userID: 'known_abc', event: 'page_load'}` Your Entity Source or Assignment source must contain the secondary identity (in this case, `userID`) that enables Statsig to join your assignment data with your metric data: `{stableID: 'unknown_123', userID: 'known_abc', country: 'USA'}` ## Considerations Deduplicating records can lead to biased results, so Statsig performs two extra health checks on this kind of experiment. - Statsig checks your deduplication rate and warns you if it's unusually high. Expect some secondary IDs to have multiple logged-out IDs due to users using different devices or clearing browser history. - Statsig performs a chi-squared test to evaluate whether the deduplication rate is identical across arms of the experiment. In some cases, an experiment may cause more users to return (for example, an email re-engagement campaign), in which case duplicates are likely more frequent in that arm and can be a positive outcome. In this case, you can use first-touch attribution to maintain a common identifier. ================================================================================ # Filter Exposures URL: https://docs.statsig.com/statsig-warehouse-native/features/filtering-exposures Updated: 2025-09-18 ================================================================================ # Filter Exposures ## Filter Exposures by Qualifying Event You can use Qualifying Events to filter exposures to units that did or did not trigger an event after exposure. Qualifying Events are useful for analysis-only experiments where the assignment tool may have over-exposed units. For example, the tool might assign units on page load when the intervention only triggered when a user clicked a button. ![Qualifying event filter configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/filtering-exposures/f7a5ee06-b67a-4cba-9680-fbe99c64d0fc.png) Use this tool with caution. It's possible to introduce post-assignment data into your assignment data, biasing results. For this reason, Statsig disables qualifying event filters by default on Assign and Analyze experiments, because the Statsig SDK typically doesn't over-expose units. Contact the Statsig team to enable this feature if you have a use case for it. You can configure the following settings: - Qualifying Event: the event source to qualify exposures with. You can filter this to pick specific target events within a qualifying event source. - Exclude matching units: whether to include or exclude units that triggered the event. - Use qualifying event timestamp for first exposures: if the actual intervention occurred when the unit triggered the qualifying event, enable this setting so that Statsig overrides the exposure timestamp with the qualifying event timestamp. - Filter events by time window: restrict qualifying event matching to events that occurred within X days or minutes of the unit's exposure event. ## Filter Assignment Source You can also filter exposures to units based on columns in the assignment source. You can use certain columns directly and apply additional filters on top. As with filtering by qualifying event, use this tool carefully because it can artificially introduce bias to experiment results. ![Assignment source filter selection UI](https://docs.statsig.com/images/statsig-warehouse-native/features/filtering-exposures/36ddb74f-d9e9-4e25-8349-61077f77b863.png) ================================================================================ # Normalized Metrics (aka Clustered Experiments) URL: https://docs.statsig.com/statsig-warehouse-native/metrics/normalized-metrics Updated: 2025-09-18 ================================================================================ # Normalized Metrics (aka Clustered Experiments) ## When to use normalized metrics Normalized metrics scale a unit-level metric by the number of units exposed, so you can compare groups when the unit of randomization differs from the unit of analysis. In standard A/B tests, the unit of randomization (for example, UserID) matches the unit of analysis. In some cases, though, the two units should differ. The most common example is B2B experiments where you want to randomize by BusinessID but measure by average metric per UserID, not average metric per BusinessID. For example, if you add image support to a collaborative commenting feature and want to A/B test it before rollout, you randomize using BusinessID. You can't randomize by UserID, because everyone within a single business must have the same treatment. If you compared comments per BusinessID, the data would be skewed by large companies. A business with 1000 employees and 10 comments would contribute more weight than a business with 5 employees and 5 comments. Normalizing the metric by users exposed to the experiment corrects for this skew. If 1000 and 5 users were exposed from each business, the first business would have a comments/user rate of 0.01 and the second would have a rate of 1. These normalized rates make the comparison valid across companies of different sizes. ## What normalized metrics do Internally, normalizing a metric creates a ratio metric. The numerator is the metric being normalized. The denominator is a COUNT DISTINCT of the UnitID being normalized to. To create this ratio metric yourself and use it in experiments, refer to the [Cluster Experiments](https://docs.statsig.com/metrics/different-id) guide. ## How to create normalized metrics Create normalized metrics when adding metrics to an experiment. ![Experiment metrics configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/metrics/normalized-metrics/a440ccfa-0271-4fbd-ba9d-7bb858f3e180.png) Select the unitID to normalize by on the next screen. ## Where to use normalized metrics You can use normalized metrics anywhere you can run a ratio metric and a count-distinct metric. ================================================================================ # Experiment Quality Score URL: https://docs.statsig.com/statsig-warehouse-native/features/quality-score ================================================================================ # Experiment Quality Score ## How Experiment Quality Score works The Experiment Quality Score is a metric that gives a quick view of the quality and trustworthiness of an experiment configured in Statsig. The score helps experimenters and their peers across an organization identify potential issues in experiment setup, execution, and data collection, supporting more confident decision-making. Measuring this score across all experiments can help teams discover systematic issues in their program and identify opportunities to improve their experimentation program over time. ## Configure Experiment Quality Score Enable Experiment Quality Score in the project settings under _Settings > Experimentation > Experiment Quality Score_. The feature uses a list of pre-defined assessment criteria. You can customize the weight of each criterion based on your organization's needs, though Statsig provides default values. ![Experiment quality score configuration interface](https://docs.statsig.com/images/snippets/quality-score/91fea3df-0dae-4d0a-ada8-1c1c9313e60e.png) ## Advanced configuration using the console API For teams that need additional checks, have different requirements across product teams, or need different thresholds, Statsig supports advanced configuration through the console API. For example, you can require hypotheses to be at least 200 characters and contain a link to an external planning document. To configure this, run a POST or PATCH on the `console/v1/experiments` endpoint to update individual scores on any given experiment. Targeting the existing set of scores lets you override weights (usually to 0), so the list contains only the custom set needed. For example, running patch on an experiment with this payload: ```plaintext { "manualQualityScores": [ { "criteriaName": "HYPOTHESIS_LENGTH", "criteriaDescription": "Check passed", "status": "PASSED", "score": 0, "weight": 0 }, { "criteriaName": "MyCompany\'s Hypothesis Check", "criteriaDescription": "Has Internal URL and > 200 Chars", "status": "PASSED", "score": 100, "weight": 100 }, { "criteriaName": "Naming", "criteriaDescription": "Experiment prefixed with team name", "status": "FAILED", "score": 0, "weight": 100 } ] } ``` Would: - Drop the original HYPOTHESIS\_LENGTH check - Keep the other original checks, with their weights - Add a new check, `MyCompany's Hypothesis Check`, for custom logic on the hypothesis - Add a new check, `Naming`, for custom logic on the name Statsig normalizes the other weights. If the original HYPOTHESIS\_LENGTH had a weight of 10, the total weight becomes 290 and Statsig normalizes scores accordingly. If all non-custom checks are passing, the score is 190/290 or ~66%. The general flow for using this approach is: - Use Console API's `experiments/get` to pull all experiments - For each experiment: - Run custom logic - Patch results ## Calculation notes Statsig skips checks in an unready state during evaluation and renormalizes the other weights to 100%. For example, if the experiment hasn't started, the `Balanced Exposures` component is in an unready state and Statsig ignores it. Statsig omits checks with a weight of 0 entirely from the card. ## View quality scores When enabled, quality scores appear in the details tab of an experiment. Statsig evaluates applicable checks and contributes them to the number shown. Statsig color-codes the score based on the percentage threshold: - > = 85% corresponds to passing/green - > = 50% corresponds to warning/yellow - < 50% corresponds to error/red ![Experiment quality score display with color-coded status](https://docs.statsig.com/images/snippets/quality-score/d7483b96-8077-419d-9e23-a3e648b7e066.png) The console API also provides quality scores, letting you retrieve the data in bulk for analysis. ================================================================================ # Experiment Diagnostics URL: https://docs.statsig.com/statsig-warehouse-native/features/monitor-an-experiment Updated: 2025-09-18 ================================================================================ # Experiment Diagnostics After you turn on your experiment, you can monitor its health and view the exposures for the control and variant groups. ### Monitoring experiment health To monitor the status of your experiment, - Navigate to **Experiments** in the left-hand navigation panel in the Statsig console. - Select the experiment you want to monitor. - **Experiment Health Checks** show alerts for problems with the experiment setup. Hover over the icon and click on a check for more details. ![Diagnostic health check image](https://docs.statsig.com/images/statsig-warehouse-native/features/monitor-an-experiment/8b557e40-2473-45e1-ac0c-bd61a2eb5208.png) - **Pulse metrics available** monitors availability of Pulse results, which Statsig expects the day after the experiment starts if your metrics have landed. - **Exposures are balanced** checks that the number of units exposed in each group matches the expected allocation. The Sample Ratio Mismatch (SRM) check uses a Chi-Squared test of independence. Experiments can temporarily show small imbalances due to the randomness of user assignment; these typically resolve after a couple of days. True SRM imbalances that originate from systematic assignment or logging problems tend to persist over time. The following thresholds apply to SRM alerts: - **p-value between 0.001 and 0.01**: Warning (yellow) for possible imbalance. The p-value isn't low enough to confirm a real imbalance. Wait and check again the next day. - **p-value < 0.01 and group size differs from expected size by less than 0.1% absolute**: Warning (yellow) indicating that an imbalance is possible, but the impact to the experiment is likely small. This scenario typically occurs in large web experiments (1M+ users). In these experiments, small variations in performance across groups can cause Statsig to drop a small fraction of exposures for certain groups more than others. - **p-value < 0.001 and more than 0.1% absolute deviation from expected group size**: Alert (red) meaning there is likely a problem with the experiment exposures and experiment results may not be trustworthy. - **Crossover users** monitors the percentage of units exposed to more than one experiment group. Statsig discards crossover users from the experiment analysis, which may reduce your sample size and statistical power. The following alerts apply based on the threshold for that experiment type: - **Warning (yellow)**: Statsig detected several crossover users, but the impact on the experiment is likely relatively small. - Assign & Analyze: **0.1% to 1%** - Analyze Only: **1% to 10%** - **Alert (red)**: There are a substantial number of crossover users, which can indicate a problem with your experiment setup. - Assign & Analyze: **Over 1%** - Analyze Only: **Over 10%** - **User metrics were computed** confirms that Statsig joined exposure data to metric data and produced experiment results. - **Metrics Available for Topline Impact** checks whether there is sufficient metric data to calculate topline impacts. Go to [topline impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact) for details. - **Differential Impact Detection completed** checks whether the differential impact detection has finished and flags extreme differential impacts for any sub-population according to your configuration. Go to [differential impact detection](https://docs.statsig.com/experiments/exploring-results/differential-impact-detection) for details. Some health checks apply only to end-to-end Statsig experiments where the Statsig SDK handles assignment; others apply only to analysis experiments where assignment happens outside of Statsig. - **Checks started** (end-to-end only) verifies that config checks are occurring. Available shortly after the experiment starts. - **Checks have valid unit type** (end-to-end only) ensures that config checks contain the unit ID type selected for this experiment (user ID by default). Available when checks begin. - **Exposures found** (analysis only) verifies that you provide exposures for this experiment, and Statsig populates it after pulse loads. Some health checks apply to experiments where Statsig stitches ID types. For example, in a sign-up flow experiment, stitching Stable ID to User ID enables analysis before and after a user logs in. Duplicate mapped IDs occur when the same primary ID maps to multiple secondary IDs or vice versa. This happens when you reset the primary identifier, or when there are multiple conversions from the same primary identifier. Deduplication can reduce your sample size and may affect the overall magnitude of your results. - **Deduplication Rate Check** reports the percentage of exposures which have duplicate mapped ids across primary and secondary IDs. Statsig uses the following thresholds to display deduplication rate alerts: - **Deduplication rate between 1% and 5%** Warning (yellow) indicating that Statsig applied deduplications; Statsig excludes affected units from analysis, which reduces the sample size and may affect the overall magnitude of results. - **Deduplication rate greater than 5%** Alert (red) indicating that Statsig applied and excluded a substantial number of deduplications from analysis. This can indicate a problem with the experiment setup or a 1-many mapping between the two IDs. :::note Statsig supports 1-many and many-many mapping in Advanced ID Resolution, in addition to 1-1 mapping. Go to [Advanced ID Resolution](https://docs.statsig.com/statsig-warehouse-native/features/id-resolution) for details. - **Deduplication Bias Check** reports the percentage of exposures which have duplicate mapped ids across primary and secondary IDs in each group and performs a Chi-Squared test of independence. Statsig uses the following thresholds to display deduplication bias alerts: - **p-value between 0.001 and 0.01**: Warning (yellow) indicating possible bias. The p-value isn't low enough to confirm a real imbalance in deduplication rate between groups. Wait and check again the next day. - **p-value < 0.001**: Alert (red) indicating that Statsig is likely applying deduplication more to one treatment group, and experiment results may not be trustworthy. - **Pre-experimental Bias Check** In some cases, users in two experiment groups have meaningfully different average behaviors before the experiment applies any intervention. If this difference persists after the experiment starts, the analysis may attribute that pre-existing difference to the intervention. CUPED helps address this bias but can't fully account for it. [Learn more](https://docs.statsig.com/experiments/statistical-methods/pre-experiment-bias). - **Outlier Check** In some cases, a few outliers can materially influence metrics. This check alerts you so you can evaluate whether tools like Winsorization or Capping are appropriate. It also verifies that capping isn't unduly influencing results if already applied. ================================================================================ # Loading Pulse URL: https://docs.statsig.com/statsig-warehouse-native/features/reloads Updated: 2025-09-18 ================================================================================ # Loading Pulse ## How the Pulse Engine works Statsig's experimentation engine runs the setup, diagnostics, and transformations required to generate the data points that power statistical experiment analysis. In Warehouse Native, the engine runs a series of query jobs called a DAG (Directed Acyclic Graph). These jobs take data from your sources and metric configurations to a final result set. You can find reload controls on the pulse results page: ![Pulse Load Controls](https://docs.statsig.com/images/statsig-warehouse-native/features/reloads/f6c1aa47-8d6e-4b21-96ac-f2281d0d0491.png) ### Types of reloads Statsig offers several ways to reload data: - [Full Reloads](https://docs.statsig.com/statsig-warehouse-native/features/full-reloads) completely restate your experiment data. Full reloads are useful when your underlying data changes significantly day-to-day (for example, a full DBT reload) and you want your analysis to match your raw data. - [Incremental Reloads](https://docs.statsig.com/statsig-warehouse-native/features/incremental-reloads) update your data from the last load to the current date. Running daily incremental reloads is the recommended way to keep your data current without using unnecessary compute resources to recalculate data that hasn't changed. - [Metric Reloads](https://docs.statsig.com/statsig-warehouse-native/features/metric-reloads) are useful when you want to add a metric to an analysis, or when a metric definition has changed. A metric reload does an efficient spot replacement of the data for a single metric or set of metrics. You can [schedule](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/scheduled-reloads/) full and incremental loads to get fresh results each day. ### Transparency For every load, Statsig logs the compute time and jobs, cost, and queries associated with the reload. This information is visible in your console and helps you understand what is taking time or delaying results. ### Efficient reloads Statsig optimizes the queries running in your warehouse. In direct comparisons, customers report that Statsig uses significantly fewer resources than comparable platforms. Statsig also offers turbo mode, which skips some enrichment calculations (in particular some time series rollups) to compute the latest snapshot of your data at lower cost. Using turbo mode, customers have run experiments on 150+ million users in less than 5 minutes on a Snowflake S cluster. ### Cleaning up storage Statsig automatically cleans up explore datasets, power analyses, and stratification artifacts. After you make a decision on an experiment, you can choose to delete the staging datasets, the result datasets, or both. You can also return to the experiment later and clean up from the experiment menu. ================================================================================ # Turbo Mode URL: https://docs.statsig.com/statsig-warehouse-native/features/turbo Updated: 2025-09-18 ================================================================================ # Turbo Mode Turbo Mode reduces the compute cost and load time of large Statsig Warehouse Native experiments. It calculates statistics only for the latest snapshot instead of recomputing cumulative results for every day. It trades away historical tracking, including the date picker for viewing Pulse results as of a past date and the cumulative timeseries. Use it for large, long-running experiments where standard loads are slow or expensive. By default, Statsig and other warehouse-native platforms calculate cumulative results for every day in an experiment. This calculation lets users review a rich historical view or make changes and see how those changes would have affected an analysis on previous days. This flow is heavily optimized, but it requires additional compute, so Turbo Mode gives you control over the tradeoff between compute cost and historical tracking, particularly for large experiments. ## How to use turbo mode When loading Pulse, there is a checkbox to enable Turbo Mode. Subsequent scheduled loads use the last setting. Turbo Mode changes the shape of the underlying data, so switching back to standard analysis requires a full reload with Turbo Mode disabled. There is also a project-level setting for Turbo Mode being on or off by default in a project's experimentation settings. ## What Turbo Mode removes Turbo Mode removes two features: the ability to use the date picker to view Pulse results as of a historical date, and the cumulative timeseries. Both features work when Statsig loads an experiment daily using incremental reloads. However, they may miss dates if there are gaps in the loading schedule, and they don't retroactively update when you run a full reload. ![Cumulative Timeseries](https://docs.statsig.com/images/whn/cumulative_timeseries.png) ## What Turbo Mode keeps Turbo mode and standard loads both calculate identical pulse results (including CUPED and other advanced techniques) for the latest day of the experiment analysis. Turbo mode still calculates the "daily" and "days since exposure" timeseries for diagnosis, as well as pre-experiment bias checks. ## What to expect Results vary depending on experiment settings, but Turbo jobs on large, long-running experiments typically show a 40-80% reduction in load time and compute cost. This estimate is likely biased and treat it as approximate, because the observation comes from cases where standard loads were slow and users applied Turbo Mode in response. There is no good counterfactual for companies that use Turbo Mode by default. ## When to use Turbo Turbo Mode is more effective for long-running experiments using full reloads, because without Turbo Mode the job must recreate the entire history of "user state" on each day. Turbo Mode calculates statistics only for the latest snapshot, skipping many calculations. Turbo Mode is also more effective for experiments with an unusually large number of users or metrics, because it reduces memory requirements and prevents the warehouse from spilling to disk. Disk spill dramatically slows jobs and increases cost. Holdouts benefit from Turbo Mode because they typically have a large battery of metrics, expose a large portion of a project's users, and commonly run for 3-6 months. Turbo Mode is less effective for experiments with scheduled incremental reloads or for smaller experiments. ================================================================================ # Full Reloads URL: https://docs.statsig.com/statsig-warehouse-native/features/full-reloads Updated: 2025-09-18 ================================================================================ # Full Reloads Full reloads completely wipe the Staging and Results datasets Statsig has used for previous pulse calculations, and Statsig recalculates results from scratch. ## Forwarded exposures and full reloads A full reload recalculates experiment results from the staging and results datasets. It doesn't rebuild or backfill the forwarded exposures table. A reload may also forward recent exposures before the daily export. These updates are best-effort and can be incomplete. Use the daily export as the authoritative record of eligible forwarded exposures. For details, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). Choose a full reload when Statsig needs to recompute staging and analysis results, rather than an incremental reload that only appends new data or a metric reload that restates a single metric. Generally, use full reloads for - Initial or historical pulse loads. - Cases where the customer side has lost or dropped data, so incremental reloads have lost state. - Cases where data changes frequently. For example, a dbt full reload changes historical data due to chargebacks, model changes, or other reasons. - Cases with complex data dependencies, where a team wants to ensure that the gap between Statsig and internal systems doesn't cause inconsistencies. ================================================================================ # Incremental Reloads URL: https://docs.statsig.com/statsig-warehouse-native/features/incremental-reloads Updated: 2025-09-18 ================================================================================ # Incremental Reloads Incremental reloads save state from the last load, and load from the latest data read with a small buffer to ensure completeness. This job wipes data since the last load, plus that buffer, and then appends all new data to the staging datasets before calculating results for changed days. Use an incremental reload when only new data has arrived, rather than a full reload that recomputes everything or a metric reload that restates a single metric. This is the recommended way to load active experiments, and works best for ongoing, daily loads, especially when datasets are large. ================================================================================ # Metric Reloads URL: https://docs.statsig.com/statsig-warehouse-native/features/metric-reloads Updated: 2025-09-18 ================================================================================ # Metric Reloads Metric reloads drop all data from staging pipelines associated with a metric and restate that data completely. Where this data is interconnected (for example, ratios and funnels), Statsig updates related entities as well. Use a metric reload when you add a metric or a metric definition changes, rather than a full reload that recomputes everything or an incremental reload that appends new data. A metric reload saves time by avoiding the reload of unrelated experiment metrics. ================================================================================ # Scheduled Reloads URL: https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/scheduled-reloads Updated: 2025-09-18 ================================================================================ # Scheduled Reloads ## How scheduled reloads work Scheduled reloads refresh the data behind your Metrics and Experiments from your warehouse on a daily cadence. Control these reload settings on each entity, or set project-level defaults that entities inherit from in your Project Settings. You can also use the Console API to [trigger experiment result loads](https://docs.statsig.com/console-api/introduction#post-/experiments/-experiment_id-/load_pulse). The Console API is useful for triggering refreshes when your data pipelines are ready. ### Reload schedules and exposure forwarding Scheduled reloads refresh experiment results. They may also forward recent exposures before the daily export, but these updates are best-effort and can be incomplete. The daily exposure export runs separately from results reloads and is the authoritative record of eligible forwarded exposures. Changing the reload schedule doesn't change forwarding eligibility or backfill the forwarded exposures table. For details, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). ## Gate/experiment Pulse scheduling For feature gates and experiments, you can configure individual Pulse scheduling separately from the project-level settings. Schedule daily Pulse metric reloads for individual feature gates and experiments. To access this feature: 1. Navigate to your feature gate/experiment in the Statsig Console 2. Go to the Pulse Results tab 3. Use the scheduling controls to configure daily reloads The scheduling allows you to: - Set a daily reload time in UTC - Choose between Full and Incremental reload types - Save, edit, or cancel scheduled reloads > **Note:** > > Experiments with a secondary ID type support Full reloads only. An Incremental schedule on these experiments won't run. Individual Pulse scheduling requires gates with partial rollout rules and overrides project-level settings. ## Review scheduled reloads across the project _Settings > Data Connection > Reload Settings_ has a _Scheduled Reloads_ section that lists the experiments and feature gates carrying a reload schedule in one table, instead of making you open each entity's Pulse Results tab. Use it to find the hours your reloads cluster into and to move entities off a crowded slot. Spreading start times keeps the pipeline from firing a burst of concurrent queries at your warehouse. A Type column marks each row as an experiment or a gate. Experiments that inherit the project-default schedule appear alongside entities with their own schedule, and the duration column fills in for experiments only. Gate rows link out to that gate's diagnostics. To change a schedule from the table: 1. Go to _Settings > Data Connection > Reload Settings_. 2. Find the entity in the _Scheduled Reloads_ table. 3. Click **Edit** on that row. The _Edit Scheduled Reloads_ modal opens with the entity's current settings. 4. Adjust the schedule, then save. Edit one entity at a time. The table has no multi-select or bulk schedule change. **Edit** is unavailable when you lack permission to change the entity, when a review is in progress for it, or when creation validation is still pending. The button's tooltip names the reason. ### What the table includes An entity appears in _Scheduled Reloads_ when it has a schedule and meets its type's conditions: - **Experiments**: in progress, not archived, and passing the Warehouse Native reload lifecycle checks. - **Feature gates**: enabled, not archived, and running a partial rollout. Everything else stays out, so treat the table as a view of active schedules rather than a complete inventory of the project: - Experiments that are unstarted or in draft, stopped, ended, launched, decided, abandoned, or archived. - Feature gates that are disabled, archived, or fully rolled out. - Dynamic configs, metrics, and holdouts, none of which ever appear. Editing a schedule here changes when the scheduler starts an entity's reload. It doesn't change how the scheduler runs that reload. ================================================================================ # Pipeline Overview URL: https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview Updated: 2025-09-18 ================================================================================ # Pipeline Overview Statsig Warehouse Native runs a pipeline in your warehouse that turns raw exposure and metric data into experiment results, from identifying users' first exposures through calculating group-level summary statistics. Pipeline Overview names the artifacts Statsig provisions to describe that pipeline: the `pipeline_overview` table in your warehouse, the metric source built on it, and the dashboard that charts it. To check whether individual pipeline runs are succeeding right now, go to [Pipeline Activity](https://docs.statsig.com/statsig-warehouse-native/warehouse-management/pipeline-activity) in the Statsig Console. ## Automatic setup When you create a warehouse connection, Statsig provisions the Pipeline Overview for you. During connection creation, Statsig creates the `pipeline_overview` table, the Pipeline Overview metric source, and the linked Pipeline Overview dashboard. This runs automatically and needs no action from you. Automatic setup applies to all supported warehouses, including Amazon Athena, Snowflake, BigQuery, Redshift, and Databricks. ## Main steps The main steps in the pipeline are: - Identifying users' first exposures - Annotating Metric Sources with exposure data - Creating metric-user-day level staging data - Running intermediate rollups for better performance - Calculating group-level summary Statistics ![Statsig runs the analysis pipeline inside your warehouse in five steps: it creates or updates cumulative exposures from the filtered exposure source, joins each filtered Metric Source to those exposures, calculates user-day metric values into staging tables, runs intermediate rollups, then calculates results and writes Pulse result tables. Only two outputs leave your warehouse for Statsig Storage: the exposure timeseries and the Pulse result tables.](https://docs.statsig.com/images/diagrams/whn-analysis-pipeline.svg) ![Statsig runs the analysis pipeline inside your warehouse in five steps: it creates or updates cumulative exposures from the filtered exposure source, joins each filtered Metric Source to those exposures, calculates user-day metric values into staging tables, runs intermediate rollups, then calculates results and writes Pulse result tables. Only two outputs leave your warehouse for Statsig Storage: the exposure timeseries and the Pulse result tables.](https://docs.statsig.com/images/diagrams/whn-analysis-pipeline.dark.svg) ## Types of DAGs Statsig lets you run your pipeline in a few different ways: - A **Full Refresh** totally restates the experiment's data and calculates it from scratch. This is useful for starting an experiment, or if underlying data has changed. - An **Incremental Refresh** appends new data to your experiment data. This reduces the cost of running scheduled updates to your results. - A **Metric** refresh lets you update a specific metric in case you changed a definition, or want to add new metrics to your analysis. ## Artifacts and entity relationships Statsig generates and stores the following tables in your warehouse per-experiment. You have full access to these data sources for your own analysis, models, or visualizations. For experiments, `experiment_id` is the name of the experiment; for Feature Gates, `experiment_id` is the name of the gate along with the specific rule ID (for example, `chatbot_llm_model_switch_31e9jwlgO1bSSznKntb2gp_exposures_summary`). This isn't an exhaustive list, but it includes most of the core result and staging tables useful for your own analysis. > **Note:** > > These are internal tables and change as the product evolves. Statsig documents changes here. | Table | Description | Notes | | --- | --- | --- | | `first_exposures_<experiment_id>` | Deduplicated and stitched (for experiments with ID resolution) first exposure events | Useful for ad-hoc analysis | | `exposures_summary_<experiment_id>` | Timeseries of exposures per group for display in Pulse | | | `unit_day_metrics_<experiment_id>` | User-day level metric aggregations table | Useful for ad-hoc analysis | | `unit_covariate_metrics_<experiment_id>` | User-level pre-experiment aggregations for regression adjustment/CUPED | | | `funnel_events_<experiment_id>` | Staging table for running funnel analysis | | | `percentile_values_<experiment_id>` | Staging table for running percentile analysis | | | `distinct_values_<experiment_id>` | Staging table for running count distinct analysis | | | `windowed_metrics_<experiment_id>` | Staging table for generating running totals when restating Pulse | | | `ratio_aggregations_<experiment_id>` | Staging table for generating running totals when restating Pulse | | | `results_<rollup>_<experiment_id>` | Outputs of Statistical Analysis for different rollups (e.g. daily, days-since-exposure, cumulative, 7-day). Exported to Statsig | Pulse inputs - useful for replicating Statistical analysis | | `ratio_results_<rollup>_<experiment_id>` | Outputs of Statistical Analysis for ratio metrics in different rollups (e.g. daily, days-since-exposure, cumulative, 7-day). Exported to Statsig | Pulse inputs - useful for replicating Statistical analysis | The high-level relationships and contents of these tables appear in the entity relationship diagram below. Refer to the Main steps diagram above for scheduling details. ![The pipeline turns two tables you provide, an assignment source and a metric source, into experiment results. The assignment source is deduplicated into FIRST_EXPOSURES, which both rolls up into the EXPOSURES_SUMMARY timeseries and, together with the metric source, feeds the METRIC JOIN and FUNNEL JOIN stages. Those joins produce the UNIT_DAY_METRICS and FUNNEL_EVENTS staging tables, which roll into WINDOWED_METRICS by windowed aggregation and then up to the group_id level into the final RESULTS table.](https://docs.statsig.com/images/diagrams/whn-pipeline-data-model.svg) ![The pipeline turns two tables you provide, an assignment source and a metric source, into experiment results. The assignment source is deduplicated into FIRST_EXPOSURES, which both rolls up into the EXPOSURES_SUMMARY timeseries and, together with the metric source, feeds the METRIC JOIN and FUNNEL JOIN stages. Those joins produce the UNIT_DAY_METRICS and FUNNEL_EVENTS staging tables, which roll into WINDOWED_METRICS by windowed aggregation and then up to the group_id level into the final RESULTS table.](https://docs.statsig.com/images/diagrams/whn-pipeline-data-model.dark.svg) ## Other jobs Alongside and inside this main flow, Statsig also: - Runs Health Checks and a Summary View for exposures - Calculates top dimensions for dimensional metrics - Calculates funnel steps - Runs CUPED and Winsorization procedures during the group-level summaries to reduce variance and outlier influence - Calculates inputs to the Delta Method to avoid bias on Ratio and Mean metrics Statsig generates experiment-level tables, making it easy to run follow-up analyses on specific experiments. ## Visibility Select the history icon on your pulse results to see the jobs and IDs Statsig ran for each pulse reload, along with compute time and cost. This information is also visible in your warehouse's own history and usage management. Having the costs in the console is useful for cross-functional experimentation teams running the analysis. ## Exposure export table Statsig records eligible production first exposures in the forwarded exposures table configured in your warehouse Data Connection. The daily export is the authoritative record. Results reloads may forward recent exposures earlier, but these updates are best-effort and can be incomplete. The daily export may replace them. By default, the daily export excludes experiment groups at 0% or 100% traffic share. This is the group split, not the experiment's overall allocation. If you need these experiment exposures, contact Statsig Support. For feature gates at 0% or 100% rollout, turn on the project and per-gate settings below. For forwarding requirements, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). > **Info:** > > To record exposures for a feature gate at 0% or 100% rollout: > > 1. A project admin goes to _Settings > Project Configuration > Feature Management_ and turns on **Enable exposure tracking for 0/100% rolled out Gates**. > 2. On each gate that needs these exposures, turn on **Store 0/100 Exposures**. > > Statsig bills these exposures as analytic events. For experiment variants with 0% or 100% traffic allocation, contact Statsig Support. | Column Name | Data Type | Description | | --- | --- | --- | | experiment\_id | string | The identifier for the gate/experiment | | group\_id | string | groupID for experiments; ruleID+Pass/Fail for gates | | group\_name | string | Name of the experiment group (e.g. Control vs Test) | | user\_id | string | The ID passed in as the Statsig userID | | stable\_id | string | Statsig Client SDK managed stable device identifier | | \[your custom ids\] | string | One column for every custom unitID you use on Statsig | | timestamp | timestamp | Timestamp of the first exposure | | user\_dimensions | object | Warehouse specific object with all the user dimensions | Statsig populates `user_dimensions` in the daily deduplicated export. Fast-forwarded exposure rows can omit some fields in this object until the next daily load. ### Common fields in user\_dimensions `user_dimensions` contains user attributes captured alongside the first exposure. The exact shape can vary by SDK and project configuration, but these are some of the most common fields you may see: | Field | Description | Notes | | --- | --- | --- | | `os` | Normalized operating system name | Canonical OS field on the exposure side. | | `os_version` | Operating system version | Derived from SDK metadata or user agent parsing. | | `browser_name` | Browser name | Derived from SDK metadata or user agent parsing. | | `browser_version` | Browser version | Derived from SDK metadata or user agent parsing. | | `device_model` | Device model | Forwarded or inferred when available. | | `ip` | IP address | Present when available from the SDK or request context. | | `country` | Country | Derived from request context or IP lookup. | | `locale` | Locale | Forwarded or inferred when available. | | `language` | Language | Forwarded or inferred when available. | | `appVersion` | Application version | Forwarded when present on the SDK user object. | | `sessionID` | Session identifier | Forwarded when present on the SDK user object. | | `appIdentifier` | Application identifier | Forwarded when present on the SDK user object. | Additional non-null fields from the SDK user object may also appear in `user_dimensions`. Statsig typically exports custom IDs as dedicated top-level columns in the exposure table rather than querying them from this object. Statsig uses input fields such as `deviceOS` and `systemName` to derive the exported `os` field. If you want to analyze operating system on forwarded exposures, query `user_dimensions.os`. ## Event export table If you log custom events through a Statsig SDK, Statsig also forwards those events into a configurable table in your warehouse. This is the table used when Warehouse Native customers rely on Statsig SDK logging for outcome events. - Use `user_object` for user fields associated with the event. - Use `statsig_metadata` for SDK and exposure-processing metadata. - Use `company_metadata` for the event metadata payload you logged. | Column Name | Data Type | Description | | --- | --- | --- | | user\_id | string | The ID passed in as the Statsig userID | | stable\_id | string | Statsig Client SDK managed stable device identifier | | \[your custom ids\] | string | One column for every custom unitID you use on Statsig | | timestamp | timestamp | Event timestamp | | event\_name | string | Name of the logged custom event | | event\_value | string | Optional event value | | user\_object | object | Warehouse specific object containing user fields associated with the event | | statsig\_metadata | object | Warehouse specific object containing Statsig SDK and exposure metadata | | company\_metadata | object | Event metadata payload logged with the event | ### Common fields in user\_object `user_object` contains user fields associated with the event. It often includes the same common fields as `user_dimensions`, plus any additional non-null fields sent on the SDK user object. | Field | Description | Notes | | --- | --- | --- | | `os` | Normalized operating system name | Canonical OS field on the event-side user object. | | `os_version` | Operating system version | Derived from SDK metadata or user agent parsing. | | `browser_name` | Browser name | Derived from SDK metadata or user agent parsing. | | `browser_version` | Browser version | Derived from SDK metadata or user agent parsing. | | `device_model` | Device model | Derived from `deviceModel` when provided. | | `ip` | IP address | Present when available from the SDK or request context. | | `city` | City | Added when geographic inference is available. | | `state` | State or region | Added when geographic inference is available. | | `country` | Country | Derived from request context or IP lookup. | | `locale` | Locale | Forwarded or inferred when available. | | `language` | Language | Forwarded or inferred when available. | | `appVersion` | Application version | Forwarded when present on the SDK user object. | | `sessionID` | Session identifier | Forwarded when present on the SDK user object. | | `appIdentifier` | Application identifier | Forwarded when present on the SDK user object. | ### Common fields in statsig\_metadata `statsig_metadata` contains SDK-level and exposure-processing metadata associated with the event. These are some of the most common customer-facing fields: | Field | Description | Notes | | --- | --- | --- | | `deviceType` | High-level device category | Derived from the normalized OS, for example `Desktop` or `Mobile`. | | `targetAppID` | Target app identifier | SDK target app metadata. | | `statsigTier` | Statsig environment tier | For example `prod` or `staging`. | | `keyEnvironment` | SDK key environment | Environment associated with the SDK key. | | `keyID` | SDK key identifier | Useful for debugging ingestion and environment issues. | | `samplingRate` | Event sampling rate | Present when the event is sampled. | | `is_bot` | Bot classification | Set when Statsig classifies the event as bot traffic. | | `billing_type` | Exposure billing classification | Common on exposure-related events. | | `groupID` | Experiment group identifier | Common on exposure-related events. | | `ruleID` | Rule identifier | Common on exposure-related events. | | `continuous_rollout_id` | Continuous rollout identifier | Present for continuous rollout exposures. | | `configExposureType` | Exposure config type | For example `dynamic_config` or `experiment`. | | `isSwitchback` | Switchback flag | Present when the exposure is associated with a switchback experiment. | | `is_autotune` | Autotune flag | Present when the exposure is associated with an autotune experiment. | Other SDK debugging and exposure-processing metadata may also appear in `statsig_metadata`. ### What goes in company\_metadata `company_metadata` stores the metadata payload logged with the event. This object doesn't have a fixed schema and varies based on the event and your SDK usage. Most event-specific business context, such as `price`, `currency`, `category`, `plan`, `screen`, `route`, or nested objects like `cart`, `items`, and `context`, appears here. ================================================================================ # Read Results URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/read-results ================================================================================ # Read Results ## Read experiment results The **Results** tab shows your experiment's hypothesis, an **Exposures** chart, and a **Scorecard** of metric lifts. Open it to read and interpret how each variant performed. ### Exposures ![Exposures chart showing cumulative users per experiment group](https://docs.statsig.com/images/snippets/pulse/read-results/7a80e74e-140d-4c36-a78e-c9b626e1fee5.png) At the top of the Results page is the Exposures Chart. Exposures are the unique experimental units enrolled in the experiment. This is typically the number of unique users; for device-level experimentation, this is the number of devices. The timeline shows when the experiment started and how many exposures Statsig enrolled on each day. Use the chart to see the rate at which Statsig added users into each group and the total number of users exposed. You can also confirm whether the target ratio matches what you configured in experiment setup. ### Scorecard The experiment **Scorecard** shows the metric lifts for all Primary and Secondary metrics you set up at experiment creation. #### Immediately post-experiment start For up to the first 24 hours after starting your experiment (before the daily metric results run), Statsig calculates the **Scorecard** section hourly. This applies to Statsig Cloud only; for WHN projects you must reload results on demand or set up a daily schedule. This near-real-time scorecard lets you confirm that Statsig calculates exposures and metrics as expected and debug your experiment or gate setup if needed. > **Note:** > > Do **not** make experiment decisions based on real-time results data in this first 24-hour window after experiment start. Make decisions only after the experiment reaches its target duration, which your primary metrics determine by reaching experimental power. For more about target duration, go to [target duration](https://docs.statsig.com/experiments/setup/analysis-settings#target-duration). Because data in this early post-experiment window supports diagnostics rather than decision-making, there are a few key differences from the results shown after daily runs begin: - Metric lifts don't have confidence intervals - No time-series view of metric trends - No projected topline impact analysis - No option to apply more advanced statistical tactics, such as CUPED or Sequential Testing All of these are available in daily Results, which start showing in the next daily run. #### Post-first day scorecard ![Experiment scorecard table displaying metric lifts and confidence intervals](https://docs.statsig.com/images/snippets/pulse/read-results/8b855f5c-d26f-4185-ac31-5108fbebe18e.png) The experiment Results daily run calculates the difference between comparable randomization groups (for example, test and control) across your organization's suite of metrics. The daily run then applies a statistical test to the results. For more about Statsig's stats engine, go to [the stats engine documentation](https://docs.statsig.com/experiments/statistical-methods/introduction). For every metric, Statsig shows: - The calculated relative difference (Delta %) - The confidence interval - Whether the result is statistically significant - Positive lifts are green - Negative lifts are red - Non-significant results are grey The formula for calculating lift is: Delta(%) = (Test - Control) / Control Statsig reports confidence intervals at the selected significance level (95% by default). In a typical two-sided Z-test, Statsig shows the confidence interval as +/- 1.96 \* standard error. Statsig automatically applies 99.9% winsorization to event\_count, event\_count\_custom, and sum metrics. Winsorization caps extreme outlier values to reduce their impact on experiment results. For metrics added to the **Scorecard** or **Monitoring Metrics** sections of your experiment or gate, you can also apply optional statistical treatments. Examples include CUPED (pre-experiment bias reduction) and sequential testing adapted confidence intervals. For more details, go to [the stats engine documentation](https://docs.statsig.com/experiments/statistical-methods/introduction). - **Statsig computes experiment results for the first 90 days**: By default, Statsig computes experiment results for only the first 90 days of your experiment. You receive an email notification as you approach the 90-day limit, at which point you can extend the compute window by another 30 days at a time. If the experiment runs beyond the compute window, Statsig stops adding new users to the experiment's results. Analysis for existing exposed users continues until you make a decision on the experiment. > **Note:** > > This experiment result calculation window only affects whether Statsig includes a user in the experiment's analysis, and doesn't affect the treatment each user receives. New users still receive the experience for the group Statsig randomizes them into. ### Experiment results views Statsig offers the following views for Scorecard metric lifts: - **Cumulative results (default view)**: Displays the aggregate difference between experiment groups and visualizes the corresponding confidence intervals. - **Table view**: Displays the same data as the cumulative view but in a table format with additional fields. - **Daily results**: Shows the difference between experiment groups aggregated based on days since start of experiment. - **Days since exposure**: Shows the difference between experiment groups aggregated based on days since exposure to the experiment. Cumulative results includes a detailed view on hover, where you can additionally view the raw statistics used in the metric lift calculations, as well as topline impact. ![Cumulative results view with hover details](https://docs.statsig.com/images/snippets/pulse/read-results/856c7750-df56-45d9-b253-6b63f336cac7.png) ### Dimensions There are two ways to break down a Scorecard metric: by a **User Dimension** or by an **Event Dimension**. #### User dimensions User Dimensions refer to user-level attributes that are either part of the user object you log, or additional metadata that Statsig extracts. Examples of these user attributes include operating system, country, and region. You can create [custom "explore" queries](https://docs.statsig.com/experiments/interpreting-results/custom-queries) to _filter on_ or _group by_ available user dimensions. For example, view results for users in the US, or results for iOS users grouped by country. Go to the "explore" tab to create a custom query. ![custom queries](https://docs.statsig.com/images/snippets/pulse/read-results/e3afb526-8f9d-465e-af33-ea9575ac69e7.png) #### Event dimensions Event Dimensions refer to the value or metadata logged as part of a custom event used to define the metric. To view results for a metric broken down by categories specific to that metric, [specify the dimension](https://docs.statsig.com/metrics/metric-dimensions) in the **value** or **metadata** attributes when you log the source event. For example, when you log a "click" event on your web or mobile application, you can log the target category using the **value** attribute. Statsig automatically generates results for each category in addition to the top-level metric. To see breakdowns for all categories within a metric, click on the (+) sign next to the metric. ![dimension button](https://docs.statsig.com/images/snippets/pulse/read-results/65cbe2a0-d269-4385-a606-c825ff2e8e05.png) ![dimension results view](https://docs.statsig.com/images/snippets/pulse/read-results/f557dac6-e29f-4cb5-bd6a-19fc2b226193.png) ### Significance level settings You can adjust these settings at any time to view Scorecard results with different significance levels. - **Apply Benjamini-Hochberg Procedure per Variant**: Select this option to reduce the probability of false positives by adjusting the significance level for multiple comparisons. Go to [Benjamini-Hochberg Procedure](https://docs.statsig.com/experiments/statistical-methods/methodologies/benjamini-hochberg-procedure) for details. - **Confidence Interval**: Changes the confidence interval displayed with the metric deltas. Choose a lower confidence interval (for example, 80%) when you have higher tolerance for false positives and prefer fast iteration with directional results over longer experiments with greater certainty. - **CUPED**: Toggle CUPED on or off using the inline settings above the metric lifts. This setting applies only to **Scorecard** metrics; Statsig doesn't apply CUPED to non-Scorecard metrics. - **Sequential Testing**: Applies a correction to p-values and confidence intervals to reduce false positive rates when evaluating results before the target completion date of the experiment. This mitigates the increased false positive rate associated with the "peeking problem". Toggle **Sequential Testing** on or off using the inline settings above the metric lifts. This setting works only for experiments with a set target duration. ![analysis settings](https://docs.statsig.com/images/snippets/pulse/read-results/d2d7405a-9e86-4317-8f32-51b369c66699.png) ### Restarting results ![Restart results banner](https://docs.statsig.com/images/snippets/pulse/read-results/201ab314-9304-43f1-bc11-58dcf9394aa2.png) If your experiment has stopped computing results, you can resume updates by selecting the Restart button. Before restarting, review the following: - A Restart isn't a [Reset](https://docs.statsig.com/experiments/ending/reset). A Restart doesn't re-randomize units in your experiment, and all users continue to receive the same group assignments. - Statsig begins computing experiment results from the restart point, so metric results start over. Old results may still appear in time series and explore query views, but Statsig doesn't carry them forward or update them. - The Cumulative Exposures chart updates based on new exposures, but the duration of the pause in computations affects whether the chart starts from zero or retains past exposure counts. Avoid restarting results by actively extending experiments while they are running. Monitor email alerts from Statsig and check your experiments regularly. ================================================================================ # Metric Drill-Down URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/metric-drill-down ================================================================================ # Metric Drill-Down ## Metric tooltip A tooltip with key statistics and additional detail appears when you hover over a metric in Pulse. ![UI for metric hover card in experiments](https://docs.statsig.com/images/metric_hover_card.png) - **Group**: The name of the group of users. For Feature Gates, the "Pass" group is considered the test group while the "Fail" group is the control. In Experiments, these are the variant names. - **Units**: The number of distinct units included in the metric. E.g.: Distinct users for user\_id experiments, devices for stable\_id experiments, etc. - **Mean**: The average per-unit value of the metric for each group. - **Total**: The total metric value across all units in the group, over the time period of the analysis. ### Calculation details | Metric Type | Total Calculation | Mean | Units | | --- | --- | --- | --- | | event\_count | Sum of events (99.9% winsorization) | Average events per user (99.9% winsorization) | All users | | event\_user | Sum of event DAU (distinct user-day pairs) | Average event\_dau value per user per day. Statsig calls this "Event Participation Rate" because it represents the probability a user is DAU for that event. | All users | | ratio | Overall ratio: sum(numerator values)/sum(denominator values) | Overall ratio | Participating users | | sum | Total sum of values (99.9% winsorization) | Average value per user (99.9% winsorization) | All users | | mean | Overall mean value | Overall mean value | Participating users | | user: dau | sum of daily active users | Average metric value per user per day. The probability that a user is DAU | All users | | user: wau, mau\_28day | Not shown | Average metric value per user per day. The probability that a user is xAU | All users | | user: new\_dau, new\_wau, new\_mau\_28day | Count of distinct users that are new xAU at some point in the experiment | Fraction of users that are new xAU | All users | | user: retention metrics | Overall average retention rate | Overall average retention rate | Participating users | | user: L7, L14, L28 | Not shown | Average L-ness value per user per day | All users | ### p-value In null hypothesis significance tests, the p-value is the probability that such an extreme difference arises by random chance when the experiment has no effect. A low p-value means the observed difference is unlikely to be due to random chance. In hypothesis testing, a p-value threshold determines which results reflect a real effect and which are plausibly due to random chance. ([p-value calculation](https://docs.statsig.com/experiments/statistical-methods/p-value)) ### Reverse power Reverse power is the smallest effect size that an experiment can reliably detect in its current state (some studies refer to this value as ex-post MDE). Statsig calculates it from the sample size and standard error of the control group. Reverse power does not depend on the observed effect size. In practice, reverse power answers questions such as: given how the test performed, what is the smallest effect detectable with sufficient power (typically 80%)? For a two-sided test, Statsig computes the reverse power for a given metric X using the following equation: $$ Reverse Power = \frac{(Z_{1-\beta} + Z_{1-\alpha/2})}{\overline{X}_{\text{control}}}\times \sqrt{\frac{\mathrm{var}(\Delta \overline{X})}{N_{\text{control}}}} \times 100\% $$ For a one-sided test, Statsig computes the reverse power for a given metric X using the following equation: $$ Reverse Power = \frac{(Z_{1-\beta} + Z_{1-\alpha})}{\overline{X}_{\text{control}}}\times \sqrt{\frac{\mathrm{var}(\Delta \overline{X})}{N_{\text{control}}}} \times 100\% $$ - $\overline{X}_{\text{control}}$ is the mean metric value across control users - $\mathrm{var}(\Delta \overline{X})$ is the population variance of delta - $N_{\text{control}}$ are the observed number of units in the control group - $Z_{1-\beta}$ is the standard Z-score for the selected power. Typically $1-\beta$ = 0.8 and $Z_{1-\beta}$ = 0.84 - $Z_{1-\alpha/2}$ and $Z_{1-\alpha}$ are the standard Z-scores for the selected significance level in a two-sided test and in a one-sided test. Reverse power is an optional feature. To manage it, go to _Settings > Product Configuration > Experimentation > Organization_ and toggle it on or off. ## Detailed view Click **View Details** to access in-depth metric information. The detailed view contains three sections: - **Time Series**: How the metrics evolve over time - **Raw Date**: Group level statistics - **Impact**: How the experiment impacts the metric ### Time series In this view, select and drag to zoom in on different time ranges. Three types of time series are available in the drop-down: **Daily**: The metric impact on each calendar day without aggregating days together. This is useful for assessing day-over-day metric variability and the impact of specific events. The daily view is the recommended time series view for Holdouts, because it highlights the impact over time as new features are launched. ![Daily metric impact visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/f42453a6-e413-47d5-b176-bb3e9b49a915.png) **Cumulative**: Shows the cumulative metric impact from the start of the experiment over time. This is useful for observing trends and seeing how your confidence interval changes over time. ![Cumulative metric lift visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/b2e9aea9-98fb-4e29-bccf-abae356d0173.png) **Days Since Exposure**: Shows the metric impact based on how long a user has been in the experiment. Daily data for each user is aligned by the day they entered the experiment (Day 0, Day 1, etc.), not by calendar date. This alignment lets you distinguish early (novelty) effects from long-term effects. This view also shows pre-experiment data, which identifies biases between groups before the experiment started. Such biases can result from random chance or from an issue in the random assignment process. ![Days since exposure metric visualization interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/17eeb054-43d8-424c-b43a-85c682bfcfb8.png) ### Raw data This view shows the group-level statistics needed to compute the metric deltas and confidence interval. It includes Units, Mean, and Total (defined in the Metric Tooltip section above), as well as the Standard Error of the mean (Std Err). For details on the statistical calculations, go to the [stats engine documentation](https://docs.statsig.com/experiments/statistical-methods/introduction). ### Impact ![Experiment impact metrics interface](https://docs.statsig.com/images/snippets/pulse/metric-drill-down/171754168-624f740e-bdd6-46ea-a2e3-8d70e637ff75.png) - **Experiment Delta (absolute)**: The absolute difference of the Mean between test groups i.e. Test Mean - Control Mean. Statsig shows the p-value to indicate whether the observed absolute difference is statistically significant. - **Experiment Delta (relative)**: Relative difference of the Mean i.e. 100% x (Test Mean – Control Mean) / Control Mean. - **Topline Impact**: The measured effect that the experiment has on the overall topline metric each day, on average. Statsig computes this daily and averages it across days in the analysis window. The absolute value is the net daily increase or decrease in the metric; the relative value is the daily percentage change. - **Projected Launch Impact**: An estimate of the daily topline impact expected if you make a decision and launch the test group to all users. This accounts for the layer allocation and the size of the test group. This assumes the targeting gate (if there is one) remains the same after launch. Go to [topline impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact) for details on the exact calculation for topline and projected impact. #### FAQs about topline impact _Why is the projected launch impact smaller than the relative experiment delta?_ An experiment may affect only a subset of the user base that contributes to a topline metric. The relative experiment delta is therefore diluted when measured against the topline metric value. For example: consider a top-of-funnel experiment on the registration page. Among users who visit that page, the treatment leads to more sign-ups and a 10% lift in daily active users (DAU). The topline DAU metric includes other user segments outside the experiment, such as long-term users who don't visit the registration page. A 10% lift in the test vs. control comparison may therefore amount to only a 1% increase in overall DAU. _How can the topline impact be higher than the experiment delta?_ The topline impact can be higher or lower than the experiment delta because Statsig computes the two values differently and they have different meanings. Experiment deltas are based on unit-level averages: the mean metric value is computed for each user across all days, then averaged to get the group mean. The topline impact is computed daily based on the total pooled effect from all users, averaged across days to show the daily impact. Statsig computes topline impacts this way because most metrics are tracked daily and the topline value is typically an aggregation across all users, not a user-level average. For experiment analysis, best practice is to match the analysis unit to the randomization unit, so metrics are aggregated at the unit level before computing experiment deltas. ================================================================================ # Custom "Explore" Queries URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/custom-queries ================================================================================ # Custom "Explore" Queries Custom queries run additional experiment analyses on your existing data beyond what's in your main Results tab. Use them to gain deeper insights from experiments and feature rollouts, debug interesting results, or scope results to specific sub-groups. Custom queries let you filter or group metrics by event or user dimensions. You can also filter to a specific set of users to see how an experiment or launch affected those users. Custom queries are experimental analyses, and all the same statistical procedures apply as in the main Results tab. Statsig computes results as p-values and confidence intervals for your metric deltas. You can also use advanced statistical methods like [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) and [Sequential Testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing). > **Warning:** > > Use caution when drawing inferences from Custom Queries, especially when grouping by a dimension with many options. This increases the chance of a false-positive statistically significant result. ### Dimension loading timing for precomputed user dimensions When viewing results for precomputed user dimensions (which you configure and run on a schedule), Statsig loads these dimensions through separate asynchronous explore queries. This means: - The main experiment results appear first. - Precomputed dimensions continue loading in the background and appear within a few minutes. - This timing gap is most noticeable immediately after the first reload of the day. - If you see "No dimensions available for this time range" for precomputed dimensions, wait a few minutes and refresh to check whether dimensions have finished loading. > **Note:** > > This timing behavior only affects precomputed user dimensions that run on a schedule. User-triggered custom queries don't experience this asynchronous loading delay. ### Running a custom query To run a custom query, go to the **Explore** tab within your experiment. ![Custom query explore tab interface](https://docs.statsig.com/images/snippets/pulse/custom-queries/b2737ba1-dbf4-4235-a806-afea5dfe9a78.png) Custom Query fields: - **Metric(s)**: The metric(s) you want to analyze. You can select a single metric, a few metrics, or a Metric Tag. Adding a Tag includes all the metrics within that Tag in your Custom Query. There are three "default" metric selections included as shortcuts: - "Scorecard Metrics", all metrics included in your experiment setup's Primary and Secondary Metrics sections - "Primary Metrics" - "Secondary Metrics" - **Metric Filter**: With metrics selected, you can filter metrics by either Event or User dimensions using the "Add Filter" dropdown. For example, to view experiment results for Canadian users only, filter to "Country = CA". ![Metric filter dropdown selecting Country equals CA](https://docs.statsig.com/images/snippets/pulse/custom-queries/f56b4259-4d18-44d1-9646-9d7aa2f8f847.png) - **Group By**: You can group your custom query results by either an Event or User dimension. You can apply custom query filters at the per-metric level. The Group By action is at the query level, so all included metrics have the Group By you select applied to them. - **Time Range for Metric Data**: The date range you're running your analysis on. By default this is the "Full date range" of your experiment data. - **(Advanced) ID List Segment filters**: You can choose an ID-list based [Segment](https://docs.statsig.com/segments/overview), and Statsig calculates your results only for users in that segment. This is useful when you didn't log an important user dimension to filter on, or when you only need results for a sub-population defined in your own data warehouse. - This option can easily lead to erroneous and biased results. You must define the segment based on the user's status before their exposure to the experiment or feature gate. - You can also choose to exclude a certain ID list segment. For example, exclude users you've retroactively identified as bad actors from your lifts analysis. - **(Advanced) Filter by Exposure Date**: You can also filter the results by Exposure Date for more flexibility. You can include or exclude a date range, or in WHN, include/exclude users based on their first exposure to the experiment. - This is useful when your metrics have a novelty effect, delayed impact, or when you need to filter results to specific users. Use it cautiously because it can lead to biased results. > **Note:** > > User groups in experiment results are based on first-touch attribution. Filters and grouping are based on the user attributes collected at the time of first exposure in the gate/experiment/layer check. ![Custom query definition form showing selected metrics and filters](https://docs.statsig.com/images/snippets/pulse/custom-queries/85264260-2f65-4bfd-b4e1-477bd043b87d.png) ### Viewing a custom query in Explore These queries take a few minutes to run. After the query completes, Statsig sends an email notification and the results appear in the **Query History** section of the _Explore_ interface. Statsig stores all historical queries across your team there. You can assign a display name to a query inline for easier future identification. ![Explore tab query history list](https://docs.statsig.com/images/snippets/pulse/custom-queries/46574581-604e-4d29-b231-fa51876c813d.png) ### Scheduling a custom query To get a daily refresh of a custom query, schedule it directly from the **Explore** tab. Create the custom query, then select the "..." menu, then **Schedule**. The custom query runs daily and appears in the **Scheduled** tab of your Metric Lifts. ![Scheduled custom queries tab displaying daily runs](https://docs.statsig.com/images/snippets/pulse/custom-queries/56d11b46-f2de-4569-89f7-b0a439910964.png) ![Scheduled query configuration interface](https://docs.statsig.com/images/snippets/pulse/custom-queries/fad0c8ce-3f9c-46be-a09c-52263e124259.png) ### Reviewing custom query results Custom query results resemble the main Results tab because the statistical methods are the same. The key difference is that a custom query result is a snapshot in time. After a query runs, Statsig saves the results and doesn't update them when more metric data arrives. To update results, run a new custom query or schedule custom queries to run on a regular cadence. #### Sequential testing and custom queries If you enable [Sequential Testing](https://docs.statsig.com/experiments/advanced-setup/sequential-testing) for your experiment, it applies to custom query results as well. The degree of adjustment to confidence intervals and p-values follows the standard sequential testing rules. If a custom query doesn't satisfy the experiment's target Days or Unique Exposures from your setup, Statsig applies sequential testing adjustments to account for the underpowered state of the experiment. Because custom queries are snapshots in time, sequential testing adjustments apply to that specific analysis only. Running additional custom queries with more or less data (for example, more days or more unique users) changes the adjustments accordingly. Custom queries that meet the configured minimum Days or Unique Exposures may have no sequential adjustments applied. ![Custom query results table displaying sequential testing adjustments](https://docs.statsig.com/images/snippets/pulse/custom-queries/df7c4087-82c3-41fb-8f5d-124094ec4526.png) ================================================================================ # Export Experiment Results to Your Warehouse in Warehouse Native URL: https://docs.statsig.com/experiments/interpreting-results/access-whn Updated: 2025-09-18 ================================================================================ # Export Experiment Results to Your Warehouse in Warehouse Native In Warehouse Native, Statsig writes two datasets to your warehouse: an exposures table with each unit's eligible first exposure per experiment, and a `statsig_daily_results` SQL View with every Scorecard metric lift and its metadata. Statsig writes exposures to the forwarding table you configure in your project, and writes a new copy of the Scorecard results to the SQL View each time you load an experiment. Use the SQL View to query results across experiments in your warehouse. Use the console's **Export Report** only when you need a one-time Pulse Summary CSV file, as described in [Report types](#report-types). ## Export experiment results to your warehouse ### Exposures Statsig writes exposures to the table configured in your project setup. To find the table's location, go to _Settings > Data Connection_. The table is at `{Database Name}.{Schema Name}.{Exposures Forwarding Table Name}`, for example `experimentation.statsig.exposures`. The daily export is the authoritative record of eligible first exposures in the forwarded exposures table. Results reloads may forward recent exposures earlier, but these updates are best-effort and can be incomplete. The daily export may replace them. An exposure in Diagnostics doesn't confirm that it qualifies for this table. For forwarding requirements, including the default exclusion for experiment groups at 0% or 100% traffic share, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). A full reload recalculates results; it doesn't rebuild or backfill the forwarded exposures table. ### Results The results SQL View contains the same results you can view in the console: experiment metadata (such as team, tags, target duration, and settings like CUPED and sequential testing), each metric's metadata (such as metric tags), and all metric lifts. To enable it, go to _Project Settings > Data Connection > Export_. Statsig then creates the SQL View in your warehouse and a matching metric source in your Statsig project. Each time you load an experiment, Statsig exports a new copy of the Scorecard metric results. To tell result versions apart, use the `ds` column, which contains the timestamp when Statsig wrote the data. ![Project settings data connection export interface](https://docs.statsig.com/images/experiments/interpreting-results/access-whn/0355e284-7e3f-40db-b441-fa2a00ccf3ab.png) ### Schema of the results export table The default view name is `statsig_daily_results`. The metric source that Statsig creates in your project has the same name. | Column | Type | Description | | --- | --- | --- | | `ds` | timestamp | The time when Statsig wrote the data | | `experimentName` | string | Name of the experiment | | `experimentCreator` | string | Creator of the experiment | | `experimentTeam` | string | Team conducting the experiment | | `experimentTags` | array of strings | Tags associated with the experiment | | `experimentStartTs` | number | Start timestamp of the experiment, in milliseconds | | `experimentEndTs` | number | End timestamp of the experiment, in milliseconds | | `targetExposures` | number | The target number of exposures for the experiment | | `targetDuration` | number | The target duration of the experiment | | `actualDuration` | number | The actual duration the experiment ran, from start date to decision date. For analyze-only experiments, the number of days from the configured start date to today | | `controlGroupName` | string | Name of the control group in the experiment | | `testGroupName` | string | Name of the test group in the experiment | | `useCUPED` | boolean | Whether the experiment applied CUPED | | `useSequential` | boolean | Whether the experiment applied sequential testing | | `metricName` | string | Name of the metric the experiment measures | | `metricType` | string | Type of metric | | `metricTags` | array of strings | Tags associated with the metric | | `higherIsBetter` | boolean | Whether a higher value of the metric is better | | `isVerifiedMetric` | boolean | Whether the metric is verified | | `metricTeam` | string | Team responsible for the metric | | `absoluteDelta` | number | The absolute change in the metric value between control and test groups | | `absoluteDeltaCI` | number | Confidence interval for the absolute delta | | `relativeDelta` | number | The relative change in the metric value between control and test groups | | `relativeDeltaCI` | number | Confidence interval for the relative delta | | `absoluteDeltaPValue` | number | P-value associated with the absolute delta metric result | | `toplineAbs` | number | The absolute topline metric value for the experiment | | `toplineAbsCI` | number | Confidence interval for the absolute topline metric | | `toplineRel` | number | The relative topline metric value for the experiment | | `toplineRelCI` | number | Confidence interval for the relative topline metric | | `projectedTopline` | number | Projected topline metric value based on current data | | `projectedToplineCI` | number | Confidence interval for the projected topline metric | | `projectedToplineRel` | number | Projected relative topline metric value based on current data | | `projectedToplineRelCI` | number | Confidence interval for the projected relative topline metric | | `controlUnits` | number | The number of control group units | | `testUnits` | number | The number of test group units | | `controlTotal` | number | Total value for the control group metric | | `testTotal` | number | Total value for the test group metric | | `controlMean` | number | The mean value for the control group | | `testMean` | number | The mean value for the test group | | `sequentialTestingAbsoluteDeltaCI` | number (optional) | Confidence interval for the absolute delta with sequential testing enabled | | `sequentialTestingRelativeDeltaCI` | number (optional) | Confidence interval for the relative delta with sequential testing enabled | | `sequentialTestingAbsoluteDeltaPValue` | number (optional) | P-value for the absolute delta with sequential testing enabled | ## Report types The report types in this section are the outputs of the console's **Export Report** action, described in [Exporting experiment result reports](https://docs.statsig.com/experiments/interpreting-results/export). There are three types: | Report | Contents | Files | Approximate size | | --- | --- | --- | --- | | Exposures | All exposed users and their first exposures. Use it to join on your own internal data, run custom queries in your own warehouse, or verify who was in the experiment, which group Statsig assigned them to, and when Statsig first exposed them. | `<experiment>_first_exposures.csv` | 1-25 MB | | Pulse Summary | Precomputed summary experimental data for all metrics and test groups, including everything visible on the Results tab. | `<experiment>_pulse_summary.csv` | 10-100 KB | | Raw Data | Raw exposures and metrics data at the user-day level, for inspecting data manually or recomputing your own statistics. | `<experiment>_first_exposures.csv` (the same file as the Exposures report) and `<experiment>_user_metrics.csv` (each user's calculated metrics for each day of their enrollment) | 10 MB-1 GB | In Warehouse Native, you can export only the Pulse Summary, because Statsig stores the other two types of data only [in your warehouse](https://docs.statsig.com/statsig-warehouse-native/analysis-tools/pipeline-overview/#artifacts-and-entity-relationships). Retention limits export availability: Statsig holds exposures data for up to 90 days after you conclude an experiment, and holds raw user-level metrics data for 90 days. ### Pulse Summary file description for feature gates | Column name | Description | | --- | --- | | `name` | Name of the experiment or feature gate | | `rule` | Name of the feature gate rule | | `metric_type` | Category of the metric. Statsig computes different metric types differently, including how it computes them on the Results tab | | `metric_name` | The name of the metric. For event metrics, this is the name of the event | | `metric_dimension` | The subcategory of the metric. For example, if you log `value` in LogEvent, then `value` shows up as a subdimension. `dimension = !statsig_topline` indicates that this row reflects an aggregate across all dimensions | | `start_date` | The start date for this measurement | | `end_date` | The end date for this measurement | | `test_units` | The number of users in the test group | | `test_mean` | The average value of this metric across test users (or participating units when applicable) | | `test_stderr` | The standard error for the estimate of the mean for test users. Use this to compute confidence intervals | | `ctrl_units` | The number of users in the control group | | `ctrl_mean` | The average value of this metric across control users (or participating units when applicable) | | `ctrl_stderr` | The standard error for the estimate of the mean for control users. Use this to compute confidence intervals | | `abs_delta` | The absolute difference between the test and control mean (`test_mean` - `ctrl_mean`) | | `abs_stderr` | The estimated standard error of `abs_delta` | | `rel_delta` | The relative difference between test and control mean, sometimes called lift ((`test_mean` - `ctrl_mean`)/`ctrl_mean`) | | `rel_stderr` | The estimated standard error of `rel_delta` (`abs_delta`/`ctrl_mean`) | | `z_score` | The calculated Z-score | ### Pulse Summary file description for experiments | Column name | Description | | --- | --- | | `name` | Name of the experiment or feature gate | | `rule` | Name of the feature gate rule | | `experiment_group` | The group of users for which Statsig computed this metric. For a feature gate, this is pass or fail. For an experiment, this is the variant name | | `metric_type` | Category of the metric. Statsig computes different metric types differently, including how it computes them on the Results tab | | `metric_name` | The name of the metric. For event metrics, this is the name of the event | | `metric_dimension` | The subcategory of the metric. For example, if you log `value` in LogEvent, then `value` shows up as a subdimension. `dimension = !statsig_topline` indicates that this row reflects an aggregate across all dimensions | | `start_date` | The start date for this measurement | | `end_date` | The end date for this measurement | | `units` | The number of users included in this metric estimate | | `mean` | The average value of this metric across units (or participating units when applicable) | | `stderr` | The standard error for the estimate of the mean. Use this to compute confidence intervals | ### First exposures file description | Column name | Description | | --- | --- | | `unit_id` | The unit identifier used in the experiment (for example, `user_id`, `stable_id`, or `org_id`) | | `name` | The name of the gate or experiment | | `rule` | For gates, the rule name | | `experiment_group` | The group Statsig assigned the user to | | `first_exposure_utc` | The UTC timestamp when Statsig first assigned the user to the experiment | | `first_exposure_pst_date` | The date in PST when Statsig first assigned the user to the experiment | | `as_of_pst_date` | The date Statsig generated this data | | `user_dimensions` | JSON-formatted key-value pairs describing the user's attributes at the time of first exposure | ### Unit metrics file description | Column name | Description | | --- | --- | | `pst_ds` | The 24-hour window the data refers to. Statsig anchors all dates from 12:00 AM to 11:59 PM PST | | `unit_id` | The unit identifier used in the experiment (for example, `user_id`, `stable_id`, or `org_id`) | | `metric_type` | The category of the metric | | `metric_name` | The name of the metric | | `metric_dimension` | The name of the metric dimension. `!statsig_topline` is the overall metric with no slicing | | `metric_value` | The numeric value of the metric | | `numerator` | For some metrics, Statsig tracks the numerator | | `denominator` | For some metrics, Statsig tracks the denominator | ================================================================================ # Participating Units URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/participating-units ================================================================================ # Participating Units ## Definition In Statsig, Participating Units (sometimes called participating users) are a subset of an experiment's total exposed unit count relevant to a particular metric. They count units with a non-zero denominator value for metric types that require a numerator and denominator. Statsig uses these units in statistical calculations for ratio-based metrics. ![Participating units diagram showing subset of total exposed users](https://docs.statsig.com/images/experiments/participating_units.png) Statsig computes ratio metrics only for users with a non-zero denominator value. For example, a user must trigger the denominator event on a given day for Statsig to include them in the daily ratio. Statsig excludes users who don't trigger the denominator event during an experiment from the test vs. control comparison of a ratio metric. ## Example An example of this type of metric for an e-commerce company could be "Total Items Purchased per Order", measuring the average basket size. The numerator is the count of total items bought, and the denominator is the total number of orders submitted. If you run an experiment on the checkout flow, only users who had at least one Order event count in the "Total Items Purchased per Order" ratio metric. ================================================================================ # Best Practices and Avoiding False Positives URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/best-practices Updated: 2025-09-18 ================================================================================ # Best Practices and Avoiding False Positives Interpreting Pulse results soundly means forming a hypothesis before you look, focusing on a small set of key metrics, and staying skeptical of borderline statistical significance. Follow these practices to avoid false positives and bias: 1. Form a hypothesis before viewing Pulse. Identify which metrics you expect to shift, what else could have happened, and what signals indicate something went wrong. 2. Establish a small set of key metrics directly related to your hypothesis. More than a handful of key metrics usually indicates an ill-defined hypothesis or unfocused experimentation. Examining too many metrics increases the false positive rate. 3. Avoid cherry-picking results. Don't selectively pick metrics that look good while ignoring those that don't. Avoid using numbers with no connection to your hypothesis. Statistically significant results should have a plausible explanation (a false positive is a plausible explanation). 4. Multiple independent effects that are consistent with a plausible explanation increase confidence that the observed effects are real, even with borderline p-values. 5. Expect false positives and be cautious about statistically significant results with borderline p-values. You can expect a 95% confidence interval (5% significance level) to produce one statistically significant result out of twenty by random chance alone. This rate increases if you include borderline metrics (for example, p = 0.06). 6. Look beyond your hypothesis for additional effects, tradeoffs, and unexpected behaviors. These can reveal information about how users interact with your product and often lead to follow-up experiments. ================================================================================ # Pulse FAQs URL: https://docs.statsig.com/statsig-warehouse-native/features/interpreting-results/faq ================================================================================ # Pulse FAQs Interpreting statistical results can be difficult, and many users have similar questions. This page covers the most common ones. ## I had a stat sig result, but it turned negative. How should I interpret this In general, trust the current result, because it incorporates more information about the users in your experiment. There are several reasons this can happen: - Random noise, which gets diluted as your sample size gets larger - Within-week seasonality (e.g. an effect is different on Mondays), which gets normalized with more data - The users who saw the experiment early are different from slower adopters. A daily user likely sees your experiment before someone who uses your product once a month. Use the time series view for more insight on these adoption differences. - A novelty effect made the experiment meaningful early on, but the effect faded. For example, after changing a button, users may click it out of curiosity at first, then revert to prior behavior. Use the days-since-exposure view for more insight on novelty effects. Best practice is to set a readout date when you launch your experiment, based on a [power analysis](https://docs.statsig.com/experiments/power-analysis), and to disregard the statistical interpretation of results until that date. Reading results multiple times before the readout date dramatically increases the rate of false positives. ## How should I start interpreting results Start by using your scorecard metrics to understand whether you moved the metrics you expected to move. Before reviewing Pulse, form a hypothesis about what your experiment should drive. Your primary metrics should answer that hypothesis. The delta displayed is based on the observed difference between test and control populations. The error bars visualize a confidence interval. A confidence interval is a range of probable values for the difference between groups. A future sample's 95% confidence interval contains the true value 95% of the time. In practice, the CI is a representative range of what the true value might be. These results are statistical interpretations, not facts: - If a result isn't stat sig, you don't have sufficient evidence to reject the null hypothesis. Based on your experiment design, the observed result is reasonably likely to have happened by chance. - Generally, you should treat these results as a lack of evidence for your hypothesis. - Underpowered tests may lead to neutral results even if a true effect exists. - If a result is stat sig, you have sufficient evidence to reject the null hypothesis. In other words, if the two groups' results were identical, the probability of observing this result (or one more extreme) is below the predetermined threshold you set. - Generally, you should treat this result as evidence for your hypothesis. - Multiple comparisons (many metrics, rerunning an experiment, or grouping by dimensions) greatly increase the chance of seeing a stat sig result when there's not a true effect. Be wary of interpreting results when you see those behaviors! - A test that was extremely unlikely to succeed (such as a moonshot) with a stat sig result has a high chance of being a false positive. This is a strong signal, but consider reproducing the result, running a back-test, or reducing your significance level. After reviewing the scorecard results, use the all-metrics tab and custom queries for more information about your experiment. Examining more metrics increases the chance of a false positive, so a statistically significant movement in those views isn't necessarily a statistically sound interpretation. Use that section to look for unexpected large regressions and to generate follow-up hypotheses. ## Results are missing for some metrics Missing results typically happen when your organization uses both the SDK or event imports and precomputed metrics imported from your data warehouse. Because these pipelines can run at different times, data availability may differ. Adjust your analysis date range to get a full view of your data. ## Your external source shows more exposure events than Statsig. Are data missing Statsig doesn't count exposures on the last day (the day you made a decision). Filter out that day when you analyze your external data. The hours that define a "day" for your project depend on the timezone you assigned to your project. ## You log categorical metadata for a custom event, but Pulse doesn't show these breakouts. What's wrong Pulse shows experimental results for metric sub-groups (for example, iOS vs. Android) only when you configure your metadata as a Dimension. [Value Dimensions](https://docs.statsig.com/experiments/interpreting-results/read-results#value-dimensions) are the most common dimension type because their metadata is logged directly with your custom events. Define value dimensions in your [custom event setup](https://docs.statsig.com/metrics/metric-dimensions). ## Why are dimensions greyed out or showing "No dimensions available for this time range" Precomputed user dimensions load asynchronously after the main Scorecard results and may be greyed out while processing. Wait a few minutes and refresh. You may see "No dimensions available for this time range" when a breakdown has no results for the selected metric and date range. If a precomputed dimension stays unavailable, check its source tables and columns. A source issue can affect one dimension while others load successfully. ================================================================================ # Reports URL: https://docs.statsig.com/statsig-warehouse-native/features/reports Updated: 2025-09-18 ================================================================================ # Reports ## How report summaries work Report summaries combine experiment results with context and discussion to produce long-term records of what you learned by running the experiment. Reports live on the Statsig console, and you can export them as a PDF to your learnings library. ![Experiment report summary interface](https://docs.statsig.com/images/statsig-warehouse-native/features/reports/337c3619-a91b-4837-8d02-3db3b3299ef8.png) Reports capture results and in-context discussion, and support embedding media, charts, and rich text formatting for deeper discussion and sharing of follow-ups from outside Statsig. ![Report editor with rich text content](https://docs.statsig.com/images/statsig-warehouse-native/features/reports/96f9eb43-ca69-4d9f-98f4-740294b5671f.png) ![Embedded charts and discussions in report](https://docs.statsig.com/images/statsig-warehouse-native/features/reports/f6071323-58fe-45f0-b0a2-f532e5719ecd.png) ![Report export preview showing PDF layout](https://docs.statsig.com/images/statsig-warehouse-native/features/reports/5c782533-fa67-47bc-b21c-0f8ec6740489.png) ================================================================================ # Aggregated Impact URL: https://docs.statsig.com/statsig-warehouse-native/features/exploring-results/aggregated-impact ================================================================================ # Aggregated Impact ## Metric Insights and Aggregated Impact Statsig's Insights page shows how experiments and feature gates affect a single metric. It answers questions such as "How much impact have I driven?" and diagnoses unexpected changes in a metric. Insights presents a reverse perspective of the [Pulse](https://docs.statsig.com/experiments/interpreting-results/read-results) view. Pulse measures the impact of a new feature on all your metrics; Insights focuses on a single metric and identifies which tests are affecting that metric the most. This single-metric focus makes Insights useful for assessing your team's impact and setting realistic goals. ## How to read Insights 1. Navigate to the Insights section in the Statsig console: https://console.statsig.com/. Insights also appears in the insight tab for each metric. 2. Select a metric from the drop-down at the top of the page. 3. Select the ID type, time window, and other filters. 4. Based on the filters you choose, you can see the relative impact, topline impact, and projected launch impact for any experiment or gate that uses this metric. 5. Statsig also sums the projected launch impacts, adjusts based on false positive risk ('winner's curse'), and displays the result as the 'Aggregated Impact Estimate'. ![Insights dashboard showing aggregated impact estimates for a metric](https://docs.statsig.com/images/snippets/pulse/aggregated-impact/430563dc-4794-4d69-a314-36c76a6fcf74.png) ## How the math works Refer to the [topline impact documentation](https://docs.statsig.com/experiments/statistical-methods/topline-impact/#computing-projected-launch-impact) for details on how Statsig calculates topline and projected launch impact. To estimate false positive risk and calculate Aggregated Impact, Statsig uses the methodology in this [paper](https://dl.acm.org/doi/10.1145/3534678.3539160), which the industry widely adopts. Specifically: $$ Aggregated Impact=\sum_{i}{(1 - FPR_i) \times Projected Launch Impact_i} $$ Where the [projected launch impact](https://docs.statsig.com/experiments/statistical-methods/topline-impact/) is an estimate of the topline impact assuming you make a decision and launch the test group to all users. Statsig calculates the false positive risk using the following formula: $$ FPR_i = \frac{\alpha_i \times \pi}{\alpha_i \times \pi + (1 - \beta_i) \times (1 - \pi)} $$ In this formula, $\alpha_i$ is the significance level for experiment i, $\beta_i$ is the type II error, and 1 - $\pi$ is the prior success rate based on historical experiment results. ================================================================================ # WHN Statistics Overview URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics Updated: 2025-09-18 ================================================================================ # WHN Statistics Overview Statsig's statistics engine analyzes your experiment results and calculates the lifts, p-values, and confidence intervals you see in the console. The Stats Engine has four core values: Transparency, Trust, Flexibility, and Power. The pages below cover the Pulse Statistics Engine in detail, including how Statsig calculates results. ## Transparency Statsig documents all of its methodology, and the analysis is fully visible in Warehouse Native. Statsig provides the tools, data, and queries you need to reproduce the results you see in the console, with no hidden logic. Most enterprise data science teams validate results as part of their evaluation process. Transparency includes: - Console-based access to the SQL Statsig runs. You have access to the tables and queries on your warehouse, and Statsig surfaces SQL snippets in the console whenever it runs a query so you can verify what Statsig calculates. - Visibility into costs. Most customers can run pulse analyses for very low cost, and Statsig surfaces run time and resource utilization to help you manage your warehouse bill for experimentation. - Support: Statsig offers support with access to the data science team for open discussion of methodology, approaches, and collaborative development of new features. ## Trust Experiments drive important business decisions, and it's critical that you can trust the analysis and statistics Statsig runs. Statsig has a rigorous evaluation process for its methodologies, including peer review, simulations, and publishing the thought process behind statistical designs. You can trust Statsig's results to be accurate and reliable as they help guide your decisions. Trust includes: - Detailed blog posts on the rationale behind decisions in new features - Documentation of methodologies in blogs, with references to prior art - A full suite of diagnostic health checks on experiment results to warn you of compromised statistical assumptions or data quality ## Flexibility Experimentation isn't a single approach that fits every situation. Depending on your industry, philosophy, or the setup of a specific experiment, Statsig lets you configure your analysis to suit your needs, offering: - Standard T-Tests - Sequential Testing - Bayesian Tests - Switchback Tests - Multi-armed bandits Statsig also offers many options to control for multiple comparisons, outliers, and regression adjustment. ## Power Effective experimentation relies on having trustworthy results quickly. Statsig has invested heavily in accuracy and power, so your results are faster and more reliable. Examples of features focused on the power of Statsig's stats engine: - [CUPED](https://www.statsig.com/blog/cuped): reduces experiment run times and accounts for pre-experiment bias - [Stratified Sampling](https://docs.statsig.com/experiments/advanced-setup/stratified-sampling): makes experiment results more accurate and consistent ================================================================================ # Confidence Intervals URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/confidence-intervals ================================================================================ # Confidence Intervals Confidence intervals are an intuitive way to quantify the uncertainty in the observed metric deltas. A 95% confidence interval should contain the true effect 95% of the time: if you ran an experiment 100 times, the true value of the metric delta should fall inside the confidence interval 95 times. ![Confidence interval visualization showing statistical significance](https://docs.statsig.com/images/snippets/stats-methods/confidence-intervals/168382034-73afed14-d9f5-42cb-ade1-034526002a0b.png) In practical terms, a 95% confidence interval that doesn't contain zero (the green bar above) represents a statistically significant result (with _α = 0.05_). Significance and confidence intervals don't always align this way. The p-value of the difference between test and control can be statistically significant even when the relative delta confidence interval crosses zero (using [The Delta Method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method)) or appears as a point estimate (using [Fieller Intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals)). This mismatch happens because of uncertainty in the control. Only 5% of the time would you expect to see the confidence interval exclude zero if the true effect was zero (also called a false positive). Larger confidence intervals imply less certainty in the exact size of the effect with a larger range of likely values. ## Computing confidence intervals Statsig calculates confidence intervals using a two-sample z-test. This test requires knowledge of the variance in the measured metric delta, which Statsig derives differently depending on the type of metric (refer to [how Statsig derives variance](https://docs.statsig.com/experiments/statistical-methods/variance)). After establishing the variance of the delta, Statsig computes the confidence intervals. ### Two-sided tests For the absolute metric delta, the confidence interval is: $$ CI(\Delta \overline{X}) = \Delta \overline{X} \pm Z_{\alpha/2} \cdot \sqrt{{var(\Delta \overline{X})}} $$ where: - $Z_{\alpha/2}$ is the z-critical value for the significance level you want (1.96 for the standard $\alpha=0.05$ and 95% confidence interval) for a two-sided test - $var(\Delta \overline{X})$ is the variance of the absolute delta (details [here](https://docs.statsig.com/experiments/statistical-methods/variance)) The confidence interval for the relative metric delta can use one of two methods: [Fieller Intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals) or the [Delta Method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method). Customers can choose either method in their Statsig console. Statsig recommends Fieller Intervals and enables them by default for all new customers. When using Fieller Intervals, you can compute the relative metric delta CI using: $$ CI(\% \Delta \overline{X} ) = \frac{1}{1-g} ( \frac{\overline{X_T}}{\overline{X_C}} - 1 \pm \frac{Z_{\alpha/2}}{\sqrt{n_C} \cdot \overline{X_C}} \sqrt{(1-g) \cdot \frac{var(X_T)}{n_T(n_T-1)} + \frac{\overline{X_T} var(X_C)}{\overline{X_C} n_C (n_C-1)}}) $$ When using the Delta Method, the confidence interval is: $$ \begin{split} CI(\Delta \overline X\%) &= \Delta \overline X\% \pm Z_{\alpha/2} \cdot\sqrt{{var(\Delta \overline X\%)}}\\ &= \frac{\Delta \overline X}{\overline X_c} \pm Z_{\alpha/2} \cdot\sqrt{(\frac{\overline X_t}{\overline X_c})^{2} \cdot (\frac{var(X_c)}{n_c \cdot \overline X_c^2} + \frac{var(X_t)}{n_t \cdot \overline X_t^2})} \cdot 100\% \end{split} $$ If using the Delta Method and the control mean isn't significantly away from zero, then it simplifies to: $$ \begin{split} CI(\Delta \overline X\%) &= \Delta \overline X\% \pm Z_{\alpha/2} \cdot\sqrt{{var(\Delta \overline X\%)}} \\ &= \frac{\Delta \overline X}{\overline X_c} \pm Z_{\alpha/2} \cdot \frac{\sqrt{{var\left(\Delta \overline X\right)}}}{\overline X_c} \cdot 100\% \end{split} $$ ### One-sided tests When running one-sided tests, the form of the confidence interval calculation changes slightly to account for a redistribution of the false positive rate you want when looking for increases or decreases in the metric: $$ CI(\Delta \overline{X}) = \begin{cases} \left[\Delta \overline{X} - Z_{\alpha} \cdot \sqrt{{var(\Delta \overline{X})}}, \quad +\infty \right) & \text{if right-hand test}\\ \\ \left(-\infty, \quad \Delta \overline{X} + Z_{\alpha} \cdot \sqrt{{var(\Delta \overline{X})}} : \right] & \text{if left-hand test} \end{cases} $$ where: - $Z_{\alpha}$ is the z-critical value for the significance level you want (1.645 for the standard $\alpha=0.05$ and 95% confidence interval) for a one-sided test - $var(\Delta \overline{X})$ is the same as for two-sided tests - the choice of confidence interval depends on if the one-sided test is looking for increases or decreases in the metric ## Welch's t-test for small sample sizes For small sample sizes, Statsig uses Welch's t-test instead of a standard z-test. Welch's t-test handles samples of unequal size or variance without increasing the false positive rate. The structure of the confidence interval calculation remains the same (depending on whether you use a 1- or 2-sided test), replacing the z-critical value with the t-critical value with degrees of freedom $\nu$. For a two-sided test, the confidence interval is therefore: $$ CI(\Delta \overline{X}) = \Delta \overline{X} \pm t_{\alpha/2} \cdot \sqrt{{var(\Delta \overline{X})}} $$ $$ \nu = \frac{\left(var(\overline X_t) + var(\overline X_c)\right)^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} = \frac{var(\Delta\overline{X})^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} $$ Where $N_t$ and $N_c$ are the number of users in the test and control groups, respectively. For a large number of degrees of freedom, the t-statistic converges with the z-statistic. Therefore, Statsig uses Welch's t-test only when $\nu < 100$. ## Comparing experiment data to a fixed baseline: one-sample t-test Sometimes you want to answer questions like "Does my test variant lead to a click-through rate higher than 0.5?" You can define a fixed-baseline comparison when adding metrics to the experiment. Statsig calculates the confidence interval as $$ CI(\Delta \overline X) = (\overline X_{group} - fixed \ value) \pm Z \cdot\sqrt{{var( \overline X_{group})}} $$ ================================================================================ # p-Value Calculation URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/p-value ================================================================================ # p-Value Calculation In Null Hypothesis Significance Tests, the p-value is the probability of observing an effect at least as large as the measured metric delta. The p-value assumes the null hypothesis is true. In practice, a p-value below the pre-defined Type I Error threshold ($\alpha$) serves as evidence of a true effect. The methodology for p-value calculation depends on the number of degrees of freedom ($\nu$). A two-sample z-test is appropriate for most experiments. Statsig uses Welch's t-test for smaller experiments with $\nu < 100$. In both cases, the p-value depends on the metric [mean](https://docs.statsig.com/experiments/statistical-methods/metric-deltas) and [variance](https://docs.statsig.com/experiments/statistical-methods/variance) computed for the test and control groups. Typically, a p-value below threshold $\alpha$ occurs only when the confidence interval doesn't cross 0. However, this correspondence isn't always the case in the Statsig UI. When the p-value of the difference between test and control is significant, the relative delta confidence interval may still cross zero (when using [The Delta Method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method)) or appear as a point estimate (when using [Fieller Intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals)). In these cases, the absolute difference's p-value remains statistically significant. ## Two-sample tests ### Two-sided z-test You can compute the z-statistic (also called the z-score) of a two-sample z-test in multiple equivalent formats: $$ \begin{split} Z &= \frac{\overline X_t - \overline X_c}{\sqrt{var(\overline X_t)+ var(\overline X_c)}} \\ &= \frac{\overline X_t - \overline X_c}{\sqrt{var(\Delta \overline{X})}} \\ &= \frac{\overline X_t - \overline X_c}{\sqrt{\sigma_{\overline{X}_t}^2 + \sigma_{\overline{X}_c}^2}} \end{split} $$ where: - $Z$ is the observed z-statistic (not the z-critical value $Z_{\alpha/s}$) - $var(\Delta \overline{X})$ is the variance of the absolute delta of means - $var(\overline{X}_i)$ is the variance of sample means either control or treatment group (details [here](https://docs.statsig.com/experiments/statistical-methods/variance)) - $\sigma_{\overline{X}_t}$ is the standard error of the mean of either control or treatment group (these are the terms you can find in Pulse under the Statistics tab of a metric) Statsig obtains the two-sided p-value from the standard normal cumulative distribution function: $$ p-value = 2 \cdot \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{-|Z|}{e^{-t^2/2}dt} $$ ### Welch's t-test For smaller sample sizes, Statsig prefers Welch's t-test because it produces lower false positive rates when group sizes and variances are unequal. In Pulse, Statsig automatically applies Welch's t-test when the degrees of freedom $\nu < 100$. Statsig computes the t-statistic (also called the t-score) identically to the two-sample z-statistic above. Statsig computes the degrees of freedom $\nu$ using: $$ \nu = \frac{\left(var(\overline X_t) + var(\overline X_c)\right)^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} := \frac{var(\Delta\overline{X})^2}{\frac{var(\overline X_t)^2}{N_t - 1}+\frac{var(\overline X_c)^2}{N_c - 1}} $$ Statsig then obtains the p-value from the t-distribution with $\nu$ degrees of freedom. ### One-sided z-test The one-sided z-test computes the z-statistic $Z$ in the same way as the two-sided test. The one-sided p-value differs as follows: $$ p-value = \begin{cases} 1 - \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z}{e^{-t^2/2}dt} &\text{if right-hand test}\\ \frac{1}{\sqrt{2\pi}} \int \limits _{-\infty}^{Z}{e^{-t^2/2}dt} &\text{if left-hand test} \end{cases} $$ where: - Statsig computes $Z$ as in the two-sided test. This uses the signed z-statistic, not the absolute value used in the two-sided p-value. ================================================================================ # Metric Deltas URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/metric-deltas ================================================================================ # Metric Deltas ## Computing metric deltas A metric delta refers to the difference in metric values between two groups, by default the test and control groups. The metric delta is the impact you measure when evaluating experiment results. To account for the different number of users (or units) in each group, Statsig compares the mean metric value per user, not the total. > **Note:** > > **Selecting groups** > > Statsig defines all deltas as the difference between a "treatment" group and a presumably unchanged "control" group. However, Statsig allows comparison between any two groups. Pulse provides two different metric deltas. The absolute delta is the difference between the two means: $$ \Delta \overline{X}=\overline{X}_t-\overline{X}_c $$ Understanding the impact relative to the baseline value of the metric is often helpful. For example, an absolute delta of +1 clicks/user has different meanings with a baseline value of 1 (+100% increase) vs. a baseline value of 100 (+1% increase). Statsig computes the relative delta using the mean of the control group as the baseline: $$ \Delta \overline{X} \%=\frac{\overline{X}_t-\overline{X}_c}{\overline{X}_c} \times 100 \% $$ > **Note:** > > If you reverse the order of group comparison in Pulse to be "control" vs "treatment", all deltas reverse and the direction of change inverts. ## Computing means Computing group means correctly is critical for obtaining meaningful metric deltas. The methodology for calculating metric means depends on the metric type. ### Event count and sum metrics These metrics represent totals: number of times an event occurs, sum of time spent, total purchase amount, and similar values. The mean is the average user-level total during the analysis period. The mean value of the metric $X$ for a group is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} X_{i, d} $$ where: - $N$ is the number of users in the group - $n_i$ is the number of days during the analysis period that user $i$ was the experiment - $X_{i,d}$ is the metric value for user $i$ on day $d$ > **Note:** > > Statsig includes only user metrics from after a user's exposure to the experiment in the group mean. ### User accounting and Event User metrics (and legacy Event DAU) Event User metrics set to "Daily Participation Rate" capture the number of distinct users that have the event each day. In Pulse results, Statsig normalizes these values by the number of days the user is in the experiment. The normalized value represents the probability that a user is daily active for that event (the daily participation rate). The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \frac{1}{n_i} \sum_{d=0}^{n_i} X_{i, d} $$ where: - $X_{i,d}$ takes value 0 or 1 depending on if user $i$ has the event on a given day $d$. Statsig computes the following user accounting metrics the same way: _DAU, WAU, MAU\_28day, L7, L14, L28_ For new user accounting (_new\_DAU, new\_WAU, new\_MAU\_28day_), Statsig counts users that are new xAU at some point during the analysis window. The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N \max \left(X_i\right) $$ Where $\max(X_i)$ is the maximum value of the new xAU metric for user $i$. > **Note:** > > **event\_dau** metrics are now in legacy support only and Statsig no longer creates them for new events. Existing event\_dau metrics remain available for any of your new experiments, and Statsig continues to compute them daily. For all new events, create an event\_user metric to measure daily active users. ### Custom ratios, means, retention, and stickiness metrics These metrics include click-through rate, average purchase value, sessions per user, and similar values. Statsig obtains each by dividing a numerator value, $X$, by a denominator value, $Y$. The mean value of a ratio metric $R$ for an experiment group is: $$ \overline{R}=\frac{\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} X_{i, d}}{\frac{1}{N} \sum_{i=0}^N \sum_{d=0}^{n_i} Y_{i, d}}=\frac{\overline{X}}{\overline{Y}} $$ Where $N$ is the number of users in the experiment group that participate in the metric, i.e. have a non-zero denominator value. $X_{i,d}$ and $Y_{i,d}$ are the $X$ and $Y$ values for user $i$ on day $d$. Different approaches exist for ratio metrics in experiments. Statsig selected this implementation because it's statistically sound and interpretable: - $R$ is the ratio of two means of independent observations: a set of user-level $X$ values and a set of user-level $Y$ values. You can therefore use the central limit theorem to separately obtain the summary statistics of $X$ and $Y$. - Statsig computes the group means in the same way as the topline metric value, making the means easier to interpret and relate to the topline metric. ### Event User one-time event For custom **event\_user** metrics with "One-Time Event" selected, Statsig computes how many users have the event at any time after entering the experiment. Statsig doesn't normalize this result by the number of days a user is in the experiment. The group mean is: $$ \overline{X}=\frac{1}{N} \sum_{i=0}^N X_{i} $$ where: - $N$ is the number of users in the group - $X_{i}$ takes value 0 or 1 depending on if user $i$ has the event at any point after entering the experiment ================================================================================ # Standard Error & Mean Variance URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/variance ================================================================================ # Standard Error & Mean Variance The confidence interval and p-value of a metric delta between two groups both depend on the standard error of the mean of each group. The standard error is sometimes denoted "SE" or "std err". You obtain the standard error of the mean by dividing the sample standard deviation of $X$ by the square root of the number of users in the group. $$ \sigma_{\overline X} = \frac{\sigma_{X}}{\sqrt{N}} = \sqrt{\frac{var(X)}{N}} = \sqrt{var(\overline{X})} $$ Standard deviation is the square root of variance. Because variances are easier to manipulate algebraically, Statsig derives the variance for each metric type and then takes the square root to obtain the confidence intervals. Pulse shows the standard error of the mean of each group alongside the units and mean of each group. ## Computing variance The variance of the absolute metric delta is the sum of the variances of the test and control means: $$ var(\Delta \overline X) =var(\overline X_t - \overline X_c) = var(\overline X_t) + var(\overline X_c) $$ Computing this correctly requires accurate variance of the means for each group. ### Count and sum metrics For count and sum metrics, Statsig obtains the variance of the sample mean for a given group directly from the sample variance: $$ var(\overline{X}) = \frac{var(X)}{N} = \frac{\frac{1}{N-1}\sum_{i=0}^{N}(X_i-\overline{X})^2}{N} $$ Where: - $N$ is the number of users in the group - $X_i$ is the metric value for user $i$ - $\overline{X}$ is the user-level average of $X$ for users in that group ### Ratio and mean metrics Ratio and mean metrics combine multiple variables $X$ and $Y$ rather than a single variable $X$. The variance of these metrics depends on both the numerator and denominator variables, which are typically correlated. For metric $R$, the group mean $\overline{R}$ and group variance of the mean $var(\overline{R})$ must account for this correlation. For example, in a _clicks per session_ metric, the number of clicks and the number of sessions come from the same group of users and aren't independent. To account for any correlation, Statsig computes the variance of the mean of a ratio metric $R$ using the delta method: $$ var(\overline R) = var\left(\frac{\overline X}{\overline Y}\right) := \left(\frac{\overline X}{\overline Y}\right)^2 \cdot \left(\frac{var(\overline X)}{\overline X^2} + \frac{var(\overline Y)}{\overline Y^2} - 2 \cdot \frac{covar(\overline X, \overline Y)}{\overline X\cdot \overline Y} \right) $$ where Statsig computes the variance of the numerator and denominator means in the same way as detailed above for count metrics, and the covariance is $$ covar(\overline X, \overline Y) = \frac{covar(X, Y)}{N} = \frac{\frac{1}{N-1}\sum_{i=0}^{N}(X_i-\overline X)\cdot (Y_i-\overline Y)}{N} $$ ================================================================================ # Topline and Projected Impact URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/topline-impact ================================================================================ # Topline and Projected Impact The **topline impact** is the average daily effect that an experiment has on the overall metric value, measured between two groups. The **projected launch impact** is an estimate of the daily global metric impact expected if you launch the test group to all users (beyond those in the experiment). Statsig computes this impact relative to the expected baseline metric value without the experiment running. Statsig shows both Topline Impact and Projected Launch Impact in absolute and relative units. Neither uses CUPED, because CUPED already adjusts for pre-exposure data (the starting point for topline metrics), and combining the two double-counts that adjustment. > **Tip:** > > **Example**: Take a simple example experiment with a Control group of 1000 users and a Test group of another 1000 users, which ran for 30 days. For an **event\_count** metric, the observed Experiment Delta is +1.0 events per user (abs). The Topline Impact for this metric is +33.33 events per day (abs). ## Computing topline impact Statsig computes the topline impact over the total duration of the experiment, which produces the most accurate estimate and tight confidence interval. The calculation depends on whether the metric represents an absolute quantity or a ratio: ### Count and sum metrics (event\_count, sum) Statsig derives the absolute topline impact from the experiment results. It depends on the difference in means between test and control and the average number of users in the test group per day. $$ Impact_{abs}=(X_t-X_c) \cdot N_t / n_{days} $$ Using the absolute impact and the overall metric value (as shown in the [metrics dashboard](https://docs.statsig.com/metrics/console)), Statsig computes the relative impact: the percentage change in the overall metric value over the rollup window attributed to the active experiment. $$ Impact_{rel}=\frac{Impact_{abs}}{\text{Topline\_Value}-Impact_{abs}} \times 100\% $$ ### Ratio and mean metrics To derive the topline impact on a ratio metric, Statsig first determines the impact on the numerator (_X_) and denominator (_Y_) separately. The topline impact is the current ratio metric value minus the baseline value obtained by subtracting the numerator and denominator impacts: $$ Impact_{abs}=\frac{Topline_X}{Topline_Y}-\text{Baseline\_Value} $$ Where the baseline value is the expected value of the topline metric if the experiment wasn't running: $$ \text{Baseline\_Value}=\frac{Topline_X-(\bar{X_t}-\bar{X_c}) \cdot N_t}{Topline_Y-(\bar{Y_t}-\bar{Y_c}) \cdot N_t} $$ Statsig obtains the relative impact for ratio metrics by dividing the absolute impact by the baseline value: $$ Impact_{rel}=\frac{Impact_{abs}}{\text{Baseline\_Value}} \times 100\% $$ ### Composite metrics Statsig computes full Topline Impact for composite metrics, including both absolute and projected impact. Statsig computes each component metric's daily value, then combines those values using the composite's `+` and `-` operators. Statsig rolls up the combined result the same way as any other metric type. This brings composite metrics to parity with ratio, funnel, and retention metrics for Topline Impact. Statsig shows absolute and projected impact for composite metrics across supported warehouses. ## Computing projected launch impact Statsig uses the layer allocation of the experiment and the size of the test group to estimate a scaling factor _m_, which represents the increase in absolute impact expected when you launch the test group. Statsig calculates the launch factor over a rollup window as $$ m_{rollup}=\frac{1}{\sum_{1}^{rollup}{\text{layer\_alloc} \times \text{group\_pct}}} \times rollup $$ to accommodate changes in allocation during the experiment. > **Note:** > > Statsig doesn't factor in the targeting gate. The projected impact calculation assumes that the target gate remains the same after you launch the experiment. ### Count and sum metrics (event\_count, event\_dau, sum) For count and sum metrics, the projected absolute impact is the current topline impact scaled by factor _m_. For example, consider an experiment running at 50% layer allocation with a 50/50 test/control split, so that 25% of all users are in the test group. If the allocation changed during the experiment, Statsig uses a weighted average based on historical allocations. If the topline impact is +10 events per day, launching the experiment produces +40 events per day. $$ Projected_{abs}=Impact_{abs} \times m $$ The relative projected impact is the expected percentage change in the topline metric, relative to the baseline metric value without the experiment running. $$ Projected_{rel}=\frac{Projected_{abs}}{\text{Topline\_Value}-Impact_{abs}} \times 100\% = Impact_{rel} \times m $$ ### Ratio and mean metrics The projected impact of ratio metrics depends on the numerator and denominator impacts in the same way as the topline impact calculation. Statsig uses the same scaling factor _m_ to obtain the projected impact for each term: $$ Projected_{abs}=\frac{Topline_X+(m-1) \cdot (\bar{X_t}-\bar{X_c}) \cdot N_t}{Topline_Y+(m-1) \cdot (\bar{Y_t}-\bar{Y_c}) \cdot N_t} - \text{Baseline\_Value} $$ Where the first term represents the projected metric value after launch. Finally, the projected relative impact of a ratio metric is the projected absolute impact divided by the baseline value of the ratio: $$ Projected_{rel}=(\frac{Projected_{abs}}{\text{Baseline\_Value}}) \times 100\% $$ ## Confidence intervals Statsig computes the confidence intervals for topline and projected impact using the same method as the [confidence intervals](https://docs.statsig.com/experiments/statistical-methods/confidence-intervals) for experiment deltas. $$ CI(Impact) = Impact \pm Z \cdot \sqrt{var(Impact)} $$ For the absolute impact of count and sum metrics, the variance is a linear combination of the test and control variances: $$ var(Impact_{abs})=[var(\bar{X_t})+var({\bar{X_c}})] \cdot N_t^2 $$ And for projected launch impact: $$ var(Projected_{abs})=var(Impact_{abs}) \cdot m^2 $$ For ratio metrics and relative impacts, Statsig calculates the variance using the Delta method. This accounts for the correlation between numerator and denominator terms by using Taylor expansion to linearize expressions containing non-linear combinations of experiment variables. For example, the variance in the relative impact of a count metric is: $$ var(Impact_{rel})=var(Impact_{abs}) \cdot \frac{(\text{Topline\_Value})^2}{(\text{Topline\_Value} - Impact_{abs})^4} $$ ================================================================================ # Variance Reduction URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/variance-reduction ================================================================================ # Variance Reduction ## Variance reduction [Variance](https://docs.statsig.com/experiments/statistical-methods/variance) measures the dispersion (or "noise") in a metric or experiment results. Higher variance produces larger confidence intervals, requiring more sample to detect a statistically significant result for the same effect size. Lower variance reduces required sample size, which leads to shorter experiment run times. Statsig uses a form of CUPED based on a [2013 Microsoft paper](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf) (Deng, Xu, Kohavi, & Walker). Statsig automatically applies CUPED to experiments and runs it for the topline results on key metrics in Pulse, producing significant variance reduction for most metrics. Go to the [CUPED launch post](https://blog.statsig.com/cuped-on-statsig-d57f23122d0e) for more details. ## CUPED - Controlled-experiment Using Pre-Existing Data CUPED (Controlled-experiment Using Pre-Existing Data) uses user information from before an experiment to reduce variance and increase confidence in experimental metrics. In Statsig, the pre-experiment data window is the 7 days before each user's exposure, rather than a fixed window before the experiment starts. This approach helps debias experiments where groups were randomly different before you apply any treatment. The Cloud product uses stratification alongside CUPED to account for users who may not have pre-experiment data. Statsig groups users into strata based on available pre-experimentation information. Statsig estimates treatment and control effects within each stratum, then aggregates them to produce an overall result. Statsig then applies standard difference-in-means and variance estimation. This approach retains users with missing pre-data while still benefiting from variance reduction where applicable. ## Winsorization Another technique for reducing noise is Winsorization, which manages the influence of outliers. Winsorization measures the percentile _P<sub>x</sub>_ of a metric and sets all values over _P<sub>x</sub>_ to _P<sub>x</sub>_. Winsorization reduces the influence of extreme outliers caused by factors such as logging errors or bad actors. ## Metric selection The metrics you use can dramatically influence the sensitivity of your analysis. CUPED and Winsorization, along with techniques like creating threshold-based flags, let you trade exact numbers for significantly more statistical power. Go to the [Statsig blog post on variance reduction](https://www.statsig.com/blog/understanding-and-reducing-variance-and-standard-deviation) for more information. ## Related resources - [Deng, Xu, Kohavi, & Walker](https://exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf): the seminal paper on using CUPED for online controlled experiments - [Booking.com on CUPED](https://booking.ai/how-booking-com-increases-the-power-of-online-experiments-with-cuped-995d186fff1d): theory and practice of CUPED - [Improving the Sensitivity of Online Controlled Experiments: Case Studies at Netflix](https://www.kdd.org/kdd2016/papers/files/adp0945-xieA.pdf) ================================================================================ # Pre-Experiment Bias URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/pre-experiment-bias ================================================================================ # Pre-Experiment Bias Pre-experiment bias occurs when users in two experiment groups have meaningfully different average behaviors before you apply any intervention. If this difference persists after the experiment starts, the analysis may attribute that pre-existing difference to the intervention, making a result appear more or less impactful than it is. [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) helps address this bias, but can't fully account for it. Some metrics, such as retention, aren't viable candidates for CUPED, and you can't easily adjust them. Statsig measures the pre-experiment values of all scorecard metrics for all experiment groups and determines whether the values are significantly different and could cause misinterpretations. If Statsig detects bias, it notifies users and places a warning on relevant Pulse results. ### How it works Statsig provides a "Days Since Exposure" view to help identify novelty effects and pre-experiment effects. For example, the test group in the following experiment had a consistently higher mean than the control group in the week before the experiment started: ![Pre-experiment bias visualization showing test group with consistently higher mean than control group](https://docs.statsig.com/images/snippets/stats-methods/pre-experiment-bias/246545035-22ff2db6-9c08-4227-a53d-8faa8feb5e92.png) Statsig detects this bias by running the standard [pulse](https://docs.statsig.com/experiments/interpreting-results/read-results) calculation on the pre-experiment term (looking back one week in Cloud, and the configured CUPED lookback window in Warehouse Native). Statsig then calculates the p-value for the null hypothesis that the groups are identical. Statsig flags relevant results using logic that balances awareness against false positives from large numbers of scorecard metrics or groups. ### What to do Pre-experiment bias can occur by chance and isn't always a major issue. - If the total delta is small, it may not meaningfully influence the interpretation of results. - If CUPED can account for the bias, the bias shouldn't affect results. In many cases, treat this warning as informational and proceed, applying extra scrutiny to impacted metrics. Treating the warning as informational is appropriate when the metric isn't critical to the experiment or when directional movement matters more than the exact value. Additional experiment time may also reduce the bias if no systemic source exists, because new users dilute the imbalance. If the metric is critical and the exact numerical value matters, consider resalting and restarting the experiment. ================================================================================ # Bonferroni Correction URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/bonferroni-correction ================================================================================ # Bonferroni Correction ## What is Bonferroni correction A Bonferroni Correction is a statistical method that reduces the probability of false positives by adjusting the significance level for multiple comparisons. If you run a test with α = 0.05, the probability of a false positive is 5%. Running more comparisons at the same significance level increases the chance of at least one false positive, because each comparison is an additional opportunity for a false positive. Bonferroni corrections are an optional feature on Statsig experiments that reduce the probability of Type I errors (false positives) by adjusting the significance level (α). Statsig divides the significance level by the number of comparisons it evaluates. You can choose to apply these based on one or both of the following: - The number of test groups (multiple treatment hypotheses). Statsig divides the significance level by the number of variants it compares against control. - The number of metrics in the scorecard. Here you may select what percentage of your total α Statsig divides evenly among the Primary Metrics, and Statsig splits the remaining α equally among Secondary Metrics. For example: - Significance level of 0.05 - 2 Primary Metrics and 4 Secondary Metrics - 60% of α applied to Primary Metrics - Statsig calculates each Primary Metric with α = 0.6 \* 0.05 / 2 = 0.015 - Statsig calculates each Secondary Metric with α = 0.4 \* 0.05 / 4 = 0.005 - If you select both corrections, Statsig applies them on top of each other. In the example above, to also correct for having 2 test groups, further divide each α by 2. When analyzing dimensions, if you enable correction for metrics, Statsig applies it separately for the dimensional breakdown. Statsig uses the number of dimensions as the total metric count to correct for in the dimensional analysis, but this doesn't impact topline metrics. ![Bonferroni correction configuration interface](https://docs.statsig.com/images/snippets/stats-methods/bonferroni-correction/038d75eb-5745-4587-b180-86b88594ccb9.png) ## How experiment metrics appear after applying Bonferroni correction In the experiment scorecard section, Statsig derives confidence intervals from (1 - adjusted α) for applicable metrics. Hovering over a confidence interval displays the adjusted α alongside other relevant metric details. In the experiment explore section, Statsig calculates a new adjusted α based on your selections, and the confidence intervals use (1 - adjusted α). ================================================================================ # Benjamini–Hochberg URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/benjamini-hochberg-procedure ================================================================================ # Benjamini–Hochberg ## What the Benjamini-Hochberg procedure is The Benjamini-Hochberg Procedure ("BH" procedure) is a statistical method that reduces the probability of false positives by adjusting the significance level for multiple comparisons. The BH procedure isn't as extreme as a [Bonferroni Correction](https://docs.statsig.com/experiments/statistical-methods/methodologies/bonferroni-correction). A Bonferroni Correction controls the chance of at least one false positive (Family Wise Error Rate), while the BH procedure controls the expected value of false positives after you reject the null hypothesis (False Discovery Rate). You can enable the BH procedure for individual experiments, or configure global Experiment Settings to enable it by default. ![Benjamini-Hochberg procedure configuration interface](https://docs.statsig.com/images/snippets/stats-methods/benjamini-hochberg-procedure/c865494e-0ae4-489c-a416-45848b4d10bc.png) ## Methodology The [Benjamini-Hochberg Procedure](https://www.statisticshowto.com/benjamini-hochberg-procedure/) updates the significance level (modifying your pre-set $\alpha$). Statsig calculates the new significance level by sorting the p-values of metrics in ascending order and comparing each with a paired threshold. Each p-value’s paired threshold is the False Discovery Rate you want divided by the number of comparisons Statsig evaluates, multiplied by the rank of that p-value in the ordered list. The largest threshold value that is higher than its corresponding p-value becomes the new significance level ($\alpha$). You can apply the Benjamini-Hochberg Procedure based on: - The number of test groups (multiple treatment hypotheses). For each metric aggregate the list of p-values from each variant and complete the Benjamini-Hochberg procedure. - The number of metrics in the scorecard. For each variant aggregate the list of p-values from each metric and complete the Benjamini-Hochberg procedure. - Both the number of test groups and number of metrics in the scorecard. Statsig aggregates all p-values to complete the Benjamini-Hochberg procedure. Statsig doesn't apply the BH procedure when evaluating the p-values of any event-dimension or user-property experiment metric results. Statsig compares only the top-line metric results to the new significance level. ## How experiment metrics appear after applying Benjamini-Hochberg In the experiment scorecard section, Statsig derives confidence intervals from (1 - adjusted α) for applicable metrics. Hovering over a confidence interval displays the adjusted α alongside other relevant metric details. In the experiment explore section, Statsig calculates a new adjusted α based on your selections, and the confidence intervals use (1 - adjusted α). ================================================================================ # CUPED URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/cuped ================================================================================ # CUPED ## CUPED: Controlled-experiment using pre-existing data CUPED (Controlled-experiment Using Pre-Existing Data) is a technique that uses user information from before an experiment to reduce variance and increase confidence in experimental metrics. At Statsig, this pre-experiment data is the 7 days before each user's exposure, rather than a fixed window before the experiment starts for all users. This approach helps debias experiments that have meaningful pre-exposure bias (for example, groups that were randomly different before any treatment). The Cloud product uses a 7-day window for CUPED calculation. For Warehouse Native customers, Statsig recommends a 7-day window, but you can customize it to any length. For more information, go to the [Variance Reduction](https://docs.statsig.com/experiments/statistical-methods/variance-reduction) page. For an in-depth look at the methodology, refer to [CURE by Statsig](https://drive.google.com/file/d/1cLXDhwK4jcu5Oss2rVGHtp22LxVLLzBC/view?usp=sharing). ## CUPED for simple aggregations The original [Microsoft paper](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf) and Statsig's in-depth [article](https://www.statsig.com/blog/cuped) on the technique describe the methodology for simple aggregations. The Cloud product uses stratification alongside CUPED to account for users who may not have pre-experiment data. Statsig groups users into strata based on available pre-experimentation information. Statsig first estimates treatment and control effects within each stratum, then aggregates them to produce an overall result. Statsig then applies the standard difference-in-means and variance estimation. This approach retains users with missing pre-data while still benefiting from variance reduction where applicable. ## CUPED for ratio metrics The Microsoft paper also gives details on how to implement CUPED for a different analysis unit (Appendix B). Statsig extends this to work for ratio metrics, where each experiment unit has a numerator and a denominator. The variance reduction process works by finding the variance of experiment data, pre-experiment data, and the covariance between the two. Denote the numerator, denominator, pre-experiment numerator, and pre-experiment denominator of a unit as $Y$, $N$, $X$, and $M$, respectively. Using the CUPED-reduced variance formula, $$ Var(\frac{Y_{cv}}{N_{cv}})=Var(\frac{Y}{N})+\theta^2 Var(\frac{X}{M})-2\theta Cov(\frac{Y}{N}, \frac{X}{M}) $$ where Statsig finds the optimal $\theta$ as $$ \frac{Cov(\frac{Y}{N}, \frac{X}{M})}{Var(\frac{X}{M})} $$ expanded to \\ $$ \frac{Cov(\frac{Y}{\mu_N}-\frac{\mu_Y N}{\mu^2_N}, \frac{X}{\mu_M}-\frac{\mu_X M}{\mu^2_M})}{Var(\frac{X}{\mu_M}-\frac{\mu_X M}{\mu^2_M})} $$ From this: $$ \frac{\hat{Y_{c}}}{\hat{N_{c}}}=\frac{Y_{c}}{N_{c}}-\theta( \frac{X_{c}}{M_{c}} - \mathbb{E}[R]) $$ $$ \frac{\hat{Y_{t}}}{\hat{N_{t}}}=\frac{Y_{t}}{N_{t}}-\theta( \frac{X_{t}}{M_{t}} - \mathbb{E}[R]) $$ Because $\mathbb{E}[R]$ is difficult to derive and the expectation term is the same for both groups, Statsig substitutes $\mathbb{E}[R]$ with $\frac{X_{c}}{M_{c}}$, transforming the formulas above to: $$ \frac{Y_{cv}(control)}{N_{cv}(control)}=\frac{Y(control)}{N(control)} $$ $$ \frac{Y_{cv}(test)}{N_{cv}(test)} :=\frac{Y(control)}{N(control)} - (\frac{Y(control)}{N(control)} - \theta \frac{X(control)}{M(control)}) + (\frac{Y(test)}{N(test)} - \theta\frac{X(test)}{M(test)}) :=\frac{Y(test)}{N(test)} - \theta\frac{X(test)}{M(test)} + \theta \frac{X(control)}{M(control)} $$ Using the optimal $\theta$, Statsig reduces group-level variance by plugging the parameter back in to calculate the adjustment. Across-group $\theta$ doesn't necessarily reduce variance for one group, or the sum of variances of all groups, but in most cases it does. Simulation shows that 98.3% of metrics saw a decrease with CUPED. Statsig uses CUPED variance when all of the following conditions hold: - Core assumptions of the CUPED model hold; rounding error or other data artifacts can violate this - E(X\_hat) = E(X) - The pooled variance of the adjusted population across groups is < the variance of the unadjusted population - Enough units have pre-experiment values (> 100) - Enough percentage of units have pre-experiment values (> 5%) ================================================================================ # Delta Method URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/delta-method ================================================================================ # Delta Method ## Delta method for ratio metrics Statsig uses the delta method when calculating the variance for variables that have a numerator and denominator. The variance of ratio and mean metrics depends on the numerator and denominator variables, which are typically correlated. For example, consider a _clicks per session_ metric. The number of clicks and the number of sessions are two sets of observations coming from the same group of users, so they aren't independent of each other. To properly account for this correlation, Statsig obtains the variance of a ratio metric _R_ using the delta method: ![Delta method variance formula](https://docs.statsig.com/images/snippets/stats-methods/delta-method/167956015-cc3f9fca-2c4d-410c-bff1-3f13dd16d105.png) where Statsig computes the variance of the numerator and denominator means in the same way as detailed above for count metrics, and the covariance is ![Covariance calculation formula](https://docs.statsig.com/images/snippets/stats-methods/delta-method/167956127-c17017ef-07b2-4f76-88c4-00539eec50a7.png) ## Delta method for relative lifts Statsig may also use the delta method when calculating the confidence interval for relative lifts. The other methodology for calculating confidence intervals for relative lifts is [Fieller Intervals](https://docs.statsig.com/experiments/statistical-methods/methodologies/fieller-intervals). The delta method is a heuristic for Fieller Intervals that converges with a large population. ================================================================================ # Fieller Intervals URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/fieller-intervals ================================================================================ # Fieller Intervals ## Fieller intervals You can use Fieller Intervals as the methodology for calculating confidence intervals for the relative change between test and control group. The Delta Method is an approximation for the variance of a ratio between two variables that Statsig then uses to establish a confidence interval. Fieller Intervals are an exact solution for the confidence interval. In most cases, Fieller Interval results are very similar to results from the Delta Method. Because Fieller Intervals are more accurate, Statsig recommends using this methodology. ## Calculation ### 1: Determine if a Fieller interval is well-defined Before applying Fieller’s Theorem, Statsig checks that the denominator of the relative lift metric $\overline{X_C}$ is significantly distinct from 0. Statsig calculates the parameter $g$: $$ g = \frac{Z_{\alpha/2}^2 \cdot \mathrm{var}(X_C)}{(n_C-1) \cdot \overline{X_C}^2} $$ Where: - $Z_{\alpha/2}$ is the critical value associated with the confidence level you want - $\mathrm{var}(X_C)$ is the variance of the control group metric values - $n_C$ is the number of units in the control group - $\overline{X_C}$ is the mean of the control group metric values When $g$ < 1, the control mean is significantly different from 0, and Fieller intervals apply. ### 2A: Apply Fieller interval formula Since the control and test group results are independent of each other, Statsig can drop covariance terms in Fieller's Theorem. $$ CI(\% \Delta \overline{X} ) = \frac{1}{1-g} \left( \frac{\overline{X_T}}{\overline{X_C}} \pm \frac{Z_{\alpha/2}}{\overline{X_C}} \sqrt{ \frac{\overline{X_T}^2}{\overline{X_C}^2} \cdot \frac{\mathrm{var}(X_C)}{n_C-1} + (1-g)\frac{\mathrm{var}(X_T)}{n_T-1} } \right) - 1 $$ ### 2B: Edge case: control mean not statistically distinct from zero In rare cases (less than 5% of observed metric comparisons on Statsig), g $\geq$ 1, which means the control group’s mean isn’t statistically distinguishable from 0. When $\overline{X_C}$ isn't statistically different from zero, the denominator of the relative lift calculation is unstable. This means that the confidence interval for the percent difference between test and control is unbounded. When the confidence interval is unbounded, Statsig surfaces the relative lift observed during the experiment. $$ \% \Delta \overline{X} = \frac{\overline{X_T}-\overline{X_C}}{\overline{X_C}} $$ ## Enabling Fieller intervals in Statsig Configure the relative confidence interval methodology in _Experimentation Settings_ at the organization level. Changing this setting only affects experiments created after the setting change. ![Experimentation settings configuration interface](https://docs.statsig.com/images/snippets/stats-methods/fieller-intervals/9c8b90f8-1f0b-472f-883d-c3f30bd78696.png) In many cases, the results are effectively the same as using the [Delta Method](https://docs.statsig.com/experiments/statistical-methods/methodologies/delta-method). However, if you're running experiments with small sample sizes or noisy denominators, Fieller Intervals are more reliable, and Statsig strongly recommends using them. In the experiment scorecard, Fieller Intervals appear as shown below. ![Experiment scorecard with Fieller intervals](https://docs.statsig.com/images/snippets/stats-methods/fieller-intervals/1cb4ebb6-0425-49bf-a319-48794d25ce96.png) ================================================================================ # SRM Checks URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/srm-checks ================================================================================ # SRM Checks ## How SRM checks work Sample ratio mismatch (SRM) occurs when the observed allocation of unique users between test groups differs from the expected allocation or "split" of the test. Go to the [Statsig blog post on SRM](https://www.statsig.com/blog/sample-ratio-mismatch) for background. SRM is a signal that there could be unknown bias in the test. Unless you can clearly diagnose the reason for the imbalance, there's no reliable way to know how much this bias affects your results. Statsig runs SRM checks on all experiments and feature gates as part of Health Checks (described in [Health Checks](https://docs.statsig.com/experiments/monitor)). Statsig uses a Chi-squared test to identify whether the split of users between groups indicates a sample ratio mismatch. ![SRM health check results interface](https://docs.statsig.com/images/experiments/srm-checks-health.png) Statsig automatically analyzes data by common dimensions logged by the Statsig SDK to identify potential drivers of SRM. These include sdk\_type, sdk\_version, reason, is\_bot, browser\_name, browser\_version, os, os\_version, and region. ![SRM dimension analysis breakdown](https://docs.statsig.com/images/experiments/srm-checks-dimensions.png) ================================================================================ # Winsorization in Warehouse Native URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/winsorization ================================================================================ # Winsorization in Warehouse Native Statsig Warehouse Native lets you configure winsorization per metric to cap extreme values and reduce outlier noise in experiment results. Winsorization measures the percentile Px of a metric and sets all values over Px to Px. Statsig computes the Px value using all non-zero and non-null unit-level values of the metric. Statsig aggregates metrics from rows or events, then uses the Px'th unit's value as the threshold to adjust other units' values. #### Statsig Cloud At Statsig, the default percentile for winsorization is 99.9%. Winsorization at this percentile reduces the influence of extreme outliers caused by factors such as logging errors or bad actors. Statsig applies winsorization to sum, event count, mean, ratio, and funnel metrics, including imported metrics. Statsig doesn't apply winsorization to Participation or User Accounting metrics. #### Warehouse Native Statsig Warehouse Native lets you configure winsorization per metric and choose the upper and lower bounds to apply. ![Winsorization configuration interface](https://docs.statsig.com/images/snippets/stats-methods/winsorization/6d058842-27f7-4b6b-9bd8-245a5f894f90.png) Statsig applies winsorization to sum, event count, mean, and ratio metrics. ## Metric capping Metric capping is an effective technique for handling outliers. You can define maximum values for a metric for any unit type configured for that metric. Statsig automatically adjusts any value exceeding the cap downward to the cap value. For example, if purchases greater than $10,000 per day shouldn't skew analysis, Statsig adjusts any transaction exceeding that threshold downward to the limit. Metric capping supports Event Count and Aggregation (sum) metric types. ================================================================================ # One-Sided Tests URL: https://docs.statsig.com/statsig-warehouse-native/features/statistics/methodologies/one-sided-test ================================================================================ # One-Sided Tests ## One-sided tests (also known as one-tailed tests and non-inferiority tests) A one-sided test lets you test for a metric moving in only one direction, which you specify in advance. This trade-off gives you additional sensitivity (or power). It differs from the standard Pulse results, which show two-sided results by default. Use cases for one-sided testing include detecting regressions in guardrail metrics and testing for a change where only one direction has meaningful business impact. For example, you may be less interested in detecting whether a new feature reduces crash rates, but very interested in learning whether the new feature increases crash rates. In that case, you're willing to forgo detecting the reduction in favor of better detecting the increase. > **Info:** > > One-sided tests completely disregard the possibility of detecting the metric moving in the direction you don't specify. Instead, they give you higher sensitivity in the direction you're looking, because they allot all your alpha to testing statistical significance in that one direction. This allocation produces one-sided confidence intervals (CIs) that are narrower in the direction of interest than their two-sided counterparts. ## How to enable one-sided tests When setting up an experiment and identifying metrics to measure, the default setting is to run a two-sided test. To change the test type, click the metric name on the experiment setup screen. A popup opens where you can modify the test type and indicate the direction you want to measure. > **Note:** > > V1 doesn't support Bayesian testing yet. ![One-sided test configuration interface](https://docs.statsig.com/images/snippets/stats-methods/one-sided-test/23044f21-6249-4fc1-9895-22111bb16010.png) ## How to read one-sided test results Metrics using one-sided tests appear in Pulse very similarly to two-sided tests. The only difference is that Statsig shows a one-sided CI rather than a two-sided CI. One-sided CIs can be confusing at first. They extend to infinity or negative infinity, which makes sense because Statsig only detects changes in the specified direction. As with all CIs, they indicate that the real mean value of the metric likely falls within this range. Because the CI for a one-sided metric is wide, it's equally useful to read the results as indicating high confidence that the mean value doesn't fall outside the CI. ![One-sided confidence interval visualization](https://docs.statsig.com/images/snippets/stats-methods/one-sided-test/7ab3d680-b4c4-4321-b1fc-cc506b0ab21b.png) ## FAQ #### Why can't I just run two one-sided tests Running two one-sided tests results in a less powerful test. One-sided tests work by allocating the entirety of Type I error (alpha/significance) to one direction. Adding a one-sided test in the other direction reintroduces the chance of making a Type I error in that direction. The result is confidence intervals that appear tighter but actually produce higher rates of decision error than the specified confidence level (default: 95%). #### Why use a one-sided test rather than a two-sided test The choice depends on your use case, metric of interest, and the business impact of any decision. Choose one-sided tests when you plan to act only on changes in one direction and detecting changes in the other direction has no business value. ================================================================================ # CURE URL: https://docs.statsig.com/statsig-warehouse-native/cure/introduction Updated: 2025-09-18 ================================================================================ # CURE CURE (variance Control Using Regression Estimates) is Statsig's extended implementation of [CUPED](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped). CUPED uses pre-experiment data for each experimental unit to control variance observed in an online experiment. CUPED can reduce variance moderately to significantly and can correct for some pre-existing differences between experiment groups. CUPED provides additional statistical power without requiring additional users or experiment runtime. However, CUPED has one major limitation: it relies on pre-experiment data for a given metric to reduce that metric's variance. This means that: - New user experiments can't use the technique - Metrics which aren't autocorrelated don't see significant variance reduction ## What is CUPED Refer to the [CUPED documentation](https://docs.statsig.com/experiments/statistical-methods/methodologies/cuped) or the [CUPED blog post](https://www.statsig.com/blog/cuped). ## How CURE improves on CUPED CURE solves the no-covariate problem by allowing practitioners to specify additional covariates, which the CUPED regression uses. Statsig uses the predictions from this regression to generate an estimator set that is unbiased, but has lower variance than the original estimator. CURE can reduce experiment runtimes more than CUPED alone. When you combine CURE with Statsig's Entity Properties, practitioners can connect existing feature stores to this variance reduction technique. > **Note:** > > Like CUPED, CURE can modify the point estimates of groups, though the total value across all experimental groups sums to the same value as in the unadjusted dataset. > > Expect drift in value between groups, particularly when there are pre-experiment differences and the correlation is high. This drift is the algorithm adjusting for pre-existing deltas in experiment groups. Contact the team in Slack if you have concerns. ## How CURE differs from standard regression This technique is similar to standard regression estimates used in other experimentation tools, but differs in several ways: - Statsig applies CURE across all major experimental surfaces, including experiment scorecards, drill-down explore queries, filtered queries, and power analysis. Applying CURE across these surfaces ensures results match between scorecards and explore queries, which can diverge in tools with incomplete CUPED implementations. - Multivariate regressions enable variance reduction for new users or users without pre-experiment data. - CURE manages feature selection, preventing overfitting issues seen in similar multivariate approaches, and making regression adjustments more transparent. ## How CURE calculates variance reduction The original CUPED implementation by Microsoft [(Deng, et. al.)](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf) is equivalent to an OLS regression with one independent variable. However, the adjustment doesn't need to be a single-variable regression. A regression guarantees identical or lower variance, but any unbiased adjustment is mathematically valid. By calculating the covariance matrix between covariates and experiment outcomes in SQL, you can generate the inputs for multivariate regressions. Use these inputs to adjust post-exposure values in an unbiased manner, meaning the regression is demeaned and uses only pre-experiment data. This yields an estimator with variance less than or equal to the original estimator. Specifically: - if covariates don't exist, nothing happens and the adjusted estimator is identical to the unadjusted - in the worst case where covariates are uncorrelated, the adjusted estimator is identical to the unadjusted - if no additional covariates are applied, CURE is mathematically equivalent to CUPED - if additional covariates are applied that increase the $R^2$ (i.e. portion of explained variance), CURE reduces variance more than CUPED ## CURE for ratio metrics When you combine Statsig's CUPED implementation for ratio metrics with CURE covariates, ratio metrics can use both pre-experimental data and user-provided covariates. With an adjusted formula to calculate the covariance of a ratio random variable to a simple variable, Statsig establishes a multi-covariate regression similar to CURE for simple metrics. The variance and mean adjustments follow the ratio CUPED approach. - As an artifact of the regression, Statsig obtains the shrinkage $R^2$, which it uses to scale the post-adjustment variance. - Statsig constructs the mean adjustment as the inner product of the coefficient vector $\theta$ and the covariate group means $C$. By calculating the difference in adjustment between the test and control group, Statsig adjusts only the test group mean while holding the control group mean the same. ## Data sources When you enable CUPED, pre-experiment metric data is still an input to the CURE regression. CURE allows you to pull data from: - Assignment records: if using end-to-end experiments with Statsig, log user attributes using the SDK, and Statsig exports them for use in CURE. - Entity property sources: use any timestamp-enabled entity property source to provide covariate data. Statsig disables non-timestamped entity property sources to prevent data leakage into CURE. Entity property sources are a convenience feature; you could alternatively manage joining user features to your assignment data. In practice, this feature enables use cases such as providing your own table of regression estimates as covariates, similar to DoorDash's [CUPAC](https://careersatdoordash.com/blog/improving-experimental-power-through-control-using-predictions-as-covariate-cupac/) approach. ## Configuration You can manage CURE in two places: - Project Settings under Experimentation: the default CURE Covariates setting lets you specify covariates to use across any CUPED-enabled metric in your project. - Advanced Settings in the Experiment Settings page: specify covariates for a single experiment. ## Datasets Statsig surfaces CURE information in experiment diagnostics, providing details on coefficients and relevant covariates for any given metric. View the adjustments used under the Regression Adjustment job, and check the coefficients table to run your own analysis on the regression model. ## Outputs View the DAG history to see the exact coefficients used and the table where Statsig stores them. Statsig also renders an in-console explanation of which variables contributed to variance reduction and by how much, which helps users decide which features to use. ## Known limitations Like CUPED, CURE can modify the point estimates of groups. The total value across all experimental groups sums to the same value as in the unadjusted dataset. However, you can expect drift in value between groups, particularly when there are pre-experiment differences and the correlation is high. This drift is the algorithm adjusting for pre-existing deltas in experiment groups. Contact the team in Slack if you observe a concerning change. ## Feature selection Statsig uses Lasso regression to select important features, reducing the computational cost of adjusting the unit metric level and controlling for multicollinearity. View the contribution of each feature on the variance reduction card. The estimated proportion of variance reduction is: $$ \text{Variance Reduction}_{i} = \frac{{Coefficient_{i}}^2*Var(feature_{i})}{\sum {Coefficient_{i}}^2*Var(feature_{i})} $$ by that, $$ \sum \text{Variance Reduction}_{i} = 100\% $$ ## Winsorization Statsig winsorizes data before and after regression to reduce the effect of extreme outliers on the regression. Without this step, high-influence data dominates the analysis. ## References - [From Augmentation to Decomposition: A New Look at CUPED in 2023](https://arxiv.org/html/2312.02935v1) - [Improving Experimental Power through Control Using Predictions as Covariate (CUPAC)](https://careersatdoordash.com/blog/improving-experimental-power-through-control-using-predictions-as-covariate-cupac/) - [Agnostic notes on regression adjustments to experimental data: Reexamining Freedman’s critique](https://projecteuclid.org/journals/annals-of-applied-statistics/volume-7/issue-1/Agnostic-notes-on-regression-adjustments-to-experimental-data--Reexamining/10.1214/12-AOAS583.full) ================================================================================ # Get Started With CURE URL: https://docs.statsig.com/statsig-warehouse-native/cure/cure-setup Updated: 2025-09-18 ================================================================================ # Get Started With CURE ## Defaults By default, CURE runs a univariate regression when you enable it, which is the same as the [standard implementation of CUPED](https://www.exp-platform.com/Documents/2013-02-CUPED-ImprovingSensitivityOfControlledExperiments.pdf). To add additional covariates ## Project defaults In project settings under Experimentation, specify default covariates for your company: ![Project Settings](https://docs.statsig.com/images/cure/project_setting.png) You can source covariates from the assignment source for the experiment, or from Entity Property Sources. Properties with an Entity Property Source name attached come from a property source and Statsig always includes them on the experiment. Properties without an EPS come from an assignment source and apply if the column exists on the assignment source of a given experiment. ## Experiment settings Per-experiment, specify additional covariates or remove covariates specific to your analysis: ![Experiment Settings](https://docs.statsig.com/images/cure/experiment_setting.png) Statsig populates this list from the experiment assignment source columns and relevant Entity Property Sources. ## Metric:Metric One tool this framework enables is metric:metric covariates, such as using units' pre-experiment clicks as a covariate for units' in-experiment revenue. Statsig doesn't use this approach for several reasons: - Consistency: adding a new metric to your analysis shouldn't significantly alter the results of other metrics. - Unnecessary complexity: if you have key metrics that function as covariates, explicitly provide these for all metrics as a covariate in an entity property source. This approach achieves the same result without opaque outputs from unknown metric covariances. Statsig recommends explicitly including key metric covariates as numerical covariates rather than adding arbitrary covariates based on metric selection. Contact the team in Slack to discuss further. ## Preventing adjustments You can turn off CUPED in your Pulse results, and can create a project-level setting to enforce this behavior. CURE still runs when CUPED is off, which incurs some compute cost. To avoid running CURE, turn it off on a given metric by clearing the CUPED option in the metric's setup page. ![Metric Settings](https://docs.statsig.com/images/cure/metric_setting.png) ================================================================================ # Autotune URL: https://docs.statsig.com/statsig-warehouse-native/features/autotune Updated: 2025-09-18 ================================================================================ # Autotune Autotune uses a multi-armed bandit to automatically shift traffic toward the best-performing variant for a single goal metric. In Warehouse Native, Statsig pulls Autotune success events from a Metric Source and computes results in your warehouse. Setup is similar to cloud [Autotune](https://docs.statsig.com/autotune/overview). ## Creating an Autotune To set up an Autotune on Warehouse Native, start by defining your objective. The objective can be an _event_ or a _value_ from a Metric Source. For detailed instructions, refer to [how to set up a Metric Source](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources). You can also specify the optimization direction (Maximize or Minimize) to determine how Autotune evaluates variant performance. ![Autotune configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/autotune/autotune-config.png) 1. Navigate to the [Experiments section](https://console.statsig.com/experiments) in the sidebar of the Statsig Console. 2. Click on the [Autotune tab](https://console.statsig.com/autotune) at the top. 3. Click the Create button and enter the name and description of the Autotune Experiment that you want to create. 4. Select an ID Type for your Experiment. 5. Create and name your variants for your Autotune Experiment. Statsig returns the variant listed as Control/Default when the Autotune Experiment isn't running. 6. Select your Metric Source that you defined earlier as shown below. ![Autotune metric source configuration interface](https://docs.statsig.com/images/statsig-warehouse-native/features/autotune/autotune-metric-source.png) You can configure the following parameters: | Parameter | Description | | --- | --- | | Exploration Window | The initial time period where Autotune splits traffic equally. Useful for noisy or temporal metrics where hourly swings can bias initial measurements. | | Attribution Window | The maximum duration between the exposure and success event that counts as a success. Statsig recommends 1 hour for most applications; adjust if you expect the success event to lag the exposure event by several hours. | | Winner Threshold | The "probability of best" threshold a variant must reach for Autotune to declare it the winner, stop collecting data, and direct all traffic. A lower value results in faster decisions but increases the probability of selecting the wrong winner. | Click **Create** to finalize the setup. 7. You've configured the Autotune, and it's ready. Click **Start** when you're ready to launch your Autotune test. ================================================================================ # Contextual Bandit URL: https://docs.statsig.com/statsig-warehouse-native/features/contextual-bandit ================================================================================ # Contextual Bandit A contextual bandit (Autotune AI) personalizes the variant Statsig serves each user, based on context features you pass on the user object. The bandit learns from outcomes to improve its predictions. In Warehouse Native, outcomes come from a Metric Source in your warehouse, and Statsig trains the model on data it processes in your warehouse. Use a contextual bandit when the best variant depends on who the user is. To find one winning variant for all users, use [Autotune](https://docs.statsig.com/statsig-warehouse-native/features/autotune) instead. ## How Warehouse Native changes a contextual bandit Setup and SDK usage match cloud [contextual bandits](https://docs.statsig.com/autotune/contextual/introduction). Warehouse Native changes where data comes from and where Statsig processes it. | Area | Warehouse Native behavior | | --- | --- | | Outcomes | Outcomes must come from a Metric Source that contains your outcome events. You can't log outcome events with Statsig. | | Exposures | Statsig exports exposures on demand for each load, up to the first million exposures. After the first million, Statsig exports exposures in daily batches. | | Training | Statsig processes data in your warehouse and trains the model on an anonymized feature set. Training pipelines run hourly. | | Data latency | If your outcome data lags by more than 24 hours, bandit exploration can slow down significantly. | ## Create a contextual bandit Before you start, set up a [Metric Source](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources) that contains your outcome event. 1. In the Statsig console, go to _Experiments > Autotune_, then click **Create**. 2. Enter a name and, optionally, a goal that explains why you're running the bandit. 3. Set the autotune type to **Contextual**. 4. Choose the outcome type: - **Event Occurring**: For discrete outcomes, such as clicks or checkouts. - **Event Value**: For continuous outcomes, such as revenue or latency. Set whether a higher or lower value is better. 5. Select the Metric Source that contains your outcome event, and add optional filters. For **Event Value**, select the field that holds the value. 6. Review the training settings, such as the exploration window, attribution window, feature list, and excluded feature list. For descriptions of each setting, refer to [Training settings](https://docs.statsig.com/autotune/contextual/getting-started#training-settings). 7. Define the variants that your code fetches. ## Serve variants in code Fetch the assigned variant with `getExperiment`, and pass context features in the `custom` field of the user object. Statsig needs a few hundred units to train a model. Training starts only after the attribution window for those units ends. For supported SDKs, refer to [Get started with Autotune AI](https://docs.statsig.com/autotune/contextual/getting-started). For a code example, refer to [Use the Contextual Autotune in code](https://docs.statsig.com/autotune/contextual/getting-started#use-the-contextual-autotune-in-code-python-example). To monitor a running bandit, refer to [Monitoring your Contextual MAB](https://docs.statsig.com/autotune/contextual/monitoring). For how Statsig builds and scores the model, refer to [Contextual Bandit Methodology](https://docs.statsig.com/autotune/contextual/methodology). ================================================================================ # Meta-Analysis URL: https://docs.statsig.com/statsig-warehouse-native/features/meta-analysis Updated: 2025-09-18 ================================================================================ # Meta-Analysis ## How meta-analysis works Meta-analysis identifies patterns across the many experiments your teams run. Common questions it helps answer include: - How hard is a metric to move? - Are there more sensitive proxies for the metric you care about? - How are teams performing relative to each other? Statsig has worked with multiple organizations to help them run thousands of trustworthy experiments per year. These tools are useful whether you're running 50 experiments a year or 5000. To influence the roadmap, reach out in [Slack](https://statsig.com/slack). ## Experiment timeline view This view lets you filter to experiments a team has run. At a glance you can answer questions like: 1. What experiments are running now? 2. When are they expected to end? 3. What % of experiments ship Control vs Test? 4. What is the typical duration? 5. Do experiments run for their planned duration - or much longer or shorter? 6. Do experiments impact key business metrics - or only shallow or team level metrics? 7. How much do they impact key business metrics? ![Experiment timeline view dashboard](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/d1e1db49-18b4-46af-93f7-4c0e58c5bdb0.png) ## Metric impact (batting average) The "batting average" view shows how easy or hard a metric is to move. You can filter to a set of shipped experiments and see how many moved a metric by 1% vs 10%. As with other meta-analysis views, you can filter by team, tag, or statistical significance. Common uses include: - Validating whether a claim that the next experiment will move a metric by 15% is reasonable. - Establishing realistic goals based on past ability to move the metric. ![Metric batting average analysis chart](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/72f987a4-02ba-4937-9f3d-06892c55e4e9.png) ## Metric correlation view This view plots two metrics on the same chart, where each data point represents one experiment's impact. Use it to assess whether the metrics tend to move together. Often the metric you want to move isn't very sensitive and takes time to measure. Finding more sensitive, faster-to-measure proxy metrics is useful for running experiments. You can also remove outliers, filter to a team's experiments, or download the underlying dataset. In this example: "Checkouts" is the target metric, but it isn't very sensitive. "AddToCart" correlates well with "Checkouts", while "ViewItemDetail" doesn't. ![Metric correlation scatter plot](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/016285b0-cdc4-46a4-8fdf-204b20b5b0e4.png) ![Metric correlation analysis interface](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/c29e5d7d-d8b6-4841-acaf-8d521a5db398.png) ## Metric insights This view lets you pick a metric and see all experiments and feature rollouts that impact this metric. [Learn more](https://docs.statsig.com/experiments/exploring-results/aggregated-impact). ![417923655-430563dc-4794-4d69-a314-36c76a6fcf74](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/8d61ada1-bf1f-41cf-b52b-f01d24052568.png) ## Knowledge bank The Knowledge Bank is a searchable repository of experiment learning across teams. Use it to find shipped, healthy experiments, gain context on past work, and generate ideas for new experiments. It gives new team members a way to explore experiments by keyword when the structured meta-analysis views don't fit the need. The meta-analysis tools provide more structured discovery, but free text search also works here. ![Knowledge bank search interface](https://docs.statsig.com/images/snippets/stats-methods/meta-analysis/860430c4-a754-4ff8-aa85-8bf49a755801.png) ================================================================================ # Practical Use Cases URL: https://docs.statsig.com/statsig-warehouse-native/features/use-case Updated: 2025-09-18 ================================================================================ # Practical Use Cases Statsig Warehouse Native supports practical experiment workflows such as filtering experiment results to new users only and analyzing logged-in metrics when your experiment exposures happen at a logged-out grain. Each example pairs a common scenario with the queries and configuration Statsig uses to solve it. ## How can I define and filter results to 'new users' only ### Scenario I want to filter the experiment results to new users only: A user is 'new' if they had never visited the website before this experiment exposed them. If the first time the user visited the website was after the exposure timestamp in this experiment, the user was a 'new user'; otherwise the user was an existing user. ### Solution Assuming you have a logging table that contains every visit with a relative timestamp (`logging`), and another table with all users' `user_id` values (`user`), first create an Entity Property with the following logic: ```sql select distinct user_id, 'new' as new_user, timestamp('1900-01-01') as timestamp from user -- you can add filters here to include only targeted population only union all select distinct user_id, 'existing' as new_user, timestamp as timestamp from logging ``` Select **Run Query** to return a table like this. Select **Save Results** to use this Entity Property across all experiments and gates to filter or group experiment results by whether a user is new or existing. | user\_id | new\_user | timestamp | | --- | --- | --- | | A | new | 1900-01-01T00:00:00+00:00 | | A | existing | 2024-01-01T10:10:18+00:00 | | B | new | 1900-01-01T00:00:00+00:00 | --- ## How can I analyze logged-in metrics when my experiment exposures are at logged-out grain ### Scenario I want to run an experiment to find out which version of my website design leads to a higher signup rate among new visitors. The experiment assignment occurs when a logged-out user visits my website, and the experiment exposes them to one of the design variants. When a user decides to sign up, they receive a new and unique logged-in user ID. To calculate the conversion rate (CVR) accurately and consistently, I need a reliable way to map the logged-out IDs to the corresponding logged-in IDs. This mapping allows me to attribute each signup to the correct experiment variant and evaluate which design performs better in driving conversions. ### Solution Statsig supports two commonly used approaches for this mapping, each suited to different business scenarios: **Strict 1:1 Mapping**: Keeps only records where there is a unique, unambiguous mapping between the logged-out ID and the logged-in ID. Statsig discards any records with duplication (for example, multiple logged-out IDs mapping to the same logged-in ID or the reverse). Use this approach when accuracy and clarity are the top priorities and data duplication is rare. **First Touch Mapping**: When a logged-in ID maps to multiple logged-out IDs, retains only the first association and discards the rest. Better suited for scenarios where you want to preserve as much data as possible and duplications are common (for example, users frequently access the website from multiple devices or sessions). For either mapping approach, you need to create a mapping between the logged-out ID and the logged-in ID. Set up an Entity Property that contains both IDs, or create an exposure assignment source with columns for both ID types. #### Step 1: Advanced settings for your experiments When setting up your experiment, navigate to _Setup > Advanced Settings_, and select your Secondary ID type (the log-in user ID in this scenario). ![Experiment setup advanced settings selecting secondary ID](https://docs.statsig.com/images/statsig-warehouse-native/features/use-case/76f83c44-0389-4441-a5fc-bf29b9cab119.png) #### Step 2: Identify the mapping mode that suits your need ![ID resolution mapping mode options](https://docs.statsig.com/images/statsig-warehouse-native/features/use-case/e49a030e-4933-4019-80f3-812c46cdd493.png) #### Step 3: Choose your Entity Property Source ![Entity property source selection for ID mapping](https://docs.statsig.com/images/statsig-warehouse-native/features/use-case/abceaaf3-b15d-481e-9e7f-abc8a5c2cef3.png) - **\[Recommended\]** Create a new Entity Property Source for your ID Resolution mapping if you haven't already. Go to _Data > Entity Properties_. You can either enter an existing table with the ID mappings or write a new query to create the mappings with the following logic: ```sql SELECT stable_id, user_id, timestamp FROM id_mapping ``` - You can also choose **"None"** to use your assignment source for the mapping. Create your new assignment source by going to _Data > Assignment Sources_. Statsig doesn't recommend this option because it becomes more complex to manage as your experiments scale. ================================================================================ # MEX on Warehouse Native URL: https://docs.statsig.com/statsig-warehouse-native/features/mex-on-warehouse-native Updated: 2025-09-18 ================================================================================ # MEX on Warehouse Native [Metrics Explorer](https://docs.statsig.com/product-analytics/overview) (or MEX) is Statsig's analytics solution. With Warehouse Native, MEX integrates directly on top of your tables to provide analysis on the same datasets you use for experimentation. > **Info:** > > Contact the team to enable Metrics Explorer in your account. ## Functionality ### [Drill-Down and Filter](https://docs.statsig.com/product-analytics/overview) Filter and group by fields to calculate measures as timeseries, bar-charts, and more. ### [Funnel Analysis](https://docs.statsig.com/product-analytics/funnels) Run funnel analysis to understand how users move through your product. ### [Group By Experiment](https://docs.statsig.com/product-analytics/drilldown#drilling-down) View arbitrary timeseries and rollups grouped by experiment membership, allowing more observational analysis of what happened during your experiment. ### [Retention Chart](https://docs.statsig.com/product-analytics/drilldown#retention) Analyze user retention reports to understand how effectively your product maintains user engagement over time. ### [Distribution Chart](https://docs.statsig.com/product-analytics/drilldown#distribution) View distribution charts to help you visualize the range of user experiences across your product. ### Save, share, and view SQL Save analyses and share them with coworkers. Viewing the SQL gives you access to the queries Statsig ran internally, which you can use as a starting point for deeper analysis. ## Use it with replays MEX works together with [Session Replay](https://docs.statsig.com/session-replay/overview) to help you understand the user behavior you measure in your experiments. ================================================================================ # Geotests URL: https://docs.statsig.com/statsig-warehouse-native/geotests/introduction Updated: 2025-09-18 ================================================================================ # Geotests Geotests are specialized experiments that allow you to target users based on geographic location. These tests let you evaluate features, content, or experiences across any type of geographic area you specify. By splitting your campaign across DMAs or postal codes, you can measure incrementality even when an ads platform doesn't provide incrementality measurement. Run a geotest when you can't run an A/B test at a per-user level. Common causes include: - You don't have per-user control over who sees what, for example, a third-party marketing platform like Meta or Google Ads. - You can't attribute metrics to individuals, for example, you can't tie total store foot traffic to which users received your email campaign. One of the most common use cases is marketing: you can't A/B test on third-party ad platforms, but geo-testing lets you evaluate the incrementality of your program. Geotests are particularly valuable for businesses with global audiences who need to optimize their product for regional differences in user needs, preferences, or regulatory requirements. ## Why use Geotests Statsig's Geotesting combines the flexibility and statistical rigor of Statsig with your own data sources in your warehouse. Geotesting: 1. Uses the data already in your warehouse, avoiding expensive and time-consuming exports. 2. Includes an automated Experiment Designer to help you select where and when to run your campaign. 3. Exports your campaign definition to your campaign platform, making setup faster and less error-prone. 4. Automates analysis of the campaign, providing statistical rigor to measure incrementality. ## GeoLift Statsig's Geotesting builds on top of Geolift, a best-in-class industry tool for running geospatial experimentation for marketing. [GeoLift](https://facebookincubator.github.io/GeoLift/) is an open-source package from Meta that many use to infer causal relationships in timeseries data. It builds on advancements made in prior packages like Google’s [Causal Impact](https://google.github.io/CausalImpact/CausalImpact.html) package. Statsig uses GeoLift in its implementation of Geotesting, allowing you to connect your own internal metrics and feed them into the analysis package. ## Related resources - [GeoLift](https://facebookincubator.github.io/GeoLift/) - [CausalImpact](https://google.github.io/CausalImpact/CausalImpact.html) - [Synthetic Control Methods (wiki)](https://en.wikipedia.org/wiki/Synthetic_control_method) - [Causal inference using synthetic controls (medium)](https://medium.com/data-science-at-microsoft/causal-inference-using-synthetic-controls-d96a890c83a7) ================================================================================ # Get Started with Geotests URL: https://docs.statsig.com/statsig-warehouse-native/geotests/geotests-setup ================================================================================ # Get Started with Geotests Setting up a geotest in Statsig Warehouse Native takes five steps, from defining geo types to running analysis: 1. Define your Geo Types 2. Configure your Metric Source 3. Create and Configure 4. Evaluate Design Options 5. Run Analysis ## Define your geo types First decide on one or more geo types relevant to your business. Some of the most common are Postal Codes and DMAs (Designated Market Areas), but Statsig allows you to define any arbitrary geo type. ![Geo types configuration interface](https://docs.statsig.com/images/geotests/geo_types_settings.png) ## Configure your metric source Assuming you've already added a [metric source](https://docs.statsig.com/statsig-warehouse-native/configuration/metric-sources/) to Statsig, you can next indicate which column(s) represent the geo type(s) you've created. ![Geo column mapping configuration screen](https://docs.statsig.com/images/geotests/geo_column_mapping.png) ## Create and configure - Navigate to your _Experiments_ page. - Select **+ Create**. - In the modal, select **Analyze** to analyze existing experiment data in your warehouse. ![Experiment creation modal with analyze option](https://docs.statsig.com/images/geotests/CreateXP.png) - Enter a name and description for your experiment. - Choose **Geotest** as the experiment type from the dropdown. Fill in the remaining fields as usual. ![Geotest experiment type selection dropdown](https://docs.statsig.com/images/geotests/SetType.png) In the Setup tab: - Define your hypothesis. - Set the Geo Type (e.g., country\_id) from one of the types you've defined in your project and metric sources. - Choose your Primary Metrics. > **Note:** > > **Important Metric Types** > > Statsig limits GeoTest metrics to SUM, COUNT, and COUNT\_DISTINCT types. The inference techniques involved in synthetic control methodologies require this limitation. ![Geotest experiment setup configuration screen](https://docs.statsig.com/images/geotests/SetupXP.png) Configure: - Expected Treatment Start/End Dates - Pre-treatment duration (days) - Effect Size % (the MDE you want to measure; smaller MDEs make finding a valid design harder) - Type of Test: 1-sided or 2-sided - Alpha level (the type I error rate you want, inverse of significance) - Optionally enable Budgeting - Additional advanced modeling parameters for users familiar with [Geolift's Advanced API](https://github.com/facebookincubator/GeoLift/blob/main/R/pre_test_power.R) ![Experiment configuration settings interface](https://docs.statsig.com/images/geotests/XPAdvancedConfigs.png) ## Generate design options When your initial settings are ready, click **Use Experiment Designer** to begin the design process. ![Experiment designer launch button](https://docs.statsig.com/images/geotests/StartDesigner.png) The Experiment Designer automates the process of evaluating potential splits of geos. Creating a new design set involves 3 steps: 1. **Define your targeting** 2. **Set any Inclusion or Exclusion overrides** 3. **Define your date range** ![Geographic limitations configuration interface](https://docs.statsig.com/images/geotests/CreateDesign.png) ### Define targeting Targeting allows you to define the set of geos eligible for inclusion in your experiment. By default, Statsig pulls the unique set of geo types from your metric source from the last 90 days. You can add custom filters based on columns in your metric source. For example, you can filter geos to those in a certain region or by transactions that occurred in a certain language. ![Geotest targeting filters for eligible regions](https://docs.statsig.com/images/geotests/targeting.png) You can also manually specify a set of geos yourself. The geo id types must match those in your metric source exactly. ### Set inclusion or exclusion overrides After defining your targeting set, you can manually assign any of these geos to treatment or control groups. ![Override interface assigning specific geos to treatment or control](https://docs.statsig.com/images/geotests/targetingoverwrites.png) For example, when testing a new marketing campaign, you might want to include Austin because you've already signed a contract. You might exclude New York, Los Angeles, or Washington D.C. because of local regulations. Specify these constraints in the designer, and all design options considered conform to these rules. ### Define date range Define the data range of your design dataset. This date range defines what data Statsig pulls as the historical baseline to train a synthetic control model. A good guideline is that your design data duration should be at least 4x the expected duration of your treatment period. A longer duration achieves good fits and maximizes the sensitivity and power of your experiments. ### Advanced options - **Rolling Lookback Windows**: Control how many iterative simulations to run to evaluate power. For instance, a value equal to 5 simulates power for the last five possible tests in the date range. Corresponds to `lookback_window` in the GeoLift API. - **Dynamic Time Warping**: Control how much the synthetic control model depends on auto-correlations in the metric vs. correlations between different geos on the same days. A value of 1 focuses exclusively on the metric while a value of 0 (default) relies on correlations only. Corresponds to `dtw` in the GeoLift API. - **Control Cell Size Requirements**: Sets limits on the share of primary metric value from geos in any considered control group. If not set, Statsig analyzes all design options regardless of their size. For example, on a Revenue metric, a control size range of \[50%, 90%\] means Statsig considers only design options where 50% to 90% of revenue is in the designated control geos. Corresponds to `holdout` in the GeoLift API. ## Evaluate design options After Statsig creates a Design Option Set (usually a few minutes), Statsig shows it in your _Experiment Designs_ tab. All design option sets Statsig generates appear here, so you can look through prior design iterations as needed. ![Experiment designer options display](https://docs.statsig.com/images/geotests/DesignerOptions.png) Click into a completed design set (e.g. “Design Set 3”). - Review the ranked recommendations for your best design options. - Compare MDE, Power, Cost and Control/Test Allocation. - Click **View Cell Details** to expand and see specific geo assignments. - Review additional model performance details. - Select your design using the radio button, then click **Save Design to Experiment**. ![Design option selection interface](https://docs.statsig.com/images/geotests/DesignOption.png) ## Run analysis ![Geotest analysis results dashboard](https://docs.statsig.com/images/geotests/AnalysisResults.png) ================================================================================ # Geotesting Methodology URL: https://docs.statsig.com/statsig-warehouse-native/geotests/methodology Updated: 2025-09-18 ================================================================================ # Geotesting Methodology ## How geotesting differs from standard A/B testing Standard A/B testing relies on a few core assumptions: 1. You can reliably and randomly split your users into similar groups. 2. While each group has heterogeneity inside it, random user-level variations average out at larger sample sizes, resulting in homologous (similar) groups. 3. You control the treatment each group receives, and there's no interference between groups. When these core assumptions are true, the treatment effect is the only observable difference between the groups. Measure each group’s mean value and find the difference between them. There are times however when these assumptions don’t hold: - You can’t control and scope your intended treatment to the user level - You don’t know who the users are - You can’t track outcomes at the user level Running geographically-based campaigns is a prime example that often features at least some of these violations. Examples include: - You can’t randomly split some classic marketing, like billboards, between test and control users at a given location. You can’t track who sees them and how they act afterwards. - Some digital campaigns might be able to split users 50/50 (if the platform allows it), but without user-level data that you can tie to outcomes of interest, you can’t determine how the two groups performed. ## Using synthetic controls “Geotesting” here refers to an experimental framework that relies on a different basic setup than AB tests: 1. Split your users into geographical boundaries at some useful level (zip codes, states, countries, etc.). 2. Apply a known treatment in some “treatment” geos, and no treatment in some “control” geos. 3. Use the control geos to figure out what would have happened in the treatment geos had no treatment been applied (that is, “synthetic” results). 4. Measure the delta in the treatment geos between the actual and synthetic values. Determining what would have happened is the most difficult part of this setup. Deducing things that didn't occur is generally unreliable, but in some circumstances there is enough predictability in a system to make it possible. Geotesting relies on sufficient correlations between control and test geos to make predicting this “counterfactual” possible. Some geos tend to share general trends and seasonality. Example: nearly all zip codes in the United States exhibit similar quantities of mail sent on any given day. If you were to split zip codes 50/50, you could reasonably infer that the two groups would see similar trends. ## Estimation approach There are many ways to estimate unknown data from other known data, depending on a multitude of factors. In the case of Geotesting, the data has: - timeseries data that is autocorrelated (i.e. data is correlated from one day to the next within a group) - timeseries data that is correlated between groups - regular seasonal patterns that repeat at regular intervals - granular data from among many distinct geographies Plotting a metric of interest for a set of relevant geographies can show these relationships clearly. ![Example data from the GeoLift package walkthrough. ](https://docs.statsig.com/images/whn/GeosPreTest.png) Example data from the GeoLift package walkthrough. But what happens when a campaign runs in only some of these geos? How can you tell if a fluctuation in this graph is random noise or a statistically significant result? ![A marketing campaign that starts on day 91 (black dotted line) could have affected the treatment cities of Chicago and Portland. But how can you tell any real effect from all the noise?](https://docs.statsig.com/images/whn/GeosTest.png) A marketing campaign that starts on day 91 (black dotted line) could have affected the treatment cities of Chicago and Portland. But how do you distinguish any real effect from all the noise? Causal inference modeling addresses this question. A variety of models and methods exist for this purpose. The basic steps are: - Split your geos into test and control groups. - Using the pre-treatment period data, train a model on the control data to predict how the treatment geos behave. - Using the post-treatment period data for the control geos, create a “synthetic control” dataset to predict how the treatment geos would have behaved after the treatment event. - Subtract the synthetic data from the actual observed data to determine the induced effects of your treatment on the treatment geos. When your training data can produce strong models that can predict metric outcome well, you end up with strong estimates of an induced effect: ![Geotest period split diagram showing pre-treatment and post-treatment phases](https://docs.statsig.com/images/whn/Period_Split.png) ![Subtracting the modeled Synthetic Control values from the observed Treatment values reveals any incremental effect for the Treatment geos.](https://docs.statsig.com/images/whn/Incremental_Effects.png) Subtracting the modeled Synthetic Control values from the observed Treatment values reveals any incremental effect for the Treatment geos. ================================================================================ # Other Features URL: https://docs.statsig.com/statsig-warehouse-native/features/other-useful-features Updated: 2025-09-18 ================================================================================ # Other Features The following Statsig features work almost identically in Cloud and Warehouse Native. They're worth exploring as you integrate with Statsig: - [Feature Gates](https://docs.statsig.com/feature-flags/overview) are a best-in-class tool for managing feature release and targeting. Statsig Warehouse Native can automatically analyze feature gates with partial rollouts as experiments. - [Session Replay](https://docs.statsig.com/session-replay/overview) is a powerful tool for viewing how users interact with your product, giving richer context to changes in user behavior. - [Layers](https://docs.statsig.com/experiments/layers-overview) let you create mutually exclusive experiments for cases where changes in one experiment could collide with another and create a bug or odd result. - [Dynamic Configs](https://docs.statsig.com/dynamic-config/working-with) provide server-side configuration tools with optional targeting and integrate naturally with experiments. - [Admin](https://docs.statsig.com/access-management/introduction) tools let you control projects, teams, and user access across Statsig. ================================================================================ # Statsig SDK Quickstart Guide URL: https://docs.statsig.com/sdks/quickstart ================================================================================ # Statsig SDK Quickstart Guide This quickstart guide is meant to get your implementation up and running as quickly as possible. Because of that, it only implements a standardized set of information. For a more detailed guide, go to the [Statsig SDK Getting Started](https://docs.statsig.com/sdks/getting-started) guide or read about choosing between [client or server SDKs](https://docs.statsig.com/sdks/client-vs-server). #### React 1. **Install Statsig packages** ```bash npm install @statsig/react-bindings ``` 2. **Wrap your child components** Update your app's default function (typically App.tsx or Layout.tsx) so that the StatsigProvider component identifier wraps all child components. ```tsx import { StatsigProvider } from "@statsig/react-bindings"; // [!code ++] export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <StatsigProvider // [!code ++] sdkKey={"client-MY-STATSIG-CLIENT-KEY"} // [!code ++] user={{ userID: "quickstart-user" }} // [!code ++] loadingComponent={<div>Loading...</div>}> // [!code ++] {children} </StatsigProvider> // [!code ++] ); } ``` > **Note:** > > This example assumes client-side React. For server-side rendering, refer to the [Next.js docs](https://docs.statsig.com/client/Next). 3. **Add a client key** Create a client API key in the [Statsig console Settings](https://console.statsig.com/api_keys). Copy and paste it to replace `<REPLACE_WITH_YOUR_CLIENT_KEY>` in the code snippet from the previous step. 4. **Confirm the basic functions are working** #### Check a Gate Create a gate on the [Feature Gates page](https://console.statsig.com/gates) in console and confiirm it works from within the code: ```jsx const { client } = useStatsigClient(); return ( <div>Gate is {client.checkGate('check_user') ? 'passing' : 'failing'}.</div> ); ``` #### Get an Experiment Value Create an Experiment on the [Experiments page](https://console.statsig.com/experiments) with the console: ```jsx const { client } = useStatsigClient(); const experiment = client.getExperiment('my_experiment_name'); return ( <div>Headline Parameter: {experiment.get('my_experiment_parameter_name', 'fallback_value')}.</div> ); ``` #### Log an Event Use events to power metrics in your experiment or gates. You don't need to set up events in console first. Add them to your code: ```jsx const { client } = useStatsigClient(); return <button onClick={() => client.logEvent("button_click")}>Click Me</button> ``` ## Next steps You've set up the Statsig SDK in React. Continue with the SDK Quickstart tutorials, or go to the full [Next.js](https://docs.statsig.com/client/Next) or [React](https://docs.statsig.com/client/React) SDK reference. #### JS snippet 1. **Paste the code snippet** In the `<head>` section of your website, paste the following code snippet: ```html <script src="https://cdn.jsdelivr.net/npm/@statsig/js-client@3/build/statsig-js-client+session-replay+web-analytics.min.js?apikey=<REPLACE_WITH_YOUR_CLIENT_KEY>"></script> ``` 2. **Add a client key** Create a client API key in the [Statsig console Settings](https://console.statsig.com/api_keys). Copy and paste it to replace `<REPLACE_WITH_YOUR_CLIENT_KEY>` in the code snippet from the previous step. 3. **Confirm the basic functions are working** #### Check a Gate First, create a gate on the [Feature Gates page](https://console.statsig.com/gates) in console and confiirm it works from within the code: ```jsx window.Statsig.instance().checkGate("my_feature_gate_name"); ``` > **Note:** > > Wait for the SDK to initialize before checking a gate to ensure it has fresh values. One way to do this is to wait for the ["values\_updated"](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) event. #### Get an Experiment Value First, create an Experiment on the [Experiments page](https://console.statsig.com/experiments) from within your console: ```jsx window.Statsig.instance().getExperiment("my_experiment_name").get('my_experiment_parameter_name'); ``` > **Note:** > > Wait for the SDK to initialize before getting an experiment to ensure it has fresh values. One way to do this is to wait for the ["values\_updated"](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) event. #### Log an Event Use events to power metrics in your experiment or gates. You don't need to set up events in console first. Add them to your code: ```jsx window.Statsig.instance().logEvent("my_checkout_event_name", "event_value_item_1234", {"event_metadata": "my_metadata"}) ``` ## Next steps You've set up the Statsig JavaScript snippet. You can now: - [Record events](https://docs.statsig.com/webanalytics/overview) - [Watch session replays](https://docs.statsig.com/session-replay/overview) - [Run experiments](https://docs.statsig.com/experiments/overview) - [Use feature flags](https://docs.statsig.com/feature-flags/overview) Go to the [Javascript SDK reference](https://docs.statsig.com/client/javascript-sdk) for more information. #### Python 1. **Install the Statsig package** ```shell pip install statsig-python-core ``` 2. **Initialize the Statsig SDK** ```python from statsig_python_core import Statsig, StatsigOptions options = StatsigOptions() options.environment = "development" statsig = Statsig("<REPLACE_WITH_YOUR_SERVER_SECRET_KEY>", options) statsig.initialize().wait() statsig.shutdown().wait() ``` 3. **Add a server secret key** Create a server secret key in the [Statsig console Settings](https://console.statsig.com/api_keys). Copy and paste it to replace `<REPLACE_WITH_YOUR_SERVER_SECRET_KEY>` in the code snippet from the previous step. 4. **Confirm the basic functions are working** #### Check a Gate First, create a gate on the [Feature Gates page](https://console.statsig.com/gates) in console and confiirm it works from within the code: ```python user_object = StatsigUser(user_id="123", email="testuser@statsig.com") //add any number of other attributes gate_value = statsig.check_gate(user_object, "my_feature_gate_name"): ``` #### Get an Experiment Value First, create an Experiment on the [Experiments page](https://console.statsig.com/experiments) from within your console: ```python user_object = StatsigUser(user_id="123", email="testuser@statsig.com" my_experiment_object = statsig.get_experiment(user_object, "my_experiment_name") my_experiment_parameter_value = my_experiment_object.get_string('my_experiment_parameter_name') ``` #### Log an Event Use events to power metrics in your experiment or gates. You don't need to set up events in console first. Add them to your code: ```python user_object = StatsigUser(user_id="123", email="testuser@statsig.com" statsig.log_event( user=user_object, event_name="my_checkout_event_name", value="SKU_12345" ) ``` ## Next steps You've set up the Statsig SDK in Python. Continue with the SDK quickstart tutorials, or go to the full [Python SDK Reference](https://docs.statsig.com/server-core/python-core). #### Node 1. **Install the Statsig package** ```bash npm i @statsig/statsig-node-core ``` 2. **Initialize the Statsig SDK** ```jsx // Basic initialization const statsig = new Statsig("<REPLACE_WITH_YOUR_SERVER_SECRET_KEY>"); await statsig.initialize(); // or with StatsigOptions const options: StatsigOptions = { environment: "staging" }; const statsigWithOptions = new Statsig("secret-key", options); await statsigWithOptions.initialize(); ``` 3. **Add a server secret key** Create a server secret key in the [Statsig console Settings](https://console.statsig.com/api_keys). Copy and paste it to replace `<REPLACE_WITH_YOUR_SERVER_SECRET_KEY>` in the code snippet from the previous step. 4. **Basic Usage** #### Check a Gate First, create a gate on the [Feature Gates page](https://console.statsig.com/gates) in console and confiirm it works from within the code: ```js const userObject = new StatsigUser({ userID: "123", email="testuser@statsig.com" }); const is_gate_enabled = statsig.checkGate(userObject, "my_feature_gate_name"): ``` #### Get an Experiment Value First, create an Experiment on the [Experiments page](https://console.statsig.com/experiments) from within your console: ```js const userObject = new StatsigUser({ userID: "123", email="testuser@statsig.com" }); const myExperimentObject = statsig.getExperiment(userObject, "my_experiment_name") const myExperimentParameterValue = myExperimentObject.getValue('my_experiment_parameter_name') ``` #### Log an Event Use events to power metrics in your experiment or gates. You don't need to set up events in console first. Add them to your code: ```js userObject = StatsigUser(user_id="123", email="testuser@statsig.com" statsig.logEvent( userObject, "my_checkout_event_name", "SKU_12345" //value for the event ); ``` ## Next steps You've set up the Statsig SDK in Node.js. Continue with the SDK quickstart tutorials, or go to the full [Node.js SDK reference](https://docs.statsig.com/server-core/node-core). #### +24 more SDKs ## Explore SDKs Statsig offers SDKs for a wide variety of platforms: ### Client-side SDKs ### [JavaScript](https://docs.statsig.com/client/javascript-sdk) Browser JavaScript ### [React](https://docs.statsig.com/client/React) Client-Side React ### [React Native](https://docs.statsig.com/client/ReactNative) Bare React Native SDK ### [Next.js](https://docs.statsig.com/client/Next) Next.js SSR, SSG & Client-Side ### [Angular](https://docs.statsig.com/client/Angular) Angular bindings for Javascript SDK ### [Swift](https://docs.statsig.com/client/iosClientSDK) iOS, MacOS, tvOS SDK ### [Android](https://docs.statsig.com/client/Android) Android Kotlin/Java SDK ### [.NET Client](https://docs.statsig.com/client/DotNet) Client SDK for .NET framework ### [Roku](https://docs.statsig.com/client/Roku) Roku Brightscript SDK ### [Unity](https://docs.statsig.com/client/Unity) Unity game engine SDK ### [Dart/Flutter](https://docs.statsig.com/client/Dart) Flutter/Dart Mobile App SDK ### [C++ Client](https://docs.statsig.com/client/CPP) C++ client-side SDK ### Server-side SDKs ### [Node.js](https://docs.statsig.com/server-core/node-core) Node.js server SDK ### [Java](https://docs.statsig.com/server-core/java-core) Java server SDK ### [Python](https://docs.statsig.com/server-core/python-core) Python server SDK ### [Go](https://docs.statsig.com/server/go) Go server SDK ### [Ruby](https://docs.statsig.com/server/ruby) Ruby server SDK ### [.NET Server](https://docs.statsig.com/server-core/dotnet-core) .NET server SDK ### [PHP](https://docs.statsig.com/server-core/php-core) PHP server SDK ### [Rust](https://docs.statsig.com/server-core/rust-core) Rust server SDK ### [C++ Server](https://docs.statsig.com/server-core/cpp-core) C++ server SDK ### Integrations ### [Webflow](https://docs.statsig.com/guides/webflow-sidecar-ab-test) Webflow integration ### [Shopify](https://docs.statsig.com/guides/shopify-ab-test) Shopify integration ### [Segment](https://docs.statsig.com/integrations/data-connectors/segment) Segment data connector ### [Rudderstack](https://docs.statsig.com/integrations/data-connectors/rudderstack) Rudderstack connector ### [Hightouch](https://docs.statsig.com/integrations/data-connectors/hightouch) Hightouch integration ### [mParticle](https://docs.statsig.com/integrations/data-connectors/mparticle) mParticle connector ### [Framer](https://docs.statsig.com/guides/framer-analytics) Framer integration ### [Slack](https://docs.statsig.com/integrations/slack) Slack notifications ### [Integrations](https://docs.statsig.com/integrations/introduction) View more integrations ================================================================================ # Identify Users URL: https://docs.statsig.com/sdks/identify-users ================================================================================ # Identify Users ## Why identify users? When you run an experiment, roll out a feature, or log events, Statsig needs to know who the user is to determine: - Targeting: whether a feature gate should pass or fail for a given user - Experiment bucketing: which group a user belongs to - Analytics: how many unique users triggered an event Pass a User Object to Statsig SDKs to provide this information. Statsig also requires the User Object for experiment analysis. Statsig allocates users to the test or control group by an ID. The Statsig stats engine then uses the same ID on the users' events to calculate metric differences between the test and control groups. ## Basic user object Start by defining a basic user object: #### Basic User Object ```jsx { "userID": "u_123", // required for most setups "email": "user@example.com" // optional } ``` Add more attributes when you need finer targeting. Refer to [Enriched attributes](#enriched-attributes) for details. ## Identifying users in client SDKs In client SDKs, you initialize the SDK for a single User Object at any one time. If you call a method like `checkGate` or `getExperiment` before you initialize the SDK, results are incorrect. You also see warnings in the Statsig Console on the diagnostics tab of any gate or experiment. Initialization requires a network request, which you start by calling the `initialize()` method, or in React, `useClientAsyncInit()`. In client apps with asynchronous logic, wait for initialization to complete before checking a gate. For example, in React: #### React Example ```jsx export function App() { const { client, isLoading } = useClientAsyncInit( YOUR_CLIENT_KEY, user={ userID: "u_123"} // user object ); if (isLoading) { return <div>Loading...</div>; } return ( <StatsigProvider client={client}> <MainApp /> </StatsigProvider> ); } ``` The user object can change after initialization: for example, the user logs in and now has a `userID`. When the user object changes, call the `updateUser` method to refresh values from the Statsig server. For example, in React: #### Update User ```jsx const { user, updateUserSync } = useStatsigUser(); return <div> <p>Current User: { user.userID }</p> <button onClick={() => updateUserSync({userID: 'some-other-user'})}> Update User </button> </div>; ``` If you don't update the user before checking gates or experiments, gates and experiments evaluate using the previous user object, which can produce unexpected results. Any attribute added to the user object is targetable in the Statsig console. To target users based on `email`, `companyID`, or other attributes, add those attributes to your user object. ## Identifying users in server SDKs In server SDKs, pass a User Object with each evaluation or event call, such as `logEvent`, `checkGate`, or `getFeatureGate`. The server SDK holds the necessary rules in memory for evaluation. Pass all attributes needed to evaluate your gate or experiment on every call. Statsig SDKs don't store or enrich attributes from previous calls. Example (Node.js) #### Node.js Example ```jsx import { Statsig } from "statsig-node"; await Statsig.initialize("<YOUR_SERVER_KEY>"); const user = { userID: "u_123", custom: { plan: "premium" } }; const gate = await Statsig.checkGate(user, "beta_feature"); if (gate) { console.log("Gate passed"); } ``` ## Enriched attributes Statsig enriches the user object with useful attributes to expand targeting options. Examples of what Statsig can enrich: - `stableID`: an anonymous identifier which identifies a unique device on client SDKs - `country`: derived from IP or device locale - `appVersion`: pulled from mobile SDKs - `browser` / `OS`: captured from user agent - and more... To learn about all available fields (including `custom` attributes, `customIDs`, and `privateAttributes`), go to the [StatsigUser object](https://docs.statsig.com/sdks/user) docs. ================================================================================ # Create your first feature flag URL: https://docs.statsig.com/guides/check-gate ================================================================================ # Create your first feature flag A Feature Gate, also known as a feature flag, safely controls the rollout of new features to your users without deploying additional code. Common uses include shipping new UI elements, API endpoints, or product features. This tutorial walks through checking your first Feature Gate in Statsig end to end, from creating it in the console to evaluating it in your code with `checkGate`. By the end of this tutorial, you have: - Created a Feature Gate in the Statsig console, with targeting rules to enable the feature for a segment of Users - Initialized a Statsig Client SDK - Checked a single feature gate in your code using the `checkGate` function You need a [Statsig account](https://console.statsig.com/sign_up) and an existing application you can integrate the Statsig Client SDK into. ## Step 1: In the Statsig console ### Create a Feature Gate This example adds a Feature Gate to deploy a new UI element to a user with the "statsig.com" email domain. You can follow along with a specific feature if you have your own scenario in mind. 1. Navigate to [Feature Gates](https://console.statsig.com/gates) in the Statsig console. 2. Then, click on **Get Started** if you don't have any Feature Gates set up yet, or **Create** to create a new one. 3. Name your gate "Example Gate". The SDK also uses this name to identify the Feature Gate later. 4. Enter a description for your Feature Gate. It's good practice to describe it in a way that other teammates can easily understand. For example: "This Feature Gate is for launching an example feature for Statsig employees only." ### Create a targeting rule When you create a Feature Gate in Statsig, Statsig excludes all users from the feature by default. To enable the feature, add a rule that lets users pass the gate. The steps below walk through adding that rule in the console. 1. In the console, on the page for the Feature Gate you just created, click on **Add New Rule**. 2. Give this rule a **Name**, such as "Statsig Users Only". 3. Select **Email** as the targeting criteria to target users based on their email address. 4. In the User section of the dropdown, select the **Any Of (Case Insensitive)** operator, and then add `statsig.com` for email-based user targeting. 5. Set the **Pass Percentage** to `100%`. Doing so ensures that all users with the `statsig.com` email domain pass the Feature Gate and see the new feature. 6. Click **Add Rule** to add this rule to your Feature Gate. 7. Next, hit **Save** on the bottom right to commit these changes to the Feature Gate. You can now test this feature gate by configuring the User object in the "Test Gate" section. ### Create a Client API Key Now that you've set up the Feature Gate from the console, integrate it into your product with the Statsig SDK. First, create a new Client API key to use in your product. 1. Navigate to [**Keys & Environments**](https://console.statsig.com/api_keys) in the Statsig console. You can also find this by going to **Settings** at the bottom left of the Statsig console. 2. Scroll down to **API Keys**. Click on **Generate New Key**. 3. In the dropdown, select **Client**. 4. Copy the Client API Key you just created to your clipboard. ## Step 2: In your code ### Initialize the Statsig SDK Now that you have a Client API Key, integrate the Statsig Client SDK into your product. This tutorial uses the React SDK, but you can use a different SDK if you prefer. > **Tip:** > > Statsig offers over 20 client and server-side SDKs. Check out the full list of [SDKs](https://docs.statsig.com/sdks/quickstart#all-sdks) to find the one that best fits your needs. 1. Install the Statsig React SDK using your preferred package manager. This tutorial uses npm. #### npm ```bash npm install @statsig/react ``` 2. Import the SDK in your `App.js` file: #### Import SDK ```tsx import { StatsigProvider } from "@statsig/react-bindings"; ``` 3. Wrap your app's content within the `StatsigProvider` component. The following code snippet also creates a [User](https://docs.statsig.com/sdks/user) object for targeting your Feature Gate. #### Setup Provider ```tsx function App() { return ( <StatsigProvider sdkKey="client-KEY" user={{ userID: "Example", email: "example@statsig.com" }}> <div>Hello world</div> </StatsigProvider> ); } export default App; ``` 4. Make sure to also replace `client-KEY` with the Client API Key you copied in Step 3. ### Check your Feature Gate Evaluate a Feature Gate in your product code by getting the client with the `useStatsigClient` hook and calling `checkGate`. If you aren't sure where to place your flag, refer to [Best Practices for feature flags](https://docs.statsig.com/feature-flags/best-practices). 1. Add the following code to your `App.js` file. In this snippet, the `example_gate` is the name of the Feature Gate you created in Step 1. #### Check Gate ```tsx const { client } = useStatsigClient(); return ( <div>Gate is {client.checkGate('check_user') ? 'passing' : 'failing'}.</div> ); ``` 2. Run your app. The app renders "Gate is passing" because the [targeting rule](#create-a-targeting-rule) targets all users with the `statsig.com` email domain, and this client's User object uses that same domain. 3. After you set up your gate, [monitor the impact of your new feature rollout](https://docs.statsig.com/feature-flags/view-exposures) or [manage flag lifecycles](https://docs.statsig.com/feature-flags/feature-flags-lifecycle). ## Run your first A/B test This tutorial configured a simple feature flag. To do more complex feature rollouts or metric analysis, continue to the next tutorial to run your first A/B test in Statsig. ================================================================================ # Run your first A/B test URL: https://docs.statsig.com/guides/abn-tests ================================================================================ # Run your first A/B test An A/B test in Statsig compares two or more variants against a control to measure which performs best on your metrics. This tutorial walks through creating and implementing your first experiment end to end, from configuring it in the console to checking it in your application code. Set one up when you want to validate a change with real production traffic before rolling it out. By the end of this tutorial, you have: - Created a new user-level **Experiment** in the Statsig console, with **parameters** set for a Control and Test group - **Checked the experiment** in your application code using the **Statsig Client SDK** `getExperiment` function You need a [Statsig account](https://console.statsig.com/sign_up) and the [Statsig Client SDK](https://docs.statsig.com/sdks/quickstart) installed in an existing application. ## Step 1: In the Statsig console ### Create an experiment 1. Log in to the Statsig console at https://console.statsig.com/ and navigate to Experiments in the left-hand navigation panel. 2. Click on the **Create** button and enter the name `Quickstart Experiment` and enter a brief hypothesis. For example, "A new homepage banner will improve engagement." 3. Click **Create**. ### Set up scorecards In the Experiment Setup tab, fill out scorecards for the metrics you want to track. For this SDK tutorial, leave most settings at their default values. 1. In the **Hypothesis** card, enter a hypothesis for what you are testing: "Showing a homepage banner will increase user engagement, measured by daily\_stickiness." 2. In the **Primary Metrics** card, add a new metric called `daily_stickiness`. 3. Leave the **Secondary Metrics** and **Duration** settings at their default values. For more details on experiment setup, refer to [Creating an experiment](https://docs.statsig.com/experiments/create-new). ### Configure groups and parameters By default, the experiment runs on 100% of users: Statsig assigns 50% to a Control group and 50% to a Test group. 1. In the **Groups and Parameters** card, create a parameter called `enable_banner` and select the type as `Boolean`. 2. Set `enable_banner` to `false` for the Control group and `true` for the Test group. 3. Click **Save**. 4. Select **Save** in the bottom right to finalize this experiment setup. 5. The experiment isn't live yet. To launch it, select **Start** at the top of the page. This makes production traffic eligible for the experiment. > **Note:** > > You can't configure experiment parameters and groups after launching an experiment. To test in a staging environment, refer to [using environments](https://docs.statsig.com/guides/using-environments/#configuring-environments). ## Step 2: In your application code ### Check the experiment > **Note:** > > This tutorial assumes you have already [installed the Statsig Client SDK](https://docs.statsig.com/sdks/quickstart) in an existing application. Use a Statsig Client SDK to check a user's assigned experiment group and parameters in real time. The SDK changes the user's experience according to the assigned variant. In this case, fetch the value of the `enable_banner` parameter created in Step 1. #### Check Experiment ```tsx const quickstartExperiment = myStatsigClient.getExperiment(user, "quickstart_experiment"); // the second parameter is the default fallback value if the experiment is not found if (quickstartExperiment.get("enable_banner", false)) { showBanner(); } ``` In this snippet, users assigned to the Test group see the banner. Users assigned to the Control group don't. You don't need to [hardcode the experiment group name](https://docs.statsig.com/experiments/implementation/getting-group) ("Control" or "Test") in the code. The Statsig SDK automatically fetches the experiment configuration and returns the correct value based on the user's variant. ## Step 3: Monitor experiment diagnostics When you run your code, the SDK calls the `showBanner()` function for users in the Test group. Navigate to your experiment in the Statsig console and select the **Diagnostics** tab to see a live log stream of checks and events from your application. Refer to the [Diagnostics tab documentation](https://docs.statsig.com/experiments/implementation/getting-group#diagnostics-rule-meanings) for more information. ![Experiment Diagnostics](https://docs.statsig.com/images/guides/abn-tests/b0ab8c0e-4f13-4b2b-bf58-1f8a09d8d4a7.png) ## Step 4: Read experiment results Within 24 hours of starting your experiment, the **Results** tab in the Statsig console shows cumulative exposures and their impact on the scorecard metrics configured in the **Setup** panel. Here's a sample of what that looks like: ![Example experiment results](https://docs.statsig.com/images/guides/abn-tests/7e203d73-dbf9-4f27-87fb-b05269dd4173.png) ## Log custom events and metrics In this tutorial, you used `daily_stickiness` as the primary metric. Statsig logs this metric automatically, so you don't need to log it explicitly. To measure other events or custom metrics that occur after the experiment check, log them to Statsig. Continue to the next tutorial to learn how to log custom events and metrics with the Statsig SDK. ### Related guides - [Initialization techniques for Statsig SDKs](https://docs.statsig.com/client/concepts/initialize) - [Run a device-level experiment](https://docs.statsig.com/guides/first-device-level-experiment) - [Run an experiment on custom unit ID types](https://docs.statsig.com/guides/experiment-on-custom-id-types) - [Configure the Statsig SDK for staging environments](https://docs.statsig.com/guides/using-environments) ================================================================================ # Log your first custom event URL: https://docs.statsig.com/guides/logging-events ================================================================================ # Log your first custom event Custom events record the user actions you care about, and Statsig turns them into metrics for web analytics, product analytics, and experimentation. Log an event with the `logEvent` API in any Statsig client or server SDK. You can then view the event in [Metrics Explorer](https://docs.statsig.com/product-analytics/overview), turn it into [custom metrics](https://docs.statsig.com/metrics/how-metrics-work), visualize it in [dashboards](https://docs.statsig.com/product-analytics/dashboards), or use it in [experiment results](https://docs.statsig.com/metrics/pulse) to show the impact of your experiments. Statsig provides several ways to get started: 1. Statsig web SDKs offer [autocaptured web analytics](https://docs.statsig.com/webanalytics/overview) to automatically log common events like pageviews, clicks, and more. 2. Statsig offers [integrations](https://docs.statsig.com/integrations/introduction) to connect your existing event data in Segment, mParticle, and other sources. 3. All Statsig client and server SDKs provide a simple `logEvent` API to instrument your own events in your app or webserver. For general guidance on event logging and core concepts, continue reading or go to the "Logging events through SDKs" section. ## Identifying users with the StatsigUser object Many analytics platforms have a concept of "identifying" a user. In Statsig, the `StatsigUser` object represents this concept. You set the `StatsigUser` object at initialization time in client SDKs, or with each event in server SDKs. The [`StatsigUser`](https://docs.statsig.com/sdks/user) is a set of properties that describe the user. The JSON definition is consistent across all SDKs and integrations: #### StatsigUser Object ```json { "userID": "123", "customIDs": {}, "email": "user@example.com", "ip": "192.168.1.1", "userAgent": "Mozilla/5.0...", "country": "US", "locale": "en-US", "appVersion": "1.0.0", "custom": {}, "privateAttributes": [] } ``` Statsig reserves the `userID` field for a unique identifier for the user. Use the ID of the logged-in user. The Group analytics section explains `customIDs`. The other fields support targeting and evaluation for feature flags, and you can also use them for custom metrics and data queries in Metrics Explorer. ## Group analytics Another core concept in analytics is grouping. A user can belong to a company, organization, page, or other entity. In Statsig, the `customIDs` field represents groups. It's a dictionary that can contain multiple IDs for a single user. For example, a user can have the following `customIDs`: #### Group Example ```json { "userID": "123", "customIDs": { "companyID": "456", "projectID": "abc" } } ``` Statsig computes all metrics at the user level and also for each custom identifier. This means you can run experiments at a company level, where all users in a company receive the same experience, and compare the impact on company-level metrics. You can also use Metrics Explorer to slice metrics at the company level rather than the user level, if you have configured a `customID` for the group. For example, the Statsig project can display console page views at a user or company level: ![Viewing Console Page Views at a User Level](https://docs.statsig.com/images/guides/logging-events/67719f66-63cb-41c7-8d83-d2a567738a84.png) To set up a new "group" or "customID": 1. Go to your [project settings](https://console.statsig.com/settings). 2. Locate the "Custom IDs" section and hit "edit". ![CustomIDs in project settings](https://docs.statsig.com/images/guides/logging-events/e26cc341-13c2-4b78-898f-02d56bfc2474.png) 3. Name the new `customID` and add a description so other members of your project understand its purpose. 4. Start logging events with that customID in the `customIDs` field of the StatsigUser object. > **Note:** > > You must provide the set of all IDs on each StatsigUser object. ## Best practices ### Set all known IDs on each StatsigUser object To generate metrics for each user and group, Statsig requires all IDs on each `StatsigUser` object. Pass all identifiers for the user at client SDK initialization time or when calling `logEvent` in a server SDK, so each identifier contributes to the correct metrics. If you use a logged-out identifier for anonymous users, continue passing that identifier after the user logs in and you populate `userID`. Passing the logged-out identifier after login lets gates or experiments targeting that identifier continue bucketing the user correctly. It also lets Statsig calculate metrics at both the logged-out and logged-in levels. ### Deduplicating custom events Statsig doesn't provide a way to deduplicate custom events that you log. ### Naming conventions Consistency is the most important aspect of event naming. An inconsistent events catalogue becomes difficult to navigate. Statsig accepts any naming convention (for example, `Page View`, `PageView`, `Page-view`, or `page_view`), but the recommended format is `page_view`: lowercase, no spaces. You can't use special characters in event names. Statsig drops events that contain the following character set: `"\\[\]{}<>#=;&$%|\u0000\n\r"`. Using the recommended convention avoids duplicate entries with different casing and ensures compatibility with downstream systems connected through integrations. ### What to measure For experimentation and product analytics, log events that correspond to user actions. How you classify events depends on your goals: 1. Avoid high-cardinality event names if you have a small user base, because sparse data reduces the reliability of metrics. For example, an eCommerce website should use a generic `product_page_view` event rather than a separate event name for every product page. Store contextual page information in the `optional_event_metadata` object. 2. If you have a well-defined user funnel, log each step as a separate event. 3. If you have a less defined user journey, log generic events (for example, `page_view`) and add more detail to the value field (the primary dimension of interest) or the `optional_event_metadata` object. ## Logging events through SDKs All Statsig SDKs provide an API to log events. The API looks like this: #### JavaScript ```js statsig.logEvent( event_name, optional_event_value, optional_event_metadata ); ``` Where event name describes a notable event in your product, like `sign_up`, `achievement_unlocked`, `add_to_cart`, `check_out`, etc. Events can optionally include an event value: for example, the type of achievement unlocked, the name of the product added to cart, or the price of the item purchased. In experiments, the value field generates an automatic breakdown of the event when there are fewer than 8 distinct values. The metadata field lets you specify additional details about the event. The following examples show how a `logEvent` call looks: #### JavaScript Example ```js statsig.logEvent( 'add_to_cart', // Name 19.99, // Price { item_id: 'BC22010', cart_size: '2', user_segment: 'first_time_purchaser', } ); ``` #### C# Example ```csharp StatsigClient.LogEvent( "level_completed", // Event Name 11, // Level number new Dictionary<string, string>() { { "score", "452" } } ); ``` > **Info:** > > **Size limits on event payload** There are limits to how large each event field can be: > > | Field type | Limit | > | --- | --- | > | Object fields | 4096 (stringified length) | > | String fields | 64 (length) | Refer to the [SDK reference](https://docs.statsig.com/sdks/getting-started) for more details on logging events in your language. ================================================================================ # SDK Getting Started URL: https://docs.statsig.com/sdks/getting-started ================================================================================ # SDK Getting Started This guide describes how to fully implement your Statsig instance with SDKs. If you want a faster implementation, read the [SDK Quickstart](https://docs.statsig.com/sdks/quickstart) guide. Statsig's SDKs are the in-code tool you'll use to show experiment variants, flag features, and log key business metrics. Statsig's SDKs: - **Abstract the complexity:** Statsig handles caching, retry mechanisms, and networking. - **Encourage best practices:** Built around parameters and language-specific best practices. - **Broad deployment support:** 30+ SDKs across clients, servers, the edge, and more. ## When to use Statsig SDKs ### 1. Targeting and assignment Decide who sees new features and experiment variants. Target based on any user attributes (for example, location or device type) or environment-level attributes to control rollouts and experiment enrollment. Statsig assigns each user deterministically, so the same user gets a consistent experience across sessions and devices as long as you pass a stable identifier. You can also layer multiple targeting rules and set overrides to force specific users into a variant for testing or QA. ### 2. Logging events Log key business metrics to power experiment and product analytics. Events flow into Statsig automatically. For web-based platforms (for example, JavaScript, React), Statsig also supports [Autocaptured events](https://docs.statsig.com/webanalytics/overview). Attach a value and custom metadata to each event so you can build precise metrics and segment results later. Because metrics are defined in the Statsig console, you can create new metrics from events you already log without shipping additional code. ## Choose between client and server SDKs Statsig offers both client-side and server-side SDKs, each suited to different use cases: - **Client-side SDKs**: Designed for user-facing applications where you log events directly from the browser or mobile app. These SDKs operate in real time and provide instant feedback on user behavior. - **Server-side SDKs**: Designed for backend services. Use server-side SDKs to control experiments, feature flags, and log server-side events. Server-side SDKs provide more control for use cases involving system-level actions or business logic. For a detailed comparison, go to the [Client vs Server SDK Overview](https://docs.statsig.com/sdks/client-vs-server). For frameworks like **Next.js** that bridge client and server-side logic, go to the [Next.js SDK](https://docs.statsig.com/client/Next) guide. ## Available SDKs Statsig offers SDKs for a wide variety of platforms: ### Client-side SDKs ### [JavaScript](https://docs.statsig.com/client/javascript-sdk) Browser JavaScript ### [React](https://docs.statsig.com/client/React) Client-Side React ### [React Native](https://docs.statsig.com/client/ReactNative) Bare React Native SDK ### [Next.js](https://docs.statsig.com/client/Next) Next.js SSR, SSG & Client-Side ### [Angular](https://docs.statsig.com/client/Angular) Angular bindings for Javascript SDK ### [Swift](https://docs.statsig.com/client/iosClientSDK) iOS, MacOS, tvOS SDK ### [Android](https://docs.statsig.com/client/Android) Android Kotlin/Java SDK ### [.NET Client](https://docs.statsig.com/client/DotNet) Client SDK for .NET framework ### [Roku](https://docs.statsig.com/client/Roku) Roku Brightscript SDK ### [Unity](https://docs.statsig.com/client/Unity) Unity game engine SDK ### [Dart/Flutter](https://docs.statsig.com/client/Dart) Flutter/Dart Mobile App SDK ### [C++ Client](https://docs.statsig.com/client/CPP) C++ client-side SDK ### Server-side SDKs ### [Node.js](https://docs.statsig.com/server-core/node-core) Node.js server SDK ### [Java](https://docs.statsig.com/server-core/java-core) Java server SDK ### [Python](https://docs.statsig.com/server-core/python-core) Python server SDK ### [Go](https://docs.statsig.com/server/go) Go server SDK ### [Ruby](https://docs.statsig.com/server/ruby) Ruby server SDK ### [.NET Server](https://docs.statsig.com/server-core/dotnet-core) .NET server SDK ### [PHP](https://docs.statsig.com/server-core/php-core) PHP server SDK ### [Rust](https://docs.statsig.com/server-core/rust-core) Rust server SDK ### [C++ Server](https://docs.statsig.com/server-core/cpp-core) C++ server SDK --- ## How to install your SDK 1. **Select your SDK**: Choose the client or server SDK that fits your platform from the lists above. 2. **Follow the installation guide**: Each SDK has an installation guide that walks you through setup. 3. **Start experimenting**: After you integrate the SDK, set up feature flags, run experiments, and log events for analysis. To run an experiment, follow the [experiment process overview](https://docs.statsig.com/experiments/process-overview), which lists each step from sizing the experiment through making a decision. If you have questions or need help with installation, reach out in the [Slack community](https://statsig.com/slack). ================================================================================ # User (StatsigUser) Object URL: https://docs.statsig.com/sdks/user ================================================================================ # User (StatsigUser) Object ## Introduction to the StatsigUser object The StatsigUser object is the sole input you provide to SDKs to target gates and assign users to experiments. To target on an attribute, add it to your user object. Assembling this data is an important part of SDK setup. Provide as much information as practical, because each additional field can enrich your analyses and expand targeting options. Statsig also infers some information about each user from other traits (for example, Statsig resolves IP addresses into countries). ## Usage example in Node.js #### Node.js Example ```jsx //Create a user object const user = new StatsigUser({ userID: "12345", email: "vincent@statsig.com"}); //Use it in getExperiment() const my_experiment = statsig.getExperiment(user, "my_experiment_name") //<- any attribute you pass, you can target on ``` ### I passed that attribute before: why do I need to pass it again? You can view a specific user's historical attributes for analytics purposes through [User Profiles](https://docs.statsig.com/product-analytics/users-tab) in the Statsig console. You can't use historical attributes for targeting or gate/experiment evaluation at runtime. Statsig evaluates gates and experiment buckets based **only on the information you provide at the time of the check.** Millisecond evaluation performance depends on having all information available at request time, rather than querying historical data or storing large amounts of state in memory. ## User attributes #### Client SDKs You can explicitly supply all user attributes, and the SDK can infer some from a user's device or connection. Supplying one always overrides an inferred value. | Key | Description | Example | Client SDK Support | Auto-infer | | --- | --- | --- | --- | --- | | `userID` | ID representing a unique user. Statsig uses this ID to guarantee targeting consistency for Feature Gates and Experiments and to evaluate experiment results. If `User ID` doesn't exist yet, leave this empty; Statsig uses a `Stable ID` persisted locally for evaluations. | `your_user_id` | All | | | `email` | Email of the user. | `marcos@statsig.com` | All | | | `userAgent` | User agent of the browser. The SDK decodes this to determine the Browser and Operating System of the user's context. The SDK infers this if not provided. | `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.40 Safari/537.36` | Web | ✔ | | `ip` | IP address of the user. Inferred from the request to /initialize if not provided | `192.168.1.101` | All | ✔ | | `country` | 2-letter country code of the user. This can be supplied or inferred, and you can target based on the country code in both cases. When inferred, the country code follows ISO-3166. | `US` | All | ✔ | | `locale` | Locale of the user. When using the Android or iOS SDK, the SDK infers this if not provided. | `en_US` | Mobile | ✔ | | `appVersion` | Version of the app the user is using. When using the Android or iOS SDK, the SDK infers this if not provided. | `1.0.1` | Mobile | ✔ | | `systemName` | When using the Android/iOS SDKs, the SDK automatically assigns this, but you can also provide an explicit operating system to override. | `Android` | All | ✔ | | `systemVersion` | When using the Android/iOS SDKs, the SDK automatically assigns this, but you can also provide an explicit OS version to override. | `15.4` | All | ✔ | | `browserName` | When using the Web SDK, the SDK automatically assigns this, but you can also provide an explicit Browser Name to override. | `Chrome` | Web | ✔ | | `browserVersion` | When using the Web SDK, the SDK automatically assigns this, but you can also provide an explicit Browser Version to override. | `45.0` | Web | ✔ | | `custom` | Dictionary that can contain key/value pairs that can be used for Feature Gate targeting. Statsig stores this dictionary and makes it available after targeting. | `{subscriber: "yes", ...}` | All | | | `privateAttributes` | Dictionary that can contain key/value pairs that can be used for Feature Gate targeting. Statsig does **not** store this dictionary after using it for targeting, and removes it from any `log_event` calls. | `{sensitive_field: "sensitive_information", ...}` | All | | | `customIDs` | Dictionary that can contain key/value pairs used as the randomization unit ID for experiments that are set up using these IDs instead of the `User ID`. | `{account_id: "23456555", company_id: "company_xyz"}` | All | | ### How to override the stable ID Client SDKs generate a `stableID` for logged-out or device-level targeting. If you already manage a durable device identifier, override the SDK-generated value before or during initialization so Statsig uses your identifier for stable ID-based evaluations. #### JavaScript ```tsx import { StatsigClient, StatsigUser } from '@statsig/js-client'; const user: StatsigUser = { userID: 'a-user', customIDs: { stableID: 'my-custom-stable-id', }, }; const client = new StatsigClient('client-sdk-key', user); await client.initializeAsync(); ``` #### Android ```kotlin val options = StatsigOptions(overrideStableID = "my-custom-stable-id") Statsig.initialize(app, "client-sdk-key", user, options = options) ``` #### iOS ```swift let options = StatsigOptions(overrideStableID: "my-custom-stable-id") Statsig.initialize(sdkKey: "client-sdk-key", user: user, options: options) ``` > **Note:** > > When you override the Stable ID in a client SDK, the SDK persists that value locally and reuses it on later sessions unless you clear local storage or reinstall the app. #### Server SDKs You can explicitly supply all user attributes, and the SDK can infer some from a provided IP Address or User Agent. Supplying one always overrides an inferred value. | Attributes | Description | Example | Auto Infer | | --- | --- | --- | --- | | `userID` | ID representing a unique user. Statsig uses this ID to guarantee targeting consistency for Feature Gates and Experiments and to evaluate experiment results. | `your_user_id` | | | `email` | Email of the user | `marcos@statsig.com` | | | `userAgent` | User agent of the browser. The SDK decodes this to determine the Browser and Operating System of the user's context | `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.40 Safari/537.36` | | | `ip` | IP address of the user | `192.168.1.101` | | | `country` | 2 letter country code of the user | `US` | ✔, from IP | | `locale` | Locale of the user | `en_US` | ✔, from IP | | `appVersion` | Version of the app the user is using | `1.0.1` | | | `custom` | Dictionary that can contain key/value pairs that can be used for Feature Gate targeting. Statsig stores this dictionary and makes it available after targeting | `{skill_level: "5", is_subscriber:"false" ...}` | | | `privateAttributes` | Dictionary that can contain key/value pairs that can be used to evaluate feature gate conditions and segment conditions. Statsig does **not** store this dictionary after using it for targeting, and removes it from any log\_event calls | `{sensitive_field: "sensitive_information", ...}` | | | `customIDs` | Dictionary that can contain key/value pairs used as the randomization unit ID for experiments that are set up using these IDs instead of the `User ID` | `{account_id: "23456555", company_id: "company_xyz"}` | | ### How to override "Operating System" and "Browser" explicitly Operating system and browser are two default targeting options in Statsig. When you set the `userAgent` field, server SDKs parse the OS and browser information from it. To set these values explicitly, provide them either at the top level of the user object or inside the `custom` object. Some language type systems may not allow the top-level option. Use these keys: - Operating System: os\_name - OS Version: os\_version - Browser Name: browser\_name - Browser Version: browser\_version You can set these values either of the following ways in the user object: #### Example ```json { "userID": "uuid", "os_name": "Android", // top level "custom": { "os_name": "iOS" } } ``` If you explicitly set either of these fields, it takes precedence over the value inferred from the `userAgent` field. ### Have sensitive user PII data that shouldn't be logged? The StatsigUser object includes a `privateAttributes` field, which is a key/value dictionary for setting private user attributes. Statsig uses attributes in `privateAttributes` only for evaluation and targeting, and removes them from any logs before sending them to the Statsig server. For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. Add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ### Time-based conditions All SDKs (server and client-side) support Unix timestamps in milliseconds to evaluate time-based conditions (After time, Before time). Convert your DateTime field to a standard format before evaluation. Statsig has added ISO timestamp support to some server SDKs: - `java-server` SDK v1.6.0 and later: supports [DateTime fields in `ISO_INSTANT` format](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT) - `go` SDK v1.12.1 and later: supports [DateTime fields in `RFC3339` format](https://pkg.go.dev/time#pkg-constants) - `python` SDK: supports epoch time in seconds. The `time.time()` function may include sub-second components, so round the value to an integer. For server SDKs that server core supports (Java, Python, PHP, Rust, Node), ISO timestamp support covers: - [DateTime fields in `ISO_INSTANT` format](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_INSTANT) - [DateTime fields in `RFC3339` format](https://pkg.go.dev/time#pkg-constants) ### Why is an ID always required for server SDKs? In server SDKs, `checkGate`, `getConfig`, and `getExperiment` require a StatsigUser with a `userID` (or `customID`). Pass the user ID whenever it's available: users get a stable experience, and Statsig attributes events to the correct users so you can accurately measure downstream metrics. Guidance for cases where you can't pass an ID: 1. **On/off feature gates or non-percent-based rules (such as country targeting):** Pass any non-empty identifier or a hardcoded string. If you don't have the actual user ID, use **a random ID under 100** as a placeholder. Don't use a purely random ID, because this prevents event deduplication, inflates event volume, and increases your Statsig bill. 2. **Partial rollout with regression checks before full rollout:** Pass an ID in every `checkGate`, `getConfig`, and `getExperiment` call, as well as in any `logEvent` calls. Without an ID, Statsig can't attribute logged events to the correct users or calculate metrics accurately. 3. **A/B experiment to decide whether to ship a feature:** Pass persistent user IDs, for the same reason as case 2. 4. **No logged-in user (for example, optimizing the login flow):** Set a stable identifier as a cookie or in local storage and pass it with each Statsig call. Client SDKs provide a stable ID automatically. For use cases not covered here, reach out in the [Slack community](https://statsig.com/slack). ### Pass all IDs when you have them A common mistake is accidentally exposing users without a `userID` to a user-ID-based experiment. Statsig buckets all such users into the same group (wherever the null `userID` hashes to), which skews results. If you run experiments on multiple ID types, pass every available identifier. ================================================================================ # Initializing SDKs URL: https://docs.statsig.com/client/concepts/initialize ================================================================================ # Initializing SDKs The first step in using a Statsig SDK is calling `initialize()`, which retrieves the values needed to evaluate experiments and send events. Before initialization, Statsig SDKs don't have the latest values in memory and may return stale values or none at all. Unlike Server SDK initialization, which happens at server startup, Client SDK initialization happens when a screen renders, so initialization has more impact on user experience. Statsig offers several client initialization methods to tune performance to your needs. #### Client SDKs ## General initialization flow `initialize` takes an SDK key and `StatsigUser` object. The SDK then: 1. Check local storage for cached values. The SDK caches previous evaluations locally so they're available in the next session if there is no successful network call. 2. Create a `STATSIG_STABLE_ID`: an ID that stays consistent per device, which is useful for logged-out experiments. 3. Set the SDK as initialized so checks don't throw errors. Checks return cached values or defaults. 4. Issue a network request to Statsig to get the latest values for all gates/experiments/configs/layers/autotunes for the given user. If the project definition hasn't changed from the most recent cached values, this request may succeed without returning new data. 5. Resolve the asynchronous `initialize` call. If the request to the server failed, the SDK uses cached values or returns defaults for this session. Depending on when you check a gate or experiment after initializing, fresh values may not be available yet. Awaiting initialization resolves this, with some performance tradeoffs (described in Client initialization strategies). ## Client initialization strategies Below are the various strategies summarized at a high level, ordered from most common to least common: - [**Asynchronous Initialization (Awaited)**](#1-asynchronous-initialization-awaited): Wait for the initialization network call to finish before rendering content. - [**Bootstrap Initialization**](#2-bootstrap-initialization): Generate the assignment values on your own server, and pass them down with other request, resulting in zero-latency rendering. Provides both low latency and fresh assignments, but requires additional engineering effort. - [**Asynchronous Initialization (Not Awaited)**](#3-asynchronous-initialization-not-awaited): Don't await the return of the initialization network call. This ensures immediate rendering, but in a state that reflects stale assignments or no assignments available. - [**Synchronous Initialization**](#4-synchronous-initialization): Renders immediately, but with stale or no assignments available. Statsig never assigns first-visit users to gates and experiments. | Method | Speed-to-render? | Render consistency? | Latest content? | Engineering Complexity? | | --- | --- | --- | --- | --- | | **Explanation** | When I visit the webpage, how fast does the content appear? | Does the content ever change/flicker? | Does the user ever see an out-of-date config value? | How easy is this to implement? | | Await InitializeAsync() | ❌ Slow | ✅ Good | ✅ Yes | ✅ Easy | | InitializeAsync() | ✅ Fast | ❌ Poor | ✅ Yes | ✅ Easy | | InitializeSync() | ✅ Fast | ✅ Good | ❌ No | ✅ Easy | | BootstrapInit | ✅ Fast | ✅ Good | ✅ Yes | ❌ Extra Effort | ### 1. Asynchronous initialization - awaited > Ensures latest assignments but requires a loading state When calling `StatsigClient.initializeAsync`, the client loads values from the cache and fetches the latest values from the network. This approach waits for the latest values before rendering. It isn't immediate, but ensures the values are up to date. #### React Example ```tsx const { client, isLoading } = useClientAsyncInit( YOUR_CLIENT_KEY, { userID: "u_123" } ); if (isLoading) { return <div>Loading...</div>; } // Continue with initialized client ``` #### JavaScript Example ```js const client = new StatsigClient(YOUR_CLIENT_KEY, { userID: "u_123" }); await client.initializeAsync(); // Client is now initialized with latest values ``` ### 2. Bootstrap initialization > Ensures both latest assignments with no rendering latency Bootstrapping allows you to initialize the client with a JSON string. Values are immediately available without the client making any network requests. You're responsible for keeping these values up to date. Your server serves the configuration payload to your client app on page load (for web implementations) or during app launch (for mobile implementations). #### React Bootstrap ```tsx // Server-generated initialization values const initValues = getStatsigValuesFromServer(user); const client = useClientBootstrapInit( YOUR_CLIENT_KEY, { userID: "u_123" }, initValues ); // Client renders immediately with server values — no network request ``` #### JavaScript Bootstrap ```js const bootstrapValues = getInitializationValuesFromServer(); const client = new StatsigClient(YOUR_CLIENT_KEY, { userID: "u_123" }); client.dataAdapter.setData(bootstrapValues); client.initializeSync(); ``` ### 3. Asynchronous initialization - not awaited To fetch the latest values without awaiting the asynchronous call, call `initializeAsync` and catch the promise. This approach provides immediate rendering with cached values initially, then updates to the latest values mid-session. > **Warning:** > > Be aware that the values may switch when you check them a second time after the SDK loads the latest values. ### 4. Synchronous initialization > Ensures immediate rendering but uses cached assignments (when available) When calling `StatsigClient.initializeSync`, the client uses cached values if they're available. The SDK fetches new values in the background and updates the cache. This approach provides immediate rendering, but values may be stale or absent during the first session. #### Server SDKs ## General initialization flow Server SDKs require only a secret key to initialize. Because servers handle many users, server SDKs download all rules and configurations in your project and evaluate them in real time for each user. The Server SDK initialization process: 1. Your server checks if you have locally cached values (which you can set up with a [DataAdapter](https://docs.statsig.com/server/concepts/data_store/)). 2. If your server found values on the last call, it's ready for checks with the reason "DataAdapter". Whether it found local data or not, it next goes to the network to find updated values. 3. The server retrieves updated rules from the network, and is now ready for checks even if it didn't find values in step 1. 4. Going forward, the server retrieves new values every 10 seconds from the network, updating the locally cached values each time. DataAdapters provide resilience and ensure your server is ready to serve requests as soon as it starts up, without waiting for a network round trip. This is especially useful for short-lived or serverless instances. For advanced setups, Statsig offers a [Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy/) for additional resilience. #### Node.js Initialization ```js import { Statsig, StatsigUser } from '@statsig/statsig-node-core'; const statsig = new Statsig("YOUR_SERVER_KEY"); await statsig.initialize(); // Server SDK is now ready to evaluate gates/experiments for any user const user = new StatsigUser({ userID: "123" }); const gate = statsig.checkGate(user, "my_gate"); ``` #### Python Initialization ```python from statsig_python_core import Statsig, StatsigUser statsig = Statsig("YOUR_SERVER_KEY") statsig.initialize().wait() # Server SDK is now ready user = StatsigUser("123") gate = statsig.check_gate(user, "my_gate") ``` ================================================================================ # How Evaluation Works URL: https://docs.statsig.com/sdks/how-evaluation-works ================================================================================ # How Evaluation Works ## Why evaluation matters The essential function of the Statsig SDKs is reliable, consistent, high-performance allocation of users to the correct bucket in your experiment or feature gate. Understanding how evaluation works can help you answer questions like: - Why do I have to pass every user attribute every time? - Why do I have to wait for initialization to complete? - When does Statsig decide each user's bucket? ## How evaluation works Evaluation in Statsig is deterministic. Given the same user object and the same state of the experiment or feature gate, Statsig always returns the same result, even across different platforms (client or server). The process is: 1. **Salt Creation**: Each experiment or feature gate rule generates a unique salt. 2. **Hashing**: Statsig passes the user identifier (e.g., userId, organizationId) through a SHA256 hashing function, combined with the salt, which produces a large integer. 3. **Bucket Assignment**: Statsig then applies a modulus operation with 10000 (or 1000 for layers) to the large integer, assigning the user to a bucket. 4. **Bucket Determination**: The result defines the specific bucket out of 10000 (or 1000 for layers) where Statsig places the user. This process ensures randomized but deterministic bucketing across experiments and feature gates. The unique salt per rule ensures that Statsig can assign the same user to different buckets in different experiments. If you roll out a feature gate rule to 50%, back to 0%, then back to 50%, Statsig re-exposes the same 50% of users. Re-exposure works only **as long as you reuse the same rule** and don't create a new one. Go to the [FAQ](https://docs.statsig.com/faq/#when-i-change-the-rollout-percentage-of-a-rule-on-a-feature-gate-will-users-who-passed-continue-to-pass) for details. For more details, go to the [open-source SDK evaluator](https://github.com/statsig-io/node-js-server-sdk/blob/main/src/Evaluator.ts). For advanced use cases, Statsig lets you copy and set the salts used for deterministic hashing. One example is a series of related experiments that must reuse control and test buckets. Use this ability with care. Only Project Administrators can use this option, which appears in the Overflow (...) menu in Experiments. ## Evaluation order When evaluating gates, experiments, and layers, the SDK iterates through a list of rules generated by the server. The SDK evaluates rules sequentially, and the first matching rule determines the result. Overrides always take precedence because they appear first in the rule list. > **Note:** > > Each step uses the hash-based bucketing described above. Layer allocation and group assignment use different salts, so a user's position in the layer is independent of their group assignment within the experiment. ### Experiments When you evaluate an experiment by calling `getExperiment`, the SDK follows this evaluation order: 1. **ID overrides**: Specific user/unit IDs mapped to a group 2. **Conditional overrides**: Segment or gate-based overrides, evaluated in order 3. **Layer holdouts**: If the experiment is in a layer, the SDK checks layer-level holdout gates 4. **Holdout gates**: Experiment-level holdout gates; users in a holdout receive default values 5. **Experiment exclusion**: Mutual exclusion segments that prevent users from being in multiple experiments 6. **Start status**: If the experiment isn't started, users receive default values (with optional non-production environment exceptions) 7. **Allocation**: For experiments in a layer, the user's bucket (based on the layer's universe salt) must fall within the experiment's allocated segments. For experiments not in a layer, the experiment's own Allocation % determines whether the user's bucket falls within the experiment. The SDK checks this **before** targeting. 8. **Targeting gate**: Users who fail the targeting gate receive default values. The SDK checks this **after** layer allocation. 9. **Group assignment**: The user's bucket (based on the experiment salt) determines which group they fall into. Groups are cumulative ranges across 1000 buckets. ### Layers When you evaluate a layer by calling `getLayer`, the SDK follows this evaluation order: 1. **Override rules**: ID overrides from all experiments in the layer 2. **Layer holdout gates**: Holdout gates attached to the layer 3. **Experiment allocation**: Each experiment in the layer has a `configDelegate` rule. The user's bucket determines which experiment Statsig delegates them to. 4. **Delegated experiment evaluation**: After delegation, the experiment's own evaluation runs (start status, targeting gate, group bucketing) If no experiment allocation rule matches, the user receives the layer's default values. ### Holdouts Holdout gates evaluate in this order: 1. **Experiment exclusion**: Exclusion segments (if applicable) 2. **ID overrides**: Specific user/unit IDs 3. **Population targeting gate**: If the holdout has a targeting gate, Statsig doesn't hold out users who fail it 4. **Holdout percentage**: The pass percentage on the holdout rule determines the holdout rate ### Gates When you evaluate a feature gate by calling `checkGate`, the SDK follows this evaluation order: 1. **ID overrides**: Specific user/unit IDs mapped to pass/fail 2. **Conditional overrides**: Segment or gate-based overrides 3. **Holdout rules**: If the gate has holdouts attached 4. **Rules**: The gate's targeting rules, evaluated in the order they appear in the console. Each rule has its own conditions and pass percentage. ## When evaluation happens On server SDKs, evaluation happens when you check the gate or experiment. Server SDKs hold the entire ruleset of your project in memory (a JSON representation of each gate or experiment). On client SDKs, Statsig evaluates all gates and experiments server-side when you call `initialize`. This logic applies to both SDK types. In both cases, the SDK doesn't send the user's assignment bucket to Statsig until you call `getExperiment` or `checkGate`. ## What this means - **Performant evaluation:** No evaluations require a network request. Checks take under 1 ms after initialization. - **SDKs don't remember user attributes or previous evaluations:** Pass all required user attributes consistently on every call. Statsig returns the same value for the same inputs. A common assumption is that Statsig maintains a list of all IDs and their assigned groups. Statsig's data pipelines track users exposed to each variant to compute experiment results. However, Statsig doesn't cache previous evaluations or maintain distributed evaluation state across client and server SDKs. - **Server SDKs can handle multiple users:** Because server SDKs hold the ruleset in memory, they can evaluate any user without a network request. Pass a user object into `getExperiment` on server SDKs; on client SDKs, pass the user object into `initialize`. - **Each user receives the same bucket:** ID-based hashing guarantees consistency. If you make a change in the console that could affect user bucketing on an experiment, Statsig provides a warning. ## Evaluation of null or empty unit IDs Statsig doesn't apply any filtering or business logic before assigning an individual user ID. Statsig buckets a null or empty unit ID based on the salt. ================================================================================ # SDK Debugging URL: https://docs.statsig.com/sdks/debugging ================================================================================ # SDK Debugging ## Debugging tools When a user sees an unexpected value, start with the tooling built into the Statsig console and SDKs. ### Diagnostics & log stream Every gate, config, experiment, and layer has both a **Setup** and **Diagnostics** tab. The diagnostics view highlights pass/fail rates and bucketing counts so you can spot anomalies over time. ![Diagnostics tab showing pass and fail counts](https://docs.statsig.com/images/sdks/debugging/diagnostics-overview.png) Scroll to the log stream to inspect individual evaluations. Entries arrive within seconds for both production and non-production environments. ![Log stream showing recent exposures](https://docs.statsig.com/images/sdks/debugging/log-stream.png) > **Note:** > > Enable **Show non-production logs** in the diagnostics view to surface checks coming from test keys and development builds. An exposure in Diagnostics confirms that Statsig received it. It doesn't confirm that the exposure qualifies for warehouse forwarding or has reached your warehouse. For Warehouse Native forwarding requirements, go to [Forwarded Data](https://docs.statsig.com/statsig-warehouse-native/connecting-your-warehouse/forwarded-data). ### Logging levels and expected information Statsig SDKs emit runtime logs across four verbosity levels: - `Debug`: deep tracing meant for onboarding or issue triage. - Missing gate/config warnings when a definition is unavailable. - Step-by-step messages that follow SDK initialization and evaluations. - `Info`: healthy lifecycle events for day-to-day operation. - Initialization summaries with source and SDK version details. - Notifications when the configuration store is populated. - `Warning`: recoverable issues that might affect functionality. - Non-critical errors that the SDK handles automatically. - gRPC reconnection attempts or similar transient network events. - `Error`: critical failures that block expected behavior. - Initialization timeouts or outright failures. - Fallback notices that indicate gRPC is unavailable or misconfigured. ## Evaluation details Click any exposure in the log stream to examine the precise rule, user attributes, evaluation reason, SDK metadata, and server timestamps. That detail is often enough to pinpoint why a user received a specific value. ![Evaluation details modal with rule match information](https://docs.statsig.com/images/sdks/debugging/evaluation-details.png) ### Evaluation reasons Evaluation reasons answer two questions: where the SDK sourced its definitions and why the SDK returned a particular value. Use them to distinguish between healthy results, overrides, and error states. ![Evaluation reason popover showing source and reason](https://docs.statsig.com/images/sdks/debugging/evaluation-reason.png) #### Client SDKs #### Data source | Source | Description | Type | Debugging Suggestions | | --- | --- | --- | --- | | `Network` | Values fetched during initialization from Statsig servers. | Normal | None | | `Bootstrap` | Supplied during bootstrap (often from a server SDK). | Normal | None | | `Prefetch` | Loaded through the `prefetchUsers` API (JS only). | Normal | None | | `NetworkNotModified` | Network request succeeded but cached values were already current. | Normal | None | | `Sticky` (legacy) | Persisted from a sticky evaluation. | Normal | None | | `LocalOverride` (legacy) | Set locally through override APIs. | Normal | None | | `Cache` | Served from local cache because network values were unavailable. | Warning | Ensure `initialize()` has completed before checks run. | | `InvalidBootstrap` / `BootstrapPartialUserMatch` | Bootstrap values were generated for a different user profile. | Error | Refer to [Fixing InvalidBootstrap](#invalid-bootstrap). | | `BootstrapStableIDMismatch` | StableID differed between bootstrap and runtime user. | Error | Refer to [BootstrapStableIDMismatch](#bootstrapstableidmismatch). | | `Error` | A generic evaluation failure that was logged to Statsig. | Error | Ask for help in [Slack](https://statsig.com/slack). | | `Error:NoClient` (JS) | No Statsig client was found in context. | Error | Wrap checks in `<StatsigProvider>` or equivalent. | | `Unrecognized` (legacy) | The definition was missing from the initialize payload. | Error | Confirm the config exists and you use the correct API key. | | `NoValues` | Initialization ran but failed to retrieve values. | Error | Verify client key and network connectivity. | | `Loading` | Initialization is still in progress. | Error | Await `initializeAsync()` or guard checks until ready. | | `Uninitialized` | Initialization never started. | Error | Call `initializeAsync()`/`initializeSync()` explicitly. | | `UAParserNotLoaded` | UA parsing was disabled while targeting relies on it. | Error | Remove UA-based targeting or re-enable parsing. | | `CountryLookupNotLoaded` | Country lookups were disabled while targeting relies on them. | Error | Avoid IP-based targeting or re-enable lookups. | #### Reason (new SDKs only) | Reason | Description | Type | Debugging Suggestions | | --- | --- | --- | --- | | `Recognized` | The definition was present and matched the current values. | Normal | None | | `Sticky` | Result persisted because `keepDeviceValue` was set. | Normal | None | | `LocalOverride` | Value came from a developer override. | Normal | None | | `Unrecognized` | Definition missing from the payload. | Warning | Often expected. Refer to [Why an entity is excluded from the initialize payload](#why-an-entity-is-excluded-from-the-initialize-payload). | | `Filtered` | Definition dropped from `/initialize` because the gate resolved to a `false` default. | Normal | Refer to [Why an entity is excluded from the initialize payload](#why-an-entity-is-excluded-from-the-initialize-payload). | #### Server SDKs #### Data source | Source | Description | Type | Debugging Suggestions | | --- | --- | --- | --- | | `Network` | Configurations loaded from Statsig servers at initialization. | Normal | None | | `Bootstrap` | Server SDK bootstrapped with precomputed values. | Normal | None | | `DataAdapter` | Values retrieved from a data adapter or external store. | Normal | Review your [data adapter setup](https://docs.statsig.com/server/concepts/data_store#dataadapter-or-datastore). | | `LocalOverride` (legacy) | Value supplied through server-side override APIs. | Normal | None | | `StatsigNetwork` | Proxy/streaming fell back to Statsig APIs directly. | Fallback | Revisit your [proxy configuration](https://docs.statsig.com/server/concepts/forward_proxy/). | | `Uninitialized` | SDK has not completed initialization. | Error | Ensure initialization succeeds before evaluations. | | `Unrecognized` (legacy) | Definition missing from the cached payload. | Error | Confirm configuration exists and the API key is correct. | #### Reason (new SDKs only) | Reason | Description | Type | Debugging Suggestions | | --- | --- | --- | --- | | `LocalOverride` | Result supplied by a developer override. | Normal | None | | _None_ | Successful evaluation with the expected payload. | Normal | None | | `Unrecognized` | Definition missing from the payload. | Error | Confirm configuration exists and the API key is correct. | | `Unsupported` | SDK lacks support for a condition/operator. | Error | Upgrade to the latest SDK version. | | `Error` | Generic evaluation failure captured by the SDK. | Error | Ask for help in [Slack](https://statsig.com/slack). | ### Why an entity is excluded from the initialize payload When a client SDK initializes, Statsig evaluates every gate, experiment, and dynamic config on the server and returns the results as a flat lookup map called the initialize payload. To keep that payload small and to avoid exposing configs to client code, Statsig leaves some entities out. When you check an entity that isn't in the map, the SDK returns the default value and reports the `Unrecognized` reason. This is often expected, not an error. Statsig excludes an entity from the initialize payload when any of these conditions apply: - **Segments and holdouts**: Statsig never sends these to clients. - **SDK key entity allowlist**: when the initialize options limit the payload to a specific set of gates, experiments, or configs, Statsig omits everything outside that set. - **Target app scoping**: when the SDK key belongs to a [target app](https://docs.statsig.com/sdks/target-apps), Statsig includes only the entities linked to that app. An entity with no target app doesn't reach a target-app-scoped key. - **Feature gate with a `false` default**: On the standard hosted initialize path, Statsig applies a payload-size optimization that drops a gate when it resolves to its default value, that value is `false`, and it produces no secondary exposures. An enabled gate with no rules falls through to a `false` default, so the optimization omits it. Statsig can turn this optimization on or off, and it's the most common cause of an unexpected `Unrecognized` exposure. - **Experiment allocated to a layer**: On the standard hosted initialize path, Statsig applies an optimization that serves the layer and omits the underlying experiment. - **The entity doesn't exist**: a deleted or renamed entity, or an entity in a different project, has no definition to return. `Unrecognized` and `Filtered` describe the same event from two angles: Statsig leaves an entity out of the payload, and the client then finds the definition missing when you check it. The server-side evaluation path reports only `Unrecognized`. `Filtered` is a reason that some client SDKs emit when they recognize the default-value optimization directly. Because most payloads come from the hosted path, a default-`false` gate that Statsig omits shows up as `Unrecognized` for most customers, which is expected. #### Tell an expected omission from a misconfiguration Read the reason together with the entity's setup to decide whether omission is intentional. | What you see | Likely cause | What to do | | --- | --- | --- | | `Unrecognized` on a gate with no rules | The gate defaults to `false`, so Statsig filters it from the payload. | Expected. Take no action, or add a rule so the gate returns a non-default value. | | `Unrecognized` on an entity meant for this app | The entity has no target app matching the SDK key. | Associate the entity with the target app. Refer to [Target Apps](https://docs.statsig.com/sdks/target-apps). | | `Unrecognized` on every entity | The SDK key belongs to a different project or environment. | Verify the client key. | | `Unrecognized` after an entity changes | Someone deleted or renamed the entity. | Confirm the entity exists under the name you check. | ### Evaluation times Evaluation timestamps reveal whether an SDK is serving fresh definitions. An up-to-date LCUT (Last Config Updated Time) indicates the SDK has the latest changes. If LCUT lags behind, users may be seeing stale values. LCUT can lag because a browser tab remained open or because a server integration can't sync. #### Client SDKs | Time Field | Description | SDKs | | --- | --- | --- | | `LCUT` | Time of the most recent config change reflected in the SDK. | JavaScript (incl. React & RN), iOS, Dart | | `receivedAt` | Timestamp when the client obtained the current values. | JavaScript (incl. React & RN), iOS, Dart | #### Server SDKs | Time Field | Description | SDKs | | --- | --- | --- | | `initTime` | LCUT captured when the server SDK initialized. | All server SDKs except Rust | | `configSyncTime` | Latest LCUT received from the network or data adapter. | All server SDKs except Rust | | `serverTime` | Current server clock time when the evaluation was made. | All server SDKs except Rust | ### Mocking Statsig / local mode Use the following tools to validate code paths without making network requests: - **Local mode:** Set `localMode` to `true` so the SDK skips network calls and returns default values. Local mode is useful for tests and offline environments. - **Override APIs:** Call `overrideGate` and `overrideConfig` to force specific values for an individual user or globally. Use both techniques together to exercise each branch of your application before shipping. ### Client SDK debugger Inspect the exact values a client SDK is using by opening the Client SDK Debugger. The debugger exposes the active user object and every gate/config tied to that client. - **JavaScript / React:** Use the [Chrome extension](https://github.com/statsig-io/statsig-sdk-debugger-chrome-extension). - **iOS:** Call `Statsig.openDebugView()` in [v1.26.0](https://github.com/statsig-io/statsig-kit/releases/tag/v1.26.0) or later. - **Android:** Call `Statsig.openDebugView()` in [v4.29.0](https://github.com/statsig-io/android-sdk/releases/tag/4.29.0) or later. > **Note:** > > The Chrome extension doesn't support accounts that sign in to the Statsig console through Google SSO. | Landing | Gates List | Gate Details | Experiment Details | | --- | --- | --- | --- | | ![Client debugger landing view](https://docs.statsig.com/images/sdks/debugging/client-debugger-landing.png) | ![Client debugger gates list](https://docs.statsig.com/images/sdks/debugging/client-debugger-gates.png) | ![Client debugger gate details](https://docs.statsig.com/images/sdks/debugging/client-debugger-gate-details.png) | ![Client debugger experiment details](https://docs.statsig.com/images/sdks/debugging/client-debugger-experiment.png) | ## FAQ For SDK-specific edge cases, check each SDK’s FAQ or contact the Statsig team in the [Statsig Slack community](https://statsig.com/slack). ### Invalid bootstrap `InvalidBootstrap` occurs when you bootstrap a client SDK with values generated for a different user profile. The bootstrap user must exactly match the runtime user object. ```js // Server side const userA = { userID: 'user-a' }; const bootstrapValues = Statsig.getClientInitializeResponse(userA); // Client side const bootstrapValues = await fetchStatsigValuesFromMyServers(); const userB = { userID: 'user-b' }; // <-- Different from userA await Statsig.initialize('client-key', userB, { initializeValues: bootstrapValues }); ``` Even subtle differences count as a mismatch. Adding `customIDs` or other attributes results in a distinct user object. ```js const userA = { userID: 'user-a' }; const userAExt = { userID: 'user-a', customIDs: { employeeID: 'employee-a' } }; ``` ### BootstrapStableIDMismatch `BootstrapStableIDMismatch` is similar to `InvalidBootstrap` but focuses on `stableID`. Client SDKs generate a stable ID automatically when you don't provide one, so mixing empty user objects between server and client code can cause drift. ```js // Server side const userA = {}; const bootstrapValues = Statsig.getClientInitializeResponse(userA); // Client side const bootstrapValues = await fetchStatsigValuesFromMyServers(); const userB = { stableID: '12345' }; // <-- Server user lacked a stableID await Statsig.initialize('client-key', userB, { initializeValues: bootstrapValues }); ``` Even if both sides start with `{}`, the client-generated stable ID may not match the server’s stable ID, which triggers the same mismatch warning. ```js const userC = {}; // Client SDK auto-generates a stableID await Statsig.initialize('client-key', userC, { initializeValues: bootstrapValues }); ``` ### Environments SDKs inherit their environment from initialization options. If you don't provide an environment, the SDK defaults to production. To verify which environment a user evaluated under, open the diagnostics log stream and inspect the `statsigEnvironment` property on the exposure entry. ### Maximizing event throughput > **Info:** > > Python SDK v0.45.0+ introduces tunables that help handle high event volume without drops. The SDK batches events and retries failures in the background. When throughput spikes, adjust these options to reduce dropped events: - **`eventQueueSize`**: Number of events flushed per batch. Larger batches increase throughput but use more memory. Keep the value under approximately 3000 to avoid oversized payloads. - **`retryQueueSize`**: Number of batches kept for retrying. The default is 10. Raise this value to retain more data at the cost of higher memory usage. Tune both settings to match your traffic profile. ================================================================================ # Client vs Server SDKs URL: https://docs.statsig.com/sdks/client-vs-server ================================================================================ # Client vs Server SDKs Statsig offers client and server SDKs to enable experimentation and feature management across different parts of your application. This page outlines when to choose each. ## Overview **Client SDKs** run in code that executes on end-user devices, such as a website, mobile app, video game, or smart TV app. **Server SDKs** run on your servers (typically in the cloud), such as a web server or API server. Many customers deploy both Server and Client SDKs, which lets them gate features on both the client and server side. While this is common, you can get value from Statsig by starting with one SDK type. ## Usage Client and Server SDKs follow a similar setup pattern: 1. **Initialize:** Set up the SDK and download the latest values. 2. **Check an experiment/gate:** Reference those values to assign an experiment or flag a feature. 3. **Log custom events:** Log important app metrics to power your analyses. > **Note:** > > After initialization, both Client and Server SDKs evaluate experiments/gates _without a network request_, and typically in less than 1ms. Statsig designs the checks in its SDKs to be very efficient. ## Conceptual differences - Data Privacy: The Server SDK runs in a secure, multi-user environment, so Server SDKs have access to the full ruleset describing each experiment and gate. Client SDKs fetch only the value for a single user, avoiding exposure of your configuration definitions. | | Server | Client | | --- | --- | --- | | Privacy | Your servers operate in a secure, multi-user environment, so Server SDKs have access to the definition of all configurations in your project | Statsig precomputes all evaluations on its servers and sends results to your client applications. Statsig obfuscates names, but a savvy user might glean information from the raw response | | Evaluation Performance | The SDK evaluates in real time, without a network request. Very complex configurations can take longer to compute, but in practice, this is rarely an issue. | As Statsig precomputes all evaluation, gate and experiment checks are effectively a dictionary lookup with some computation used for creating and flushing exposure events | | Initialization Performance | The SDK makes an upfront request for configuration files, then continually polls for any changes to your configurations, updating its internal state when it detects a change | Client SDKs download configurations when you initialize, before which, the SDK may not have usable values. Values don't update mid-session unless you explicitly call updateUser. Statsig provides additional options for performant initialization; refer to [Initializing](https://docs.statsig.com/client/concepts/initialize) | | Users | Server SDKs are designed to run against multiple users, and all SDK methods require a user object for evaluation/logging | Client SDKs are designed to run with one user at a time. The SDK loads all evaluations once during initialization, and every event logged uses that user object | | Infrastructure | Server SDKs require you to host your own backend services | Client SDKs run entirely on the client and use Statsig's servers | ## Usage differences | | Server | Client | | --- | --- | --- | | Initializing | Requires only a secret key, downloads the entire ruleset and syncs it in the background | Requires a client key and a user object. Before/during initialization, the SDK attempts to fall back to cached values. | | Checking an Experiment | Requires a user object, which the SDK evaluates locally (without a network request) against a ruleset in memory | Doesn't require a user object, uses a dictionary lookup for values fetched during initialize() | | User Identifiers | Pass any and all useful user identifiers | Pass any useful identifiers, the SDK also generates a "StableID", Statsig's anonymous ID you can use to experiment on a user per-device | | Logging Events | Requires a user object | Doesn't require a user object. There is some risk of adblocking log events on client SDKs, which you can minimize by setting up a [Custom Proxy](https://docs.statsig.com/infrastructure/api_proxy/custom_proxy) | | Flushing Events | The SDK batches and flushes events every 60 seconds | The SDK batches and flushes events every 10 seconds | | Updating Configurations | Poll Statsig servers for updates every 10 seconds by default (configurable), Streaming possible with some Server SDKs and the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy) | Configuration persists until next `initialize` or `updateUser` call; call `initialize` at the start of each user session | ## Initialize and update logic **Client SDKs:** - Configuration persists until next `initialize` or `updateUser` call - Call `initialize` at the start of each user session ![Client SDKs](https://docs.statsig.com/images/client/introduction/169555378-a1ba4c22-1d13-46c5-956e-ba87abe9b549.png) **Server SDKs:** - Poll Statsig servers for updates every 10 seconds by default (configurable) - Some SDKs support grpc streaming updates by connecting to the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy) ![Server SDKs](https://docs.statsig.com/images/server/introduction/169563936-121cb75e-37e5-491f-8bb1-2d853c2e04b8.png) ## Available SDKs ### Client SDKs - [Javascript](https://docs.statsig.com/client/javascript-sdk) - [React](https://docs.statsig.com/client/React) - [React Native](https://docs.statsig.com/client/ReactNative) - [Expo](https://docs.statsig.com/client/Expo) - [iOS](https://docs.statsig.com/client/iosClientSDK) - [Android](https://docs.statsig.com/client/Android) - [.Net](https://docs.statsig.com/client/DotNet) - [Unity](https://docs.statsig.com/client/Unity) - [Roku](https://docs.statsig.com/client/Roku) - [C++](https://docs.statsig.com/client/CPP) - [Dart/flutter](https://docs.statsig.com/client/Dart) ### Server SDKs - [Node.js](https://docs.statsig.com/server/nodejsServerSDK) - [Java](https://docs.statsig.com/server/java) - [Python](https://docs.statsig.com/server/pythonSDK) - [Go](https://docs.statsig.com/server/go) - [Ruby](https://docs.statsig.com/server/ruby) - [.NET Core](https://docs.statsig.com/server-core/dotnet-core) - [C++](https://docs.statsig.com/server-core/cpp-core) - [PHP](https://docs.statsig.com/server/php) - [Rust](https://docs.statsig.com/server/rust) For more information on each SDK, refer to their respective documentation pages. Got questions? Join the Statsig engineering and product team on the [Statsig Slack channel](https://statsig.com/slack). ================================================================================ # Data Privacy for Mobile URL: https://docs.statsig.com/compliance/data_privacy_for_mobile Updated: 2025-05-21 ================================================================================ # Data Privacy for Mobile ## General ### What data does Statsig collect from users of my app Statsig collects only the data that you configure to send to Statsig. This data typically includes the occurrence of feature flag evaluations (Feature Gates), experiment exposures, and custom events you log with the SDK. ### Does that data include any personally identifiable information (PII) By default, Statsig uses randomly generated IDs as described in this article. You can also augment data sent to Statsig with additional context and metadata, including user names, email addresses, or custom attributes. This data, alone or in combination with other data, may constitute PII if it identifies an individual directly or indirectly. ### Does Statsig use the device ID to identify a user No. Statsig on Mobile doesn't use device IDs such as `Secure.ANDROID_ID` or `advertisingIdentifier` on iOS. Instead, Statsig uses a StableID, which it randomly generates per device, per app, and per installation, and which can't identify a single device across installations. Statsig generates a new StableID when you reinstall an application. These IDs provide approximate statistical information as part of the application monitoring service, for example, for Crash Free Session and User Rates. The IDs also indicate the impact of issues based on number of events versus affected users. ### What does Statsig do with the data it collects Statsig processes the data you send to it to provide feature flag management, experimentation, and analytics services. ## Apple App Store ### Do I need to disclose the use of Statsig in App Store Connect on the Apple App Store Yes, Statsig is a third-party partner whose code (SDKs) you integrate in your app that collects data from users of your app. ### What do I need to disclose to Apple Disclose all types of data you're collecting through your app, including data you're sending to Statsig. This may include "Contact Info" or "Identifiers" if you provide those in the `StatsigUser` object. Include any other categories of data you have configured the SDKs to send to Statsig. ### How does Statsig use my data The standard data use cases for Statsig are "Analytics" and "App Functionality". Disclose to Apple any other ways in which you or your app use the data you collect. ### Does Statsig use my data to track users Statsig doesn't use your data to track users. However, if you or your other third-party partners are tracking users, you still need to disclose this to Apple. ### Does Statsig use the Advertising Identifier (IDFA) No. Statsig doesn't require IDFA. ## Google Play ### Does Statsig collect any PII from children If your app targets children and you configure Statsig to collect PII, Statsig collects the elements you have designated. You remain responsible for obtaining appropriate parental consents for the PII you collect from users and send to Statsig. You also remain responsible for declaring your app's target age group to Google Play. ### Do Statsig SDKs cause my app to contain ads No. Statsig doesn't cause your app to contain any ads. ### What do I need to disclose to Google Play Disclose in your app privacy policy all types of data you're collecting through your app, including data you're sending to Statsig. ## Privacy controls ### What device and user metadata does Statsig automatically collect The Statsig SDKs automatically collect the following metadata for targeting and analytics purposes: **iOS SDK collects:** - appIdentifier: Your app's bundle identifier - appVersion: Your app's version - deviceModel: The device model (e.g., iPhone14,3) - deviceOS: The operating system (iOS) - language: The user's preferred language - locale: The user's locale identifier - sdkType: The type of SDK (ios-client) - sdkVersion: The version of the Statsig SDK - sessionID: A randomly generated UUID for the current session - stableID: A persistent device identifier (see below) - systemVersion: The iOS version - systemName: The system name (iOS) **Android SDK collects:** - appIdentifier: Your app's package name - appVersion: Your app's version name - deviceModel: The device model (e.g., Pixel 7) - deviceOS: The operating system (Android) - locale: The user's locale - language: The user's language - sdkType: The type of SDK (android-client) - sdkVersion: The version of the Statsig SDK - sessionID: A randomly generated UUID for the current session - stableID: A persistent device identifier (see below) - systemVersion: The Android API level - systemName: The system name (Android) ### How can I limit the metadata collected by Statsig Both iOS and Android SDKs provide the `optOutNonSdkMetadata` option to limit the collection of device-specific information: **iOS SDK:** ```swift let options = StatsigOptions() options.optOutNonSdkMetadata = true Statsig.start(sdkKey: "client-sdk-key", options: options) ``` **Android SDK:** ```kotlin val options = StatsigOptions(optOutNonSdkMetadata = true) ``` When you enable `optOutNonSdkMetadata`, the SDK includes only the following core SDK metadata: - sdkType: The type of SDK - sdkVersion: The version of the Statsig SDK - sessionID: A randomly generated UUID for the current session - stableID: A persistent device identifier The SDK excludes all device-specific information (appIdentifier, appVersion, deviceModel, deviceOS, locale, language, systemVersion, systemName) from logs and targeting. ### How does StableID work The StableID is a persistent identifier that Statsig uses to provide consistent user experiences and analytics: **iOS Implementation:** - Statsig stores the StableID in UserDefaults under the key "com.Statsig.InternalStore.stableIDKey". - On first generation, Statsig creates the StableID as a random UUID. - The StableID persists across app launches, but Statsig regenerates it when you reinstall the app. - You can override the StableID through the `StatsigOptions.overrideStableID` parameter. **Android Implementation:** - Statsig stores the StableID in SharedPreferences. - On first generation, Statsig creates the StableID as a random UUID. - The StableID persists across app launches, but Statsig regenerates it when you reinstall the app. - You can override the StableID through the `StatsigOptions.overrideStableID` parameter. Statsig doesn't share the StableID across different apps or websites, and it can't track users across different applications or platforms. ### How can I prevent sending sensitive user data to Statsig Use the `privateAttributes` field for sensitive data you want to use for targeting but not log: **iOS SDK:** ```swift let user = StatsigUser( userID: "user-123", email: nil, // Not included at top level to keep private privateAttributes: ["email": "user@example.com"] // Used for evaluation but not logged ) ``` **Android SDK:** ```kotlin val user = StatsigUser("user-123") user.privateAttributes = mapOf("email" to "user@example.com") ``` The SDK sends these attributes to Statsig servers during initialization for feature flag and experiment evaluation, but Statsig removes them before sending any event logs to Statsig servers. Use the attributes for targeting users with specific features or experiments, but they don't appear in your analytics data. For more comprehensive privacy controls, use [Client Bootstrapping](https://docs.statsig.com/client/concepts/initialize#bootstrapping-overview) to generate all assignments locally on your server. This approach eliminates the need to send any user attributes from the client device to Statsig. ================================================================================ # JavaScript Client SDK (Web) URL: https://docs.statsig.com/client/javascript-sdk ================================================================================ # JavaScript Client SDK (Web) - **Package:** `@statsig/js-client` ([npm](https://www.npmjs.com/package/@statsig/js-client)) - **Latest version:** 3.33.7 - **Package size:** 23.1 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK 1. **Install the SDK** To install the Statsig Web SDK, add the package using your preferred package manager. Include optional packages if you plan to enable Session Replay or Auto Capture. #### npm ```bash npm install @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` #### yarn ```bash yarn add @statsig/js-client @statsig/session-replay @statsig/web-analytics ``` > **Info:** > > If you don't need Session Replay or Auto Capture, omit the `@statsig/session-replay` and `@statsig/web-analytics` packages. After installation, configure the SDK in your app entry point before rendering your UI. 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. ```tsx import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient( 'client-xyz', { userID: 'a-user' }, { environment: { tier: 'development' }, }, ); await client.initializeAsync(); ``` Use `initializeAsync` when you need to await the latest values. For a non-blocking approach, you can call `initializeAsync()` without awaiting and rely on cached values until the promise resolves. ## Use the SDK ### Checking a feature flag/gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. ```tsx if (client.checkGate('new_homepage_design')) { // Gate is on, show new experience } else { // Gate is off, render the default experience } ``` ### Reading a dynamic config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send different values (strings, numbers, and similar types) to your clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates but returns a full JSON object you can configure on the server and fetch typed parameters from. For example: ```tsx const config = client.getDynamicConfig('awesome_product_details'); const itemName = config.get('product_name', 'Some Fallback'); const price = config.value.price ?? 10.0; if (config.value.is_discount_enabled === true) { // apply discount logic } ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```tsx // Reading values via getLayer const layer = client.getLayer('user_promo_experiments'); const promoTitle = layer.get('title', 'Welcome to Statsig!'); const discount = layer.get('discount', 0.1); ``` ```tsx // Reading values via getExperiment const titleExperiment = client.getExperiment('new_user_promo_title'); const priceExperiment = client.getExperiment('new_user_promo_price'); const experimentTitle = titleExperiment.value.title ?? 'Welcome to Statsig!'; const experimentDiscount = priceExperiment.value.discount ?? 0.1; ``` ### Logging an event After you set up a Feature Gate or an Experiment, you can track custom events to measure how your new features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and/or a metadata object to log together with the event: ```tsx client.logEvent('my_simple_event'); client.logEvent({ eventName: 'add_to_cart', value: 'SKU_12345', metadata: { price: '9.99', item_name: 'diet_coke_48_pack', }, }); ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```tsx await client.flush(); ``` ### Typed getters `Layer`, `Experiment`, and `DynamicConfig` objects support a typed `get` method. Using a fallback that matches the expected type helps avoid returning unintended values. ```tsx // config value: { "my_value": 1 } const dynamicConfig = client.getDynamicConfig('a_config'); const fallbackString = dynamicConfig.get('my_value', 'fallback'); // returns 'fallback' const fallbackNumber = dynamicConfig.get('my_value', 0); // returns 1 const rawValue = dynamicConfig.get('my_value'); // returns 1 ``` Passing a fallback of the wrong type returns that fallback. When you don't need type safety, omit the fallback to receive the raw value. ### Evaluation details Each gate, config, experiment, and layer exposes `details` describing how Statsig resolved the value. - `reason` explains the source (e.g., `Network:Recognized`, `Cache:Unrecognized`). - `lcut` is the last time any configuration changed in your project. - `receivedAt` marks when the SDK received this response, useful for judging cache staleness. ```tsx const gate = client.getFeatureGate('a_gate'); console.log(gate.details); // { reason: 'Cache:Recognized', lcut: 1713837126636, receivedAt: 1713838137598 } const config = client.getDynamicConfig('a_config'); console.log(config.details); // { reason: 'Cache:Unrecognized', lcut: 1713837126636, receivedAt: 1713838137598 } ``` Go to [`/sdk/debugging`](https://docs.statsig.com/sdks/debugging) for the full list of `reason` values. ### Sample projects Explore end-to-end examples in the [`js-client-monorepo` samples folder](https://github.com/statsig-io/js-client-monorepo/tree/main/samples) for React, Next.js, precomputed clients, and more. ## Parameter Stores Parameter Stores hold a set of parameters for your mobile app. You can remap these parameters dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Go to [Parameter Stores](https://docs.statsig.com/client/concepts/parameter-stores) to learn more. ```tsx const homepageStore = client.getParameterStore('homepage'); const title = homepageStore.get('title', 'Welcome'); const showUpsell = homepageStore.get('upsell_upgrade_now', false); ``` ## Statsig user Provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. You usually need the `userID` field to provide a consistent experience for a given user. (Refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users.) Besides `userID`, StatsigUser also has the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and/or any other updated user attributes. ### Updating users Call `updateUserAsync` when the signed-in user changes to fetch fresh values for that identity. ```tsx const user = { userID: 'a-user' }; await client.updateUserAsync(user); ``` For advanced flows such as bootstrapping or prefetching users, go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter). ### Prefetching users Use `prefetchData` to prepare values for another user so you can switch synchronously later. ```tsx const nextUser = { userID: 'my-other-user' }; await client.dataAdapter.prefetchData(nextUser); // Optionally handle failures without blocking the UI client.dataAdapter.prefetchData(nextUser).catch((err) => { console.warn('Failed to prefetch', err); }); client.updateUserSync(nextUser); const gate = client.getFeatureGate('a_gate'); console.log(gate.value, gate.details.reason); // true, 'Prefetch:Recognized' ``` ## Statsig options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingEnabled | LoggingEnabledOption | No | — | Controls logging behavior.- `browser-only` (default): log events from browser environments. - `disabled`: never send events. - `always`: log in every environment, including non-browser contexts. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableLogging | boolean | No | — | Use `loggingEnabled: 'disabled'` instead. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStableID | boolean | No | — | Skip generating a device-level Stable ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableEvaluationMemoization | boolean | No | — | Recompute every evaluation instead of using the memoized result. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initialSessionID | string | No | — | Override the generated session ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableCookies | boolean | No | — | Persist Stable ID in cookies for cross-domain tracking. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStorage | boolean | No | — | Prevent any local storage writes (disables caching). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkConfig | NetworkConfig | No | — | Override network endpoints per request type. | #### Network Config Options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | Base URL for all requests. The SDK appends endpoint paths like `/initialize` and `/rgstr`; append `/v1` when your proxy expects it. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeUrl | string | No | — | Endpoint for initialization requests only. Takes precedence over `api` for `/initialize`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeFallbackUrls | string[] | No | — | Fallback endpoints for initialization requests only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | Endpoint for event uploads. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventFallbackUrls | string[] | No | — | Fallback endpoints for event uploads only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkTimeoutMs | number | No | — | Request timeout in milliseconds. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | preventAllNetworkTraffic | boolean | No | — | Disable all outbound requests; combine with `loggingEnabled: 'disabled'` to silence log warnings. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkOverrideFunc | function | No | — | Provide custom transport (e.g., Axios). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | Set environment-wide defaults (for example `{ tier: 'staging' }`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logLevel | LogLevel | No | — | Console verbosity. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingBufferMaxSize | number | No | — | Max events per log batch. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | — | Interval between automatic flushes. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideAdapter | OverrideAdapter | No | — | Modify evaluations before returning them. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeCurrentPageUrlWithEvents | boolean | No | — | Attach the current page URL to logged events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStatsigEncoding | boolean | No | — | Send requests without Statsig-specific encoding. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventCompressionMode | LogEventCompressionMode | No | — | Control compression for batched events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableCompression | boolean | No | — | Use `logEventCompressionMode` instead. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | EvaluationsDataAdapter | No | — | Provide a custom data adapter to control caching/fetching. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | customUserCacheKeyFunc | CustomCacheKeyGenerator | No | — | Override cache key generation for stored evaluations. | ## Manual exposures > **Warning:** > > Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results. You can query your gates/experiments without triggering an exposure, and manually log the exposures later: #### Feature Gates ```tsx const result = client.checkGate('a_gate_name', { disableExposureLog: true }); // ... client.checkGate('a_gate_name'); // later, when ready to log the exposure ``` #### Dynamic Configs ```tsx const config = client.getConfig('a_dynamic_config_name', { disableExposureLog: true }); client.getConfig('a_dynamic_config_name'); ``` #### Experiments ```tsx const experiment = client.getExperiment('an_experiment_name', { disableExposureLog: true }); client.getExperiment('an_experiment_name'); ``` #### Layers ```tsx const layer = client.getLayer('a_layer_name', { disableExposureLog: true }); const value = layer.get('param_name', 'fallback'); // When ready to log const exposure = client.getLayer('a_layer_name'); exposure.get('param_name', 'fallback'); ``` ## Session Replay Install `@statsig/session-replay` and register the plugin to record user sessions. ```tsx import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; <StatsigProvider sdkKey="client-xyz" user={{ userID: 'a-user' }} loadingComponent={<div style={{ height: 100, width: 300, padding: 16 }}>Loading...</div>} options={{ plugins: [new StatsigSessionReplayPlugin()] }} > <App /> </StatsigProvider>; ``` ## Web Analytics / Auto Capture By including the [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) package in your project, you can automatically capture common web events like clicks and page views. For more information on filtering events, enabling console log capture, and other configuration options available in web analytics, refer to the [Web Analytics Configuration](https://docs.statsig.com/webanalytics/overview#event-filtering-and-console-configuration) documentation. ```tsx import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; <StatsigProvider sdkKey="client-xyz" user={{ userID: 'a-user' }} loadingComponent={<div style={{ height: 100, width: 300, padding: 16 }}>Loading...</div>} options={{ plugins: [new StatsigAutoCapturePlugin()] }} > <App /> </StatsigProvider>; ``` ## Content Security Policy Add Statsig endpoints to your CSP `connect-src` directive when running the web SDK. ```js const cspConfig = { directives: { 'connect-src': [ 'api.statsig.com', 'featuregates.org', 'statsigapi.net', 'events.statsigapi.net', 'api.statsigcdn.com', 'featureassets.org', 'assetsconfigcdn.org', 'prodregistryv2.org', 'cloudflare-dns.com', 'beyondwickedmapping.org', ], }, }; ``` > **Info:** > > Statsig occasionally updates its network domains. Verify the latest list in [Statsig Domains](https://docs.statsig.com/infrastructure/statsig_domains). ## Lifecycle and advanced usage ## Shutting Statsig down To save users' data and battery usage and prevent dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, Statsig may not have sent some events when your app shuts down. To ensure Statsig flushes or saves all logged events locally, call shutdown when your app is closing. ```tsx await client.shutdown(); ``` ## Stable ID Stable ID provides a consistent device identifier. It lets you run [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) and target gates at the device level. ### How Stable ID works - On first initialization the SDK generates a Stable ID and stores it in `localStorage` under `statsig.stable_id.<SDK_KEY_HASH>`. - Subsequent sessions reuse the stored value. Each client SDK key has its own Stable ID entry. - Local storage is scoped per domain, so cross-domain usage requires sharing the value manually (see below). ### Reading the Stable ID #### JavaScript ```tsx const context = client.getContext(); console.log('Statsig StableID:', context.stableID); ``` #### React ```tsx import { useStatsigClient } from '@statsig/react-bindings'; function MyComponent() { const { client } = useStatsigClient(); const context = client.getContext(); return <div>{context.stableID}</div>; } ``` ### Overriding the Stable ID Provide a custom Stable ID through `StatsigUser.customIDs.stableID` if you already manage a durable device identifier. #### JavaScript ```tsx import { StatsigClient, StatsigUser } from '@statsig/js-client'; const userWithStableID: StatsigUser = { customIDs: { stableID: 'my-custom-stable-id', }, }; const client = new StatsigClient('client-xyz', userWithStableID); await client.updateUserAsync(userWithStableID); ``` #### React ```tsx import { StatsigProvider, useStatsigClient } from '@statsig/react-bindings'; function App() { return ( <StatsigProvider sdkKey="client-xyz" user={{ customIDs: { stableID: 'my-custom-stable-id' }, }} > <div>Your App</div> </StatsigProvider> ); } function MyComponent() { const { client } = useStatsigClient(); useEffect(() => { client.updateUserAsync({ customIDs: { stableID: 'my-custom-stable-id' }, }); }, [client]); } ``` > **Note:** > > When you override the Stable ID, Statsig persists it to local storage, so subsequent sessions reuse your custom value. ### Sharing Stable ID across subdomains Add this helper script before initializing the SDK and then copy the stored value onto your user object. ```html <!-- cross domain id script --> <script>!function(){let t="STATSIG_LOCAL_STORAGE_STABLE_ID";function e(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();let t=()=>Math.floor(65536*Math.random()).toString(16).padStart(4,"0");return`$\{t()\}${t()}-$\{t()\}-4${t().substring(1)}-$\{t()\}-${t()}$\{t()\}${t()}`}let i=null,n=localStorage.getItem(t)||null;if(document.cookie.match(/statsiguuid=([\w-]+);?/)&&([,i]=document.cookie.match(/statsiguuid=([\w-]+);?/)),i&&n&&i===n);else if(i&&n&&i!==n)localStorage.setItem(t,i);else if(i&&!n)localStorage.setItem(t,i);else{let o=e();localStorage.setItem(t,o),function t(i){let n=new Date;n.setMonth(n.getMonth()+12);let o=window.location.host.split(".");o.length>2&&o.shift();let s=`.$\{o.join(".")\}`;document.cookie=`statsiguuid=${i||e()};Expires=$\{n\};Domain=${s};Path=/`}(o)}}();</script> <!-- Manually attach stableID to user object --> <script> const userObj = {}; if (localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')) { userObj.customIDs = { stableID: localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID'), }; } const client = new Statsig.StatsigClient('<client-sdk-key>', userObj); </script> ``` _Use this script at your discretion and test thoroughly._ ### Aligning Stable ID between client and server To share Stable ID with a backend Statsig SDK, send the value with requests and persist it server-side when missing. The server can bootstrap the client with the same Stable ID. ```tsx // Server: ensure Stable ID exists, then return initialize response for the client const values = Statsig.getClientInitializeResponse(user, YOUR_CLIENT_KEY, { hash: 'djb2', }); // Client: apply the server-provided values and initialize synchronously const { values, user: verifiedUser } = await fetch('/init-statsig-client', { method: 'POST', body: loadUserData(), }).then((res) => res.json()); const myClient = new StatsigClient(YOUR_CLIENT_KEY, verifiedUser); myClient.dataAdapter.setData(values); myClient.initializeSync(); ``` ## Using multiple instances of the SDK The examples above use the SDK's singleton. Statsig also supports creating multiple instances of the SDK. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly. > **Note:** > > Use a different SDK key for each SDK instance. The Statsig client keys various functionality on the SDK key you use. Using the same key causes collisions. All top-level static methods from the singleton carry over as instance methods. To create an instance of the Statsig SDK: ```tsx import { StatsigClient } from '@statsig/js-client'; const mainClient = new StatsigClient('client-xyz', { userID: 'a-user' }); const secondaryClient = new StatsigClient('client-abc', { userID: 'another-user' }); await Promise.all([ mainClient.initializeAsync(), secondaryClient.initializeAsync(), ]); if (mainClient.checkGate('a_gate')) { // ... } if (secondaryClient.checkGate('some_other_gate')) { // ... } ``` ## Override adapter Use the `LocalOverrideAdapter` to define local overrides for gates, configs, experiments, or layers. ```tsx import { LocalOverrideAdapter } from '@statsig/js-local-overrides'; import { StatsigClient, LogLevel } from '@statsig/js-client'; const overrideAdapter = new LocalOverrideAdapter(); overrideAdapter.overrideGate('gate_a', false); overrideAdapter.overrideGate('gate_b', true); const client = new StatsigClient('client-xyz', { userID: 'a-user' }, { logLevel: LogLevel.Debug, overrideAdapter, }); ``` ### Persisting overrides Pass your client SDK key to the adapter to persist overrides between sessions when using multi-instance setups. ```tsx const overrideAdapter = new LocalOverrideAdapter('client-xyz'); ``` ## Using persistent evaluations Persist experiment assignments so users keep the same variant even if targeting rules change. ```tsx import { StatsigClient } from '@statsig/js-client'; import { UserPersistentOverrideAdapter } from '@statsig/js-user-persisted-storage'; class LocalStorageUserPersistedStorage { load(key: string) { return JSON.parse(localStorage.getItem(key) ?? '{}'); } save(key: string, experiment: string, data: string) { const values = JSON.parse(localStorage.getItem(key) ?? '{}'); values[experiment] = JSON.parse(data); localStorage.setItem(key, JSON.stringify(values)); } delete(key: string, experiment: string) { const data = JSON.parse(localStorage.getItem(key) ?? '{}'); delete data[experiment]; localStorage.setItem(key, JSON.stringify(data)); } } const storage = new LocalStorageUserPersistedStorage(); const adapter = new UserPersistentOverrideAdapter(storage); const client = new StatsigClient('client-xyz', { overrideAdapter: adapter }); await client.initializeAsync({ userID: '123' }); const userPersistedValues = adapter.loadUserPersistedValues({ userID: '123' }, 'userID'); const experiment = client.getExperiment('active_experiment', { userPersistedValues }); ``` Refer to [Client Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment) for additional patterns and storage options. ## Common targeting use cases Capture cookies or URL parameters and pass them through `StatsigUser.custom` for targeting rules. ```tsx const user = { custom: { isLoggedIn: cookieLib.get('isLoggedIn'), utm: new URL(window.location.href).searchParams.get('utm'), }, }; const client = new StatsigClient('client-xyz', user, options); ``` ![Targeting in Console](https://docs.statsig.com/images/client/js-common-targeting.png) ## Async timeouts Limit how long `initializeAsync` and `updateUserAsync` wait for network responses before falling back to cached values. ```tsx await client.initializeAsync({ timeoutMs: 1000 }); await client.updateUserAsync( { userID: 'a-user' }, { timeoutMs: 1000 }, ); ``` ### Data adapter `StatsigClient` uses an `EvaluationsDataAdapter` to manage caching and network fetches. The default implementation (`StatsigEvaluationsDataAdapter`) reads from local storage synchronously and refreshes values from Statsig asynchronously. Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) for full examples, including bootstrapping, prefetching, and custom adapters. ### Partial user matching Use `customUserCacheKeyFunc` with `updateUserSync` when you need to enrich a user locally without triggering a full network refresh. ```tsx const originalUser = { customIDs: { analyticsID: 'analytics-123', }, }; const customKey = (sdkKey: string, user: StatsigUser) => { const analyticsID = user.customIDs?.analyticsID ?? 'anonymous'; return `sdkKey:$\{sdkKey\}:analyticsID:${analyticsID}`; }; const client = new StatsigClient('client-xyz', originalUser, { customUserCacheKeyFunc: customKey, }); await client.initializeAsync(); someAsyncFunction().then((newData) => { const enrichedUser = { ...originalUser, userID: newData.userID, email: newData.email, }; client.updateUserSync(enrichedUser); }); ``` > **Warning:** > > Custom cache keys can produce stale or incorrect evaluations if multiple users map to the same key. Await `updateUserAsync` when you need guaranteed fresh values per user. ### Client event emitter Subscribe to Statsig client lifecycle events to respond to initialization, logging, or evaluation changes. ```tsx import type { AnyStatsigClientEvent, StatsigClientEvent, } from '@statsig/client-core'; const onAnyEvent = (event: AnyStatsigClientEvent) => { console.log('Statsig event', event); }; const onLogsFlushed = (event: StatsigClientEvent<'logs_flushed'>) => { console.log('Logs', event.events); }; client.on('logs_flushed', onLogsFlushed); client.on('*', onAnyEvent); client.off('logs_flushed', onLogsFlushed); client.off('*', onAnyEvent); ``` | Event | Payload | Description | | --- | --- | --- | | `values_updated` | `{ status, values }` | Fired when initialize/update refreshes cached values. | | `session_expired` | `{}` | Fired when the current session expires. | | `error` | `{ error, tag }` | Unexpected client errors. | | `pre_logs_flushed` | `{ events }` | Before Statsig sends a batch of events. | | `logs_flushed` | `{ events }` | After Statsig sends events. | | `pre_shutdown` | `{}` | Before the SDK shuts down. | | `initialization_failure` | `{}` | Initialization failed. | | `gate_evaluation` | `{ gate }` | When Statsig evaluates a gate. | | `dynamic_config_evaluation` | `{ dynamicConfig }` | When Statsig evaluates a config. | | `experiment_evaluation` | `{ experiment }` | When Statsig evaluates an experiment. | | `layer_evaluation` | `{ layer }` | When Statsig evaluates a layer. | | `log_event_called` | `{ event }` | When you call `logEvent`. | ## Quality and troubleshooting ## Testing Mock Statsig APIs in Jest to isolate business logic. ```tsx import { StatsigClient } from '@statsig/js-client'; export async function transform(input: string): Promise<string> { const client = new StatsigClient('client-xyz', { userID: 'a-user' }, { networkConfig: { preventAllNetworkTraffic: typeof process !== 'undefined' && process.env['NODE_ENV'] === 'test', }, }); await client.initializeAsync(); if (client.checkGate('a_gate')) { input = 'transformed'; } const experiment = client.getExperiment('an_experiment'); input += '-' + experiment.get('my_param', 'fallback'); await client.shutdown(); return input; } ``` ```tsx import { StatsigClient } from '@statsig/js-client'; jest.mock('@statsig/js-client'); test('string transformations', async () => { jest .spyOn(StatsigClient.prototype, 'checkGate') .mockImplementation(() => true); jest .spyOn(StatsigClient.prototype, 'getExperiment') .mockImplementation(() => ({ get: () => 'my-value' } as any)); const result = await transform('original'); expect(result).toBe('transformed-my-value'); }); ``` ## Debugging When results look unexpected, use these tools to inspect what the SDK is doing. ### Enable verbose logging ```ts import { LogLevel, StatsigClient } from '@statsig/js-client'; const client = new StatsigClient('client-xyz', { userID: 'a-user' }, { logLevel: LogLevel.Debug, }); ``` ### Inspect the `__STATSIG__` global Open your browser console and run `__STATSIG__` to inspect the current client instance. Useful properties include `_logger._queue` for pending events. ![Statsig Global](https://docs.statsig.com/images/client/statsig-global.png) ### Review network traffic Filter network requests by `client-` to see initialization and logging calls. ![Network Logs](https://docs.statsig.com/images/client/network-logs.png) ### Check evaluation reasons ```ts const gate = client.getFeatureGate('a_gate'); console.log(gate.details.reason); ``` Common reasons: - `Network` | `NetworkNotModified`: latest values from the API. - `Cache`: loaded from local storage. - `NoValues`: no cached values and network failed. - `Bootstrap`: values provided through `dataAdapter.setData`. - `Prefetch`: values from `dataAdapter.prefetchData`. Go to [`/sdk/debugging`](https://docs.statsig.com/sdks/debugging#reasons) for full details. ## FAQs #### Does the SDK use local storage or cookies Statsig's web SDK doesn't set cookies. It stores gate/config values and unsent events in `localStorage` so features keep working when offline. #### Can I access the SDK instance globally ```tsx window.Statsig.instance().logEvent('test_event'); ``` ```ts import { StatsigClient } from '@statsig/js-client'; StatsigClient.instance().logEvent('test_event'); ``` > **Info:** > > With multiple instances, pass the SDK key: `Statsig.instance('client-YOUR_KEY')`. #### How do I handle consent or GDPR flows Start with logging disabled and storage blocked, then enable them after consent. ```tsx const client = new StatsigClient('client-xyz', {}, { loggingEnabled: 'disabled', disableStorage: true, }); await client.initializeAsync(); client.updateRuntimeOptions({ loggingEnabled: 'browser-only', disableStorage: false, }); ``` The SDK buffers up to 500 events in memory and flushes them after logging is re-enabled. ## Additional resources - [Client Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment) - [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) - [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging) ================================================================================ # HTML Snippet URL: https://docs.statsig.com/client/html-snippet ================================================================================ # HTML Snippet - **Repository:** [js-client-sdk](https://github.com/statsig-io/js-client-sdk) ## Set up the SDK 1. **Install the SDK** Install the Statsig SDK by adding a script tag to the head of your HTML file: ```js <script src="https://cdn.jsdelivr.net/npm/@statsig/js-client@3/build/statsig-js-client+session-replay+web-analytics.min.js?apikey=YOUR_CLIENT_API_KEY" crossorigin="anonymous" > </script> ``` Replace `YOUR_CLIENT_API_KEY` with your actual client API key from [Project Settings > API Keys](https://console.statsig.com/api_keys). 2. **Initialize the SDK** The HTML snippet wraps an instance of the Statsig JavaScript SDK. Providing your client API key in the URL auto-initializes the SDK, as shown in the installation step. Move to manual initialization if you need any of the following: - custom user properties - custom initialization options - check gates, configs, experiments, or log events To manually initialize an instance of the SDK, remove the key parameter from the script tag and do the following: ```js const { StatsigClient, runStatsigAutoCapture, runStatsigSessionReplay } = window.Statsig; const client = new StatsigClient( '<CLIENT-SDK-KEY>', { userID: 'a-user' } ); runStatsigSessionReplay(client); runStatsigAutoCapture(client); await client.initializeAsync(); // check gates, configs, experiments, or log events ``` You can also access the `StatsigClient` instance you create through `window.Statsig`, so you can reference it globally. Your `StatsigClient` instance provides access to all methods in the [JavaScript SDK](https://docs.statsig.com/client/javascript-sdk). Go to that documentation for initialization details and core methods. #### Can I customize the initialization logic Yes. Remove the client API key from the URL. The HTML snippet is the JavaScript SDK. Providing an API key in the URL auto-initializes an instance. To skip auto-initialization, omit the key and create your own instance. Go to the [JavaScript SDK Getting Started Guide](https://docs.statsig.com/client/javascript-sdk#getting-started) for details. Creating an instance using the HTML snippet differs from installing through npm: ```js const { StatsigClient, runStatsigAutoCapture, runStatsigSessionReplay } = window.Statsig; const client = new StatsigClient( '<CLIENT-SDK-KEY>', { userID: 'a-user' } ); runStatsigSessionReplay(client); runStatsigAutoCapture(client); await client.initializeAsync(); // check gates, configs, experiments, or log events ``` ================================================================================ # React Client SDK URL: https://docs.statsig.com/client/React ================================================================================ # React Client SDK - **Package:** `@statsig/react-bindings` ([npm](https://www.npmjs.com/package/@statsig/react-bindings)) - **Latest version:** 3.33.7 - **Package size:** 25.3 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK 1. **Install the SDK** > **Info:** > > If you need a starter project, follow the official [React quickstart](https://react.dev/learn/build-a-react-app-from-scratch). Looking for Next.js instead? Go to the [Next.js SDK](https://docs.statsig.com/client/Next) docs. ### AI-powered setup Setup Statsig in 90 seconds by copying this AI prompt into your IDE: ```text You are a frontend engineer integrating the Statsig SDK into a React app. Follow these instructions carefully: 1. Install the required Statsig packages: npm install @statsig/react-bindings @statsig/session-replay @statsig/web-analytics 2. In the main component file (`App.jsx` or `App.tsx`): - Import `StatsigProvider` and `useClientAsyncInit` from `@statsig/react-bindings` - Import `StatsigAutoCapturePlugin` from `@statsig/web-analytics` and `StatsigSessionReplayPlugin` from `@statsig/session-replay` - Initialize the SDK using your client key: 'YOUR-CLIENT-API-KEY' - Use `userID` from an existing variable if it's already declared in the file; otherwise, default to `'a-user'` - Wrap the existing app content inside `<StatsigProvider>`, using `<div>Loading...</div>` as the `loadingComponent` 3. DO NOT remove any existing JSX content from the component. Just wrap it. 4. Here is what the final file structure should look like: import { StatsigProvider, useClientAsyncInit } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; import YourApp from './YourApp'; function App() { const id = typeof userID !== 'undefined' ? userID : 'a-user'; const { client } = useClientAsyncInit( 'YOUR-CLIENT-API-KEY', { userID: id }, { plugins: [new StatsigAutoCapturePlugin(), new StatsigSessionReplayPlugin()] } ); return ( <StatsigProvider client={client} loadingComponent={<div>Loading...</div>}> <YourApp /> </StatsigProvider> ); } 5. Ask the user to provide their CLIENT-API-KEY and insert it where prompted above. ``` ### Install packages #### npm ```bash npm install @statsig/react-bindings ``` #### yarn ```bash yarn add @statsig/react-bindings ``` > **Tip:** > > Add `@statsig/session-replay` and `@statsig/web-analytics` if you plan to enable Session Replay or Auto Capture. 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. ### Wrap your app with `StatsigProvider` Provide your client SDK key and initial user when you render the provider. ```tsx import { StatsigProvider } from '@statsig/react-bindings'; function App() { return ( <StatsigProvider sdkKey="client-KEY" user={{ userID: '1234', email: 'example@statsig.com' }}> <div>Hello world</div> </StatsigProvider> ); } ``` ### Typical project structure Most projects render a root component inside the provider. ```tsx // App.tsx import RootPage from './RootPage'; import { StatsigProvider } from '@statsig/react-bindings'; export default function App() { return ( <StatsigProvider sdkKey="client-KEY" user={{ userID: '1234' }}> <RootPage /> </StatsigProvider> ); } ``` ```tsx // RootPage.tsx export default function RootPage() { return <div>Hello World</div>; } ``` > **Info:** > > Need to balance startup speed with freshness? Review [Initialization Strategies](https://docs.statsig.com/client/concepts/initialize) for bootstrap and async options. ## Use the SDK Use `useStatsigClient` inside components to retrieve the client when you need to evaluate something. ```tsx import { useStatsigClient } from '@statsig/react-bindings'; const { client } = useStatsigClient(); ``` ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. ```tsx import { useFeatureGate, useGateValue, useStatsigClient, } from '@statsig/react-bindings'; const { checkGate } = useStatsigClient(); const gateValue = useGateValue('my_gate'); const gate = useFeatureGate('my_gate'); return ( <div> {checkGate('my_gate') && <p>Passing</p>} {gateValue && <p>Passing</p>} {gate.value && <p>Passing ({gate.details.reason})</p>} </div> ); ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: ```tsx import { useDynamicConfig, useStatsigClient } from '@statsig/react-bindings'; const config = useDynamicConfig('my_dynamic_config'); const { getDynamicConfig } = useStatsigClient(); return ( <div> <p>Reason: {config.details.reason}</p> <p>Value: {config.get('a_value', 'fallback_value')}</p> <p>Another Value: {getDynamicConfig('my_dynamic_config').get('a_bool', false)}</p> </div> ); ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```tsx import { useExperiment, useStatsigClient } from '@statsig/react-bindings'; const experiment = useExperiment('my_experiment'); const { getExperiment } = useStatsigClient(); return ( <div> <p>Group: {getExperiment('my_experiment').groupName}</p> <p>Value: {experiment.get('a_value', 'fallback_value')}</p> </div> ); ``` ```tsx import { useLayer, useStatsigClient } from '@statsig/react-bindings'; const layer = useLayer('my_layer'); const { getLayer } = useStatsigClient(); return ( <div> <p>Group: {getLayer('my_layer').groupName}</p> <p>Value: {layer.get('a_value', 'fallback_value')}</p> </div> ); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: ```tsx import { useStatsigClient } from '@statsig/react-bindings'; const { logEvent } = useStatsigClient(); return <button onClick={() => logEvent('my_event')}>Click Me</button>; ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```tsx import { useStatsigClient } from '@statsig/react-bindings'; const { client } = useStatsigClient(); return ( <button onClick={async () => { await client.flush(); }} > Flush Events </button> ); ``` ## Parameter Stores Parameter Stores hold a set of parameters for your app. You can remap these parameters dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers). This remapping decouples your code from the configuration in Statsig. Refer to [Parameter Stores](https://docs.statsig.com/client/concepts/parameter-stores) for details. ## Manage users ### Updating user properties Call `updateUserAsync` when a user logs in or when you collect richer attributes. ```tsx import { useGateValue, useStatsigUser } from '@statsig/react-bindings'; export default function AccountBanner() { const gateValue = useGateValue('check_user'); const { updateUserAsync } = useStatsigUser(); return ( <div> <div>Gate is {gateValue ? 'passing' : 'failing'}.</div> <button onClick={() => updateUserAsync({ userID: '2' })}>Login</button> </div> ); } ``` ## Loading state To wait for the latest values during initialization, use either the provider or the async hook. #### StatsigProvider ```tsx import { StatsigProvider } from '@statsig/react-bindings'; export function App() { return ( <StatsigProvider sdkKey="client-KEY" user={{ userID: 'a-user' }} loadingComponent={<div>Loading...</div>} > <YourComponent /> </StatsigProvider> ); } ``` #### useClientAsyncInit ```tsx import { StatsigProvider, useClientAsyncInit } from '@statsig/react-bindings'; export function App() { const { client, isLoading } = useClientAsyncInit( 'client-KEY', { userID: 'a-user' }, ); if (isLoading) { return <div>Loading...</div>; } return ( <StatsigProvider client={client}> <YourComponent /> </StatsigProvider> ); } ``` ## React hooks > **Warning:** > > Hooks that read gates, configs, experiments, or layers log exposures on render. Use `useStatsigClient` to defer checks until you actually change the UI. ### Feature Gate hooks - Recommended: `useStatsigClient().checkGate` logs when invoked. - `useGateValue` returns the boolean value and logs immediately. - `useFeatureGate` returns the full gate object with details. ```tsx import { useFeatureGate, useGateValue, useStatsigClient, } from '@statsig/react-bindings'; const { checkGate } = useStatsigClient(); const gateValue = useGateValue('my_gate'); const gate = useFeatureGate('my_gate'); return ( <div> {checkGate('my_gate') && <p>Passing</p>} {gateValue && <p>Passing</p>} {gate.value && <p>Passing ({gate.details.reason})</p>} </div> ); ``` ### Dynamic Config hooks - Recommended: `useStatsigClient().getDynamicConfig` defers exposure until called. - `useDynamicConfig` logs on render. ```tsx import { useDynamicConfig, useStatsigClient } from '@statsig/react-bindings'; const config = useDynamicConfig('my_dynamic_config'); const { getDynamicConfig } = useStatsigClient(); return ( <div> <p>Reason: {config.details.reason}</p> <p>Value: {config.get('a_value', 'fallback_value')}</p> <p>Another Value: {getDynamicConfig('my_dynamic_config').get('a_bool', false)}</p> </div> ); ``` ### Experiment hooks - Recommended: `useStatsigClient().getExperiment` to control exposures. - `useExperiment` logs on render. ```tsx import { useExperiment, useStatsigClient } from '@statsig/react-bindings'; const experiment = useExperiment('my_experiment'); const { getExperiment } = useStatsigClient(); return ( <div> <p>Group: {getExperiment('my_experiment').groupName}</p> <p>Value: {experiment.get('a_value', 'fallback_value')}</p> </div> ); ``` ### Layer hooks Layers only log exposures when you call `.get()`. ```tsx import { useLayer, useStatsigClient } from '@statsig/react-bindings'; const layer = useLayer('my_layer'); const { getLayer } = useStatsigClient(); return ( <div> <p>Group: {getLayer('my_layer').groupName}</p> <p>Value: {layer.get('a_value', 'fallback_value')}</p> </div> ); ``` ### Parameter Store hooks ```tsx import { useParameterStore } from '@statsig/react-bindings'; function MyComponent() { const store = useParameterStore('my_parameter_store'); const title = store.get('page_title', 'Default Title'); const maxItems = store.get('max_items', 10); const isEnabled = store.get('feature_enabled', false); const storeNoExposure = useParameterStore('my_parameter_store', { disableExposureLog: true, }); return <div>{title}</div>; } ``` ### Log events from hooks ```tsx import { useStatsigClient } from '@statsig/react-bindings'; const { logEvent } = useStatsigClient(); return <button onClick={() => logEvent('my_event')}>Click Me</button>; ``` ### StatsigUser hook ```tsx import { useStatsigUser } from '@statsig/react-bindings'; const { user, updateUserSync } = useStatsigUser(); return ( <div> <p>Current User: {user.userID}</p> <button onClick={() => updateUserSync({ userID: 'some-other-user' })}> Update User </button> </div> ); ``` ### Direct access to the client ```tsx import { useStatsigClient } from '@statsig/react-bindings'; const { client } = useStatsigClient(); console.log('stableID', client.getContext().stableID); ``` ### Client initialization hooks - `useClientAsyncInit`: fetches the latest values before rendering. - `useClientBootstrapInit`: bootstrap from server-provided values. > **Info:** > > You can also initialize your own client instance manually. Refer to [Initialization Strategies](https://docs.statsig.com/client/concepts/initialize) for alternatives. ## Statsig options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingEnabled | LoggingEnabledOption | No | browser-only | Controls logging behavior.- `browser-only` (default): log events from browser environments. - `disabled`: never send events. - `always`: log in every environment, including non-browser contexts. | Use `loggingEnabled: 'disabled'` instead. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | — | — | No | — | — | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStableID | boolean | No | false | Skip generating a device-level Stable ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableEvaluationMemoization | boolean | No | false | Recompute every evaluation instead of using the memoized result. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initialSessionID | string | No | — | Override the generated session ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableCookies | boolean | No | false | Persist Stable ID in cookies for cross-domain tracking. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStorage | boolean | No | — | Prevent any local storage writes (disables caching). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkConfig | NetworkConfig | No | — | Override network endpoints per request type. | #### Network Config Options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | https://api.statsig.com | Base URL for all requests. The SDK appends endpoint paths like `/initialize` and `/rgstr`; append `/v1` when your proxy expects it. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeUrl | string | No | https://featureassets.org/v1/initialize | Endpoint for initialization requests only. Takes precedence over `api` for `/initialize`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeFallbackUrls | string[] | No | — | Fallback endpoints for initialization requests only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | https://prodregistryv2.org/v1/rgstr | Endpoint for event uploads. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventFallbackUrls | string[] | No | — | Fallback endpoints for event uploads only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkTimeoutMs | number | No | 10000 | Request timeout in milliseconds. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | preventAllNetworkTraffic | boolean | No | — | Disable all outbound requests; combine with `loggingEnabled: 'disabled'` to silence log warnings. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkOverrideFunc | function | No | — | Provide custom transport (e.g., Axios). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | Set environment-wide defaults (for example `{ tier: 'staging' }`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logLevel | LogLevel | No | Warn | Console verbosity. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingBufferMaxSize | number | No | 50 | Max events per log batch. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | 10_000 | Interval between automatic flushes. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideAdapter | OverrideAdapter | No | — | Modify evaluations before returning them. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeCurrentPageUrlWithEvents | boolean | No | true | Attach the current page URL to logged events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStatsigEncoding | boolean | No | false | Send requests without Statsig-specific encoding. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventCompressionMode | LogEventCompressionMode | No | Enabled | Control compression for batched events. | Use `logEventCompressionMode` instead. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | — | — | No | — | — | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | EvaluationsDataAdapter | No | — | Provide a custom data adapter to control caching/fetching. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | customUserCacheKeyFunc | CustomCacheKeyGenerator | No | — | Override cache key generation for stored evaluations. | ## Testing Mock Statsig hooks in Jest to isolate component logic. ```tsx import { StatsigProvider, useFeatureGate, useExperiment } from '@statsig/react-bindings'; function Content() { const gate = useFeatureGate('a_gate'); const experiment = useExperiment('an_experiment'); return ( <div> <div data-testid="gate_test">a_gate: {gate.value ? 'Pass' : 'Fail'}</div> <div data-testid="exp_test"> an_experiment: {experiment.get('my_param', 'fallback')} </div> </div> ); } function App() { return ( <StatsigProvider sdkKey={YOUR_CLIENT_KEY} user={{ userID: 'a-user' }} options={{ networkConfig: { // Optional – disable network requests in tests preventAllNetworkTraffic: typeof process !== 'undefined' && process.env['NODE_ENV'] === 'test', }, }} > <Content /> </StatsigProvider> ); } ``` ```tsx import { render, screen } from '@testing-library/react'; import * as ReactBindings from '@statsig/react-bindings'; jest.mock('@statsig/react-bindings', () => ({ ...jest.requireActual('@statsig/react-bindings'), useFeatureGate: () => ({ value: true }), useExperiment: () => ({ get: () => 'my_value' }), })); test('renders gate pass', async () => { render(<App />); const elem = await screen.findByTestId('gate_test'); expect(elem.textContent).toContain('Pass'); }); test('renders experiment value', async () => { render(<App />); const elem = await screen.findByTestId('exp_test'); expect(elem.textContent).toContain('my_value'); }); ``` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```tsx import { useEffect } from 'react'; import { useStatsigClient } from '@statsig/react-bindings'; const { client } = useStatsigClient(); useEffect(() => { return () => { void client.shutdown(); }; }, [client]); ``` ## Session Replay Install `@statsig/session-replay` and register the plugin to record user sessions. ```tsx import { StatsigProvider, useClientAsyncInit } from '@statsig/react-bindings'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; function App() { const { client } = useClientAsyncInit( 'client-KEY', { userID: 'a-user' }, { plugins: [new StatsigSessionReplayPlugin()] }, ); return ( <StatsigProvider client={client} loadingComponent={<div>Loading...</div>}> <div>Hello World</div> </StatsigProvider> ); } ``` ## Web Analytics / Auto Capture By including the [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) package in your project, you can automatically capture common web events like clicks and page views. For more information on filtering events, enabling console log capture, and other configuration options in web analytics, refer to the [Web Analytics Configuration](https://docs.statsig.com/webanalytics/overview#event-filtering-and-console-configuration) documentation. ```tsx import { StatsigProvider, useClientAsyncInit } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; function App() { const { client } = useClientAsyncInit( 'client-KEY', { userID: 'a-user' }, { plugins: [new StatsigAutoCapturePlugin()] }, ); return ( <StatsigProvider client={client} loadingComponent={<div>Loading...</div>}> <div>Hello World</div> </StatsigProvider> ); } ``` ## Using persistent evaluations To keep experiment variants stable across rerenders or user transitions, use persistent storage. The React integration mirrors the [JavaScript workflow](https://docs.statsig.com/client/javascript-sdk#using-persistent-evaluations) and you can adapt the [Next.js sample](https://github.com/statsig-io/js-client-monorepo/tree/main/samples/next-js/src/app/persisted-user-storage-example) to your setup. Read more in [Client Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment). ## Additional resources - [Initialization Concepts](https://docs.statsig.com/client/concepts/initialize) - [JavaScript Client SDK](https://docs.statsig.com/client/javascript-sdk) - [Persistent Assignment](https://docs.statsig.com/client/concepts/persistent_assignment) ================================================================================ # Next.js Client SDK URL: https://docs.statsig.com/client/Next ================================================================================ # Next.js Client SDK - **Package:** `@statsig/react-bindings` ([npm](https://www.npmjs.com/package/@statsig/react-bindings)) - **Latest version:** 3.33.7 - **Package size:** 25.3 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK ### AI-powered setup Setup Statsig in 90 seconds by copying this AI prompt into your IDE: ```text # Statsig SDK Integration for Next.js You are a frontend engineer integrating the Statsig SDK into a **Next.js application**. Follow all steps below one by one: --- ## Full Integration Instructions 1. **Detect the package manager** by checking for: - `package-lock.json` → use `npm` - `yarn.lock` → use `yarn` - `pnpm-lock.yaml` → use `pnpm` 2. **Detect the Next.js router type** by checking for: - `app/` directory → **App Router** - `pages/` directory → **Pages Router** 3. **Install the Statsig package** using the correct package manager: # For npm npm install @statsig/react-bindings @statsig/session-replay @statsig/web-analytics # For yarn yarn add @statsig/react-bindings @statsig/session-replay @statsig/web-analytics # For pnpm pnpm add @statsig/react-bindings @statsig/session-replay @statsig/web-analytics 4. Add your Statsig client key to .env.local: NEXT_PUBLIC_STATSIG_CLIENT_KEY=ask the user for their CLIENT KEY and use that input 5. Integrate Statsig into the app (auto-detect router type): ### If the project uses the App Router (has an app/ directory): // Create app/my-statsig.tsx "use client"; import React from "react"; import { LogLevel, StatsigProvider } from "@statsig/react-bindings"; export default function MyStatsig({ children }: { children: React.ReactNode }) { const id = typeof userID !== "undefined" ? userID : "a-user"; const user = { userID: id, // Optional additional fields: // email: 'user@example.com', // customIDs: { internalID: 'internal-123' }, // custom: { plan: 'premium' } }; return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={user} options={{ logLevel: LogLevel.Debug }} > {children} </StatsigProvider> ); } // Update app/layout.tsx to wrap children with MyStatsig import MyStatsig from "./my-statsig"; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode }>) { return ( <html lang="en"> <body> <MyStatsig> {children} {/* Preserve all existing layout content */} </MyStatsig> </body> </html> ); } ### If the project uses the Pages Router (has a pages/ directory): // Update pages/_app.tsx import type { AppProps } from "next/app"; import { LogLevel, StatsigProvider } from "@statsig/react-bindings"; export default function App({ Component, pageProps }: AppProps) { const id = typeof userID !== "undefined" ? userID : "a-user"; const user = { userID: id, // Optional additional fields: // email: 'user@example.com', // customIDs: { internalID: 'internal-123' }, // custom: { plan: 'premium' } }; return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={user} options={{ logLevel: LogLevel.Debug }} > <Component {...pageProps} /> {/* Preserve all existing pages */} </StatsigProvider> ); } ### Final Notes - The system must **detect the router type** and **apply the correct integration automatically**. - **Do not remove or change any existing JSX or layout structure**: only wrap the app with `StatsigProvider`. - **Preserve the file's language**: if it's TypeScript (`.tsx`), keep it as TypeScript; if it's JavaScript (`.jsx`), keep it as JavaScript. - After these steps, Statsig will be integrated across the entire app, with **feature gates, configs, and experiments** available everywhere. ``` ### Manual setup Statsig supports both [Page Router](https://nextjs.org/docs/pages) & [App Router](https://nextjs.org/docs/app), with some differences in integration patterns. #### App Router 1. **Set environment variables** Add the keys to your .env.local file: ```bash # the NEXT_PUBLIC_ prefix is required for this to be available on the client side NEXT_PUBLIC_STATSIG_CLIENT_KEY=client-<REPLACE_WITH_YOUR_CLIENT_KEY> STATSIG_SERVER_KEY=secret-<REPLACE_WITH_YOUR_SERVER_KEY> ``` 2. **Install packages** For App Router, install the @statsig/next package: #### NPM ```bash npm i @statsig/next ``` #### Yarn ```bash yarn add @statsig/next ``` #### PNPM ```bash pnpm add @statsig/next ``` 3. **Add the StatsigBootstrapProvider** The `<StatsigBootstrapProvider>` creates both a Statsig Client and Server instance internally, and ["bootstraps"](https://docs.statsig.com/client/concepts/initialize#2-bootstrap-initialization) the client so it can render each page without a blocking network request. Bootstrapping keeps your app fast, and Statsig recommends it for most users. If you need more control over your setup, refer to [Bootstrapping](#client-bootstrapping-recommended) and [React](https://docs.statsig.com/client/React) for more guidance. Add this component around the content in your root `layout.tsx` file: ```tsx import { StatsigBootstrapProvider } from "@statsig/next" export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { const user = { userID: "user-123", // add additional parameters as needed }; return ( <html lang="en"> <body> <StatsigBootstrapProvider user={user} clientKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY} serverKey={process.env.STATSIG_SERVER_KEY} > {children} </StatsigBootstrapProvider> </body> </html> ); } ``` #### Page Router 1. **Set environment variables** Add the keys to your .env.local file: ```bash # the NEXT_PUBLIC_ prefix is required for this to be available on the client side NEXT_PUBLIC_STATSIG_CLIENT_KEY=client-<REPLACE_WITH_YOUR_CLIENT_KEY> ``` 2. **Install packages** Install the @statsig/react-bindings package: #### NPM ```bash npm i @statsig/react-bindings @statsig/web-analytics ``` #### Yarn ```bash yarn add @statsig/react-bindings @statsig/web-analytics ``` #### PNPM ```bash pnpm add @statsig/react-bindings @statsig/web-analytics ``` 3. **Add StatsigProvider to \_app.tsx** To integrate Statsig into your Page Router app you can add the `StatsigProvider` to your `_app.tsx` file. There is a [full example](https://github.com/statsig-io/js-client-monorepo/tree/main/samples/next-js-pages-router-sample) in the samples directory of the javascript sdk. ```tsx import type { AppProps } from "next/app"; import { LogLevel, StatsigProvider, } from "@statsig/react-bindings"; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; export default function App({ Component, pageProps }: AppProps) { return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={{ userID: "a-user" }} options={{ plugins: [ new StatsigAutoCapturePlugin() ], }}> <Component {...pageProps} /> </StatsigProvider> ); } ``` Refer to the [User (StatsigUser)](https://docs.statsig.com/sdks/user) documentation for more information on the user property. After completing setup, you can check gates, experiments, and log events in any sub-file of layout.tsx. ## Use the SDK ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. #### App Router ```tsx 'use client'; import { useGateValue } from "@statsig/react-bindings"; export default function Home() { const gate = useGateValue("my_gate"); return ( <div> Gate Value: {gate ? 'PASSED' : 'FAILED'} </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useGateValue } from "@statsig/react-bindings"; export default function Home() { const gate = useGateValue("my_gate"); return ( <div> Gate Value: {gate ? 'PASSED' : 'FAILED'} </div> ); } ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: #### App Router ```tsx 'use client'; import { useDynamicConfig } from "@statsig/react-bindings"; export default function Home() { const config = useDynamicConfig("my_dynamic_config"); return ( <div> Title: {config.get('title', 'Fallback Title')} </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useDynamicConfig } from "@statsig/react-bindings"; export default function Home() { const config = useDynamicConfig("my_dynamic_config"); return ( <div> Title: {config.get('title', 'Fallback Title')} </div> ); } ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. #### App Router ```tsx 'use client'; import { useExperiment, useLayer} from "@statsig/react-bindings"; export default function Home() { const layer = useLayer("my_experiment_layer"); // or const experiment = useExperiment("my_experiment"); return ( <div> Title: {layer.get('title', 'Fallback Title')} {/* or */} Title: {experiment.get('title', 'Fallback Title')} </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useExperiment, useLayer} from "@statsig/react-bindings"; export default function Home() { const layer = useLayer("my_experiment_layer"); // or const experiment = useExperiment("my_experiment"); return ( <div> Title: {layer.get('title', 'Fallback Title')} {/* or */} Title: {experiment.get('title', 'Fallback Title')} </div> ); } ``` ## Parameter Stores Parameter Stores hold a set of parameters for your app. You can remap these parameters dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers). This remapping decouples your code from the configuration in Statsig. Refer to [Parameter Stores](https://docs.statsig.com/client/concepts/parameter-stores) for details. #### App Router ```tsx 'use client'; import { useParameterStore} from "@statsig/react-bindings"; export default function Home() { const store = useParameterStore("my_param_store"); return ( <div> Title: {store.get('title', 'Fallback Title')} </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useParameterStore} from "@statsig/react-bindings"; export default function Home() { const store = useParameterStore("my_param_store"); return ( <div> Title: {store.get('title', 'Fallback Title')} </div> ); } ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: #### App Router ```tsx 'use client'; import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); return ( <div> <button onClick={() => client.logEvent("my_custom_event")}> Click Me </button> </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); return ( <div> <button onClick={() => client.logEvent("my_custom_event")}> Click Me </button> </div> ); } ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. #### App Router ```tsx 'use client'; import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); return ( <div> <button onClick={async () => { await client.flush(); }} > Flush Events </button> </div> ); } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); return ( <div> <button onClick={async () => { await client.flush(); }} > Flush Events </button> </div> ); } ``` ## Session Replay #### App Router ```tsx 'use client'; import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; export default function App({ children }: { children: React.ReactNode }) { return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={{ userID: 'a-user' }} options={{ plugins: [new StatsigSessionReplayPlugin()] }} > {children} </StatsigProvider> ); } ``` #### Page Router ```tsx import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; export default function App({ Component, pageProps }) { return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={{ userID: 'a-user' }} options={{ plugins: [new StatsigSessionReplayPlugin()] }} > <Component {...pageProps} /> </StatsigProvider> ); } ``` ## Web Analytics / Auto Capture By including the [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) package in your project, you can automatically capture common web events like clicks and page views. For more information on filtering events, enabling console log capture, and other configuration options in web analytics, refer to the [Web Analytics Configuration](https://docs.statsig.com/webanalytics/overview#event-filtering-and-console-configuration) documentation. #### App Router ```tsx 'use client'; import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; export default function App({ children }: { children: React.ReactNode }) { return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={{ userID: 'a-user' }} options={{ plugins: [new StatsigAutoCapturePlugin()] }} > {children} </StatsigProvider> ); } ``` #### Page Router ```tsx import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; export default function App({ Component, pageProps }) { return ( <StatsigProvider sdkKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!} user={{ userID: 'a-user' }} options={{ plugins: [new StatsigAutoCapturePlugin()] }} > <Component {...pageProps} /> </StatsigProvider> ); } ``` ## Stable ID Stable ID provides a consistent device identifier. It lets you run [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) and target gates at the device level. ### How Stable ID works - On first initialization, the SDK generates a Stable ID and stores it in `localStorage` under `statsig.stable_id.<SDK_KEY_HASH>`. - Subsequent sessions reuse the stored value. Each client SDK key has its own Stable ID entry. - Statsig scopes local storage per domain, so cross-domain usage requires sharing the value manually (refer to Sharing Stable ID across subdomains). ### Reading the Stable ID #### JavaScript ```tsx const context = client.getContext(); console.log('Statsig StableID:', context.stableID); ``` #### React ```tsx import { useStatsigClient } from '@statsig/react-bindings'; function MyComponent() { const { client } = useStatsigClient(); const context = client.getContext(); return <div>{context.stableID}</div>; } ``` ### Overriding the Stable ID Provide a custom Stable ID through `StatsigUser.customIDs.stableID` if you already manage a durable device identifier. #### JavaScript ```tsx import { StatsigClient, StatsigUser } from '@statsig/js-client'; const userWithStableID: StatsigUser = { customIDs: { stableID: 'my-custom-stable-id', }, }; const client = new StatsigClient('client-xyz', userWithStableID); await client.updateUserAsync(userWithStableID); ``` #### React ```tsx import { StatsigProvider, useStatsigClient } from '@statsig/react-bindings'; function App() { return ( <StatsigProvider sdkKey="client-xyz" user={{ customIDs: { stableID: 'my-custom-stable-id' }, }} > <div>Your App</div> </StatsigProvider> ); } function MyComponent() { const { client } = useStatsigClient(); useEffect(() => { client.updateUserAsync({ customIDs: { stableID: 'my-custom-stable-id' }, }); }, [client]); } ``` > **Note:** > > When you override the Stable ID, Statsig persists it to local storage, so subsequent sessions reuse your custom value. ### Sharing Stable ID across subdomains Add this helper script before initializing the SDK and then copy the stored value onto your user object. ```html <!-- cross domain id script --> <script>!function(){let t="STATSIG_LOCAL_STORAGE_STABLE_ID";function e(){if(crypto&&crypto.randomUUID)return crypto.randomUUID();let t=()=>Math.floor(65536*Math.random()).toString(16).padStart(4,"0");return`$\{t()\}${t()}-$\{t()\}-4${t().substring(1)}-$\{t()\}-${t()}$\{t()\}${t()}`}let i=null,n=localStorage.getItem(t)||null;if(document.cookie.match(/statsiguuid=([\w-]+);?/)&&([,i]=document.cookie.match(/statsiguuid=([\w-]+);?/)),i&&n&&i===n);else if(i&&n&&i!==n)localStorage.setItem(t,i);else if(i&&!n)localStorage.setItem(t,i);else{let o=e();localStorage.setItem(t,o),function t(i){let n=new Date;n.setMonth(n.getMonth()+12);let o=window.location.host.split(".");o.length>2&&o.shift();let s=`.$\{o.join(".")\}`;document.cookie=`statsiguuid=${i||e()};Expires=$\{n\};Domain=${s};Path=/`}(o)}}();</script> <!-- Manually attach stableID to user object --> <script> const userObj = {}; if (localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID')) { userObj.customIDs = { stableID: localStorage.getItem('STATSIG_LOCAL_STORAGE_STABLE_ID'), }; } const client = new Statsig.StatsigClient('<client-sdk-key>', userObj); </script> ``` _Use this script at your discretion and test thoroughly._ ### Aligning Stable ID between client and server To share Stable ID with a backend Statsig SDK, send the value with requests and persist it server-side when missing. The server can bootstrap the client with the same Stable ID. ```tsx // Server: ensure Stable ID exists, then return initialize response for the client const values = Statsig.getClientInitializeResponse(user, YOUR_CLIENT_KEY, { hash: 'djb2', }); // Client: apply the server-provided values and initialize synchronously const { values, user: verifiedUser } = await fetch('/init-statsig-client', { method: 'POST', body: loadUserData(), }).then((res) => res.json()); const myClient = new StatsigClient(YOUR_CLIENT_KEY, verifiedUser); myClient.dataAdapter.setData(values); myClient.initializeSync(); ``` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: #### App Router ```tsx 'use client'; import { useEffect } from "react"; import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); useEffect(() => { return () => { void client.shutdown(); }; }, [client]); return null; } ``` > **Note:** > > In an App Router app, you need to use the [`use client` directive](https://nextjs.org/docs/app/building-your-application/rendering/client-components) to ensure your logic runs on the frontend. #### Page Router ```tsx import { useEffect } from "react"; import { useStatsigClient } from "@statsig/react-bindings"; export default function Home() { const { client } = useStatsigClient(); useEffect(() => { return () => { void client.shutdown(); }; }, [client]); return null; } ``` ## Advanced setup ### Client bootstrapping (recommended) #### App Router ```ts import { Statsig, StatsigUser } from '@statsig/statsig-node-core'; export async function POST(request: Request): Promise<Response> { const body = await request.json(); const user = new StatsigUser(body?.user ?? {}); // Ensure server SDK is initialized at startup // await Statsig.initialize(process.env.STATSIG_SERVER_KEY!); const values = Statsig.getClientInitializeResponse(user, { hashAlgorithm: 'djb2', }); return new Response(JSON.stringify(values), { status: 200 }); } ``` ```tsx import { StatsigBootstrapProvider } from '@statsig/next'; export default function RootLayout({ children }: { children: React.ReactNode }) { const user = { userID: 'user-123' }; return ( <html lang="en"> <body> <StatsigBootstrapProvider user={user} clientKey={process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY} serverKey={process.env.STATSIG_SERVER_KEY} > {children} </StatsigBootstrapProvider> </body> </html> ); } ``` #### Page Router ```ts import type { NextApiRequest, NextApiResponse } from 'next'; import { Statsig, StatsigUser } from 'statsig-node'; // legacy Node SDK for pages router export default async function handler( req: NextApiRequest, res: NextApiResponse<string>, ) { if (req.method !== 'POST') { res.status(400).send('/statsig-bootstrap only supports POST'); return; } // Ensure server SDK is initialized at startup // await Statsig.initialize(process.env.STATSIG_SERVER_KEY!); const { user } = JSON.parse(req.body) as { user: StatsigUser }; const values = Statsig.getClientInitializeResponse(user, { hash: 'djb2' }); res.status(200).send(JSON.stringify(values)); } ``` ```tsx import type { AppProps } from 'next/app'; import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigClient } from '@statsig/js-client'; import { useEffect, useMemo, useState } from 'react'; export default function App({ Component, pageProps }: AppProps) { const user = useMemo(() => ({ userID: 'a-user' }), []); const [client, setClient] = useState<StatsigClient | null>(null); useEffect(() => { (async () => { const res = await fetch('/api/statsig-bootstrap', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ user }), }); const initializeValues = await res.json(); const inst = new StatsigClient( process.env.NEXT_PUBLIC_STATSIG_CLIENT_KEY!, user, { initializeValues }, ); await inst.initializeAsync(); setClient(inst); })(); }, [user]); if (!client) { return null; } return ( <StatsigProvider client={client}> <Component {...pageProps} /> </StatsigProvider> ); } ``` ### Proxying network traffic (optional) #### App Router ```ts // Note: Using generic path names like "proxy" instead of "statsig-proxy" // to prevent ad blockers from blocking these requests import { generateBootstrapValues } from './statsig-backend'; export async function POST(request: Request): Promise<Response> { const json = await request.json(); if (!json || typeof json !== 'object') { return new Response(null, { status: 400 }); } const data = await generateBootstrapValues(); return new Response(data); } ``` ```ts // Note: Using generic path names like "search" instead of "log_event" or "events" // to prevent ad blockers from blocking these requests type ExtendedRequestInit = RequestInit & { duplex?: 'half' | 'full' }; export async function POST(request: Request): Promise<Response> { const tail = request.url.split('?').pop(); const logEventUrl = `https://events.statsigapi.net/v1/log_event?${tail}`; const fetchOptions: ExtendedRequestInit = { method: 'POST', body: request.body, headers: request.headers, duplex: 'half', }; return fetch(logEventUrl, fetchOptions); } ``` #### Page Router ```ts // Note: Using generic path names like "proxy" instead of "statsig-proxy" // to prevent ad blockers from blocking these requests import type { NextApiRequest, NextApiResponse } from 'next'; import { StatsigUser } from 'statsig-node'; import { getStatsigValues } from '@/pages/statsig-backend'; export default async function handler( req: NextApiRequest, res: NextApiResponse<string>, ) { if (req.method !== 'POST') { res.status(400).send('/initialize only supports POST'); return; } const { user } = JSON.parse(req.body) as { user: StatsigUser }; const values = await getStatsigValues(user); res.status(200).send(values); } ``` ```ts // Note: Using generic path names like "search" instead of "log_event" or "events" // to prevent ad blockers from blocking these requests import type { NextApiRequest, NextApiResponse } from 'next'; type ExtendedRequestInit = RequestInit & { duplex?: 'half' | 'full' }; export default async function handler( req: NextApiRequest, res: NextApiResponse<string>, ): Promise<void> { if (req.method !== 'POST') { res.status(400).send('/search only supports POST'); return; } let logEventUrl = `https://events.statsigapi.net/v1/log_event`; const queryParams = [] as string[]; for (const [key, value] of Object.entries(req.query)) { queryParams.push(`$\{key\}=${value}`); } if (queryParams.length > 0) { logEventUrl += '?' + queryParams.join('&'); } const fetchOptions: ExtendedRequestInit = { method: 'POST', body: req.body as BodyInit, headers: req.headers as HeadersInit, duplex: 'half', }; try { const response = await fetch(logEventUrl, fetchOptions); if (!response.ok) { res.status(500).send('Failed to log event'); return; } const body = await response.text(); res.status(response.status).send(body); } catch (err) { res.status(500).send('Failed to log event: ' + err); } } ``` ```ts // Assign URLs when creating the client const inst = new StatsigClient(clientSdkKey, user, { networkConfig: { logEventUrl: '/api/proxy/search', initializeUrl: '/api/proxy/initialize', logEventCompressionMode: 'Forced', }, disableCompression: true, disableStatsigEncoding: true, }); ``` ## Static site generation (SSG) Static Site Generation renders HTML at build time. Because static HTML can't respond to per-user values, experimenting on SSG content requires one of these patterns: - Use Edge Middleware with Statsig's Edge Config Adapter for zero-latency redirects. - Isolate Statsig usage to hydrated client components only. ```tsx // Create a single client and share it across multiple StatsigProviders const myStatsigClient = new StatsigClient(YOUR_SDK_KEY, user, options); await myStatsigClient.initializeAsync(); <StatsigProvider client={myStatsigClient}> <YourComponent /> </StatsigProvider> <StatsigProvider client={myStatsigClient}> <AnotherComponent /> </StatsigProvider> ``` ## Statsig options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingEnabled | LoggingEnabledOption | No | — | Controls logging behavior.- `browser-only` (default): log events from browser environments. - `disabled`: never send events. - `always`: log in every environment, including non-browser contexts. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableLogging | boolean | No | — | Use `loggingEnabled: 'disabled'` instead. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStableID | boolean | No | — | Skip generating a device-level Stable ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableEvaluationMemoization | boolean | No | — | Recompute every evaluation instead of using the memoized result. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initialSessionID | string | No | — | Override the generated session ID. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableCookies | boolean | No | — | Persist Stable ID in cookies for cross-domain tracking. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStorage | boolean | No | — | Prevent any local storage writes (disables caching). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkConfig | NetworkConfig | No | — | Override network endpoints per request type. | #### Network Config Options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | Base URL for all requests. The SDK appends endpoint paths like `/initialize` and `/rgstr`; append `/v1` when your proxy expects it. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeUrl | string | No | — | Endpoint for initialization requests only. Takes precedence over `api` for `/initialize`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeFallbackUrls | string[] | No | — | Fallback endpoints for initialization requests only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | Endpoint for event uploads. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventFallbackUrls | string[] | No | — | Fallback endpoints for event uploads only. This doesn't create a generic fallback for `api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkTimeoutMs | number | No | — | Request timeout in milliseconds. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | preventAllNetworkTraffic | boolean | No | — | Disable all outbound requests; combine with `loggingEnabled: 'disabled'` to silence log warnings. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkOverrideFunc | function | No | — | Provide custom transport (e.g., Axios). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | Set environment-wide defaults (for example `{ tier: 'staging' }`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logLevel | LogLevel | No | — | Console verbosity. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingBufferMaxSize | number | No | — | Max events per log batch. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | — | Interval between automatic flushes. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideAdapter | OverrideAdapter | No | — | Modify evaluations before returning them. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeCurrentPageUrlWithEvents | boolean | No | — | Attach the current page URL to logged events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableStatsigEncoding | boolean | No | — | Send requests without Statsig-specific encoding. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventCompressionMode | LogEventCompressionMode | No | — | Control compression for batched events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableCompression | boolean | No | — | Use `logEventCompressionMode` instead. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | EvaluationsDataAdapter | No | — | Provide a custom data adapter to control caching/fetching. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | customUserCacheKeyFunc | CustomCacheKeyGenerator | No | — | Override cache key generation for stored evaluations. | ## Additional resources - [JavaScript Client SDK](https://docs.statsig.com/client/javascript-sdk) - [React Client SDK](https://docs.statsig.com/client/React) - [Initialization Concepts](https://docs.statsig.com/client/concepts/initialize) ================================================================================ # Android Client SDK URL: https://docs.statsig.com/client/Android ================================================================================ # Android Client SDK - **Package:** `com.statsig:android-sdk` ([maven](https://search.maven.org/artifact/com.statsig/android-sdk)) - **Latest version:** 5.1.6 - **Repository:** [android-sdk](https://github.com/statsig-io/android-sdk) ## Set up the SDK 1. **Install the SDK** v4.37.1 and higher are published to only [Maven Central](https://central.sonatype.com/artifact/com.statsig/android-sdk). To install the SDK, set the Maven Central repository in your build.gradle. ```java dependencies { implementation "com.statsig:android-sdk:4.37.1" } ``` You can install legacy versions (<=V4.37.0) with [Jitpack](https://jitpack.io/#statsig-io/android-sdk). 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. #### MainActivity.java ```java import com.statsig.androidsdk.*; ... public class MainActivity extends AppCompatActivity implements IStatsigCallback { ... StatsigOptions options = new StatsigOptions(); options.setTier(Tier.PRODUCTION); StatsigUser user = new StatsigUser("UUID"); Statsig.initializeAsync(app, "client-key", user, this, options); ... // SDK is usable, but values will be from the cache or defaults (false for gates, {} for configs) // Once onStatsigInitialize fires, then @Override public void onStatsigInitialize() { // SDK is initialized and has the most up to date values } @Override public void onStatsigUpdateUser() { // User has been updated and values have been refetched for the new user } } ``` #### MainActivity.kt ```kotlin import com.statsig.androidsdk.* ... async { Statsig.initialize( this.application, "my_client_sdk_key", StatsigUser("user_id"), ) }.await() ``` ## Use the SDK ### Checking a Feature Flag/Gate After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. #### Java ```java DynamicConfig config = Statsig.getConfig("awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. String itemName = config.getString("product_name", "Awesome Product v1"); Double price = config.getDouble("price", 10.0); Boolean shouldDiscount = config.getBoolean("discount", false); ``` #### Kotlin ```kotlin val config = Statsig.getConfig("awesome_product_details") // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. val itemName = config.getString("product_name", "Awesome Product v1") val price = config.getDouble("price", 10.0) val shouldDiscount = config.getBoolean("discount", false) ``` ### Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example: #### Java ```java if (Statsig.checkGate("new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` #### Kotlin ```kotlin if (Statsig.checkGate("new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Getting a Layer/Experiment **Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. #### Java ```java // Values via getLayer Layer layer = Statsig.getLayer("user_promo_experiments") String promoTitle = layer.getString("title", "Welcome to Statsig!"); Double discount = layer.getDouble("discount", 0.1); // or, via getExperiment DynamicConfig titleExperiment = Statsig.getExperiment("new_user_promo_title"); DynamicConfig priceExperiment = Statsig.getExperiment("new_user_promo_price"); String promoTitle = titleExperiment.getString("title", "Welcome to Statsig!"); Double discount = priceExperiment.getDouble("discount", 0.1); ... Double price = msrp * (1 - discount); ``` #### Kotlin ```kotlin // Values via getLayer val layer = Statsig.getLayer("user_promo_experiments") val promoTitle = layer.getString("title", "Welcome to Statsig!") val discount = layer.getDouble("discount", 0.1) // or, via getExperiment val titleExperiment = Statsig.getExperiment("new_user_promo_title") val priceExperiment = Statsig.getExperiment("new_user_promo_price") val promoTitle = titleExperiment.getString("title", "Welcome to Statsig!") val discount = priceExperiment.getDouble("discount", 0.1) ... val price = msrp * (1 - discount); ``` ### Logging an Event After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event: #### Java ```java Statsig.logEvent("purchase", 2.99, Map.of("item_name", "remove_ads")); ``` #### Kotlin ```kotlin Statsig.logEvent("purchase", 2.99, Map.of("item_name" to "remove_ads")) ``` ## Parameter Stores Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers). Remapping lets you decouple your code from the configuration in Statsig. Refer to [Param Stores](https://docs.statsig.com/client/concepts/parameter-stores) for more information. ### Getting a parameter store To fetch a set of parameters, use the following API: #### Java ```java ParameterStore homepageStore = Statsig.getParameterStore("homepage"); ``` #### Kotlin ```kotlin val homepageStore = Statsig.getParameterStore("homepage") ``` ### Getting a parameter You can then access parameters like this: #### Java ```java String title = homepageStore.getString( "title", //parameter name "Welcome" // default value ); boolean shouldShowUpsell = homePageStore.getBoolean("upsell_upgrade_now", false); ``` #### Kotlin ```kotlin val title = homepageStore.getString( "title", // parameter name "Welcome", // default value ) val shouldShowUpsell = homepageStore.getBoolean("upsell_upgrade_now", false) ``` ## Statsig User You need to provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. The `userID` field is required in most cases to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) for how to run experiments for logged-out users). In addition to `userID`, StatsigUser offers the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: #### Java ```java StatsigUser newUser = new StatsigUser("new_user_id"); Statsig.updateUserAsync(newUser, this); // this must implement IStatsigCallback ... @Override public void onStatsigUpdateUser() { // User has been updated and values have been refetched for the new user } ``` #### Kotlin ```kotlin Statsig.updateUser(StatsigUser("new_user_id")) ``` ### Private attributes To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from logs before sending them to the server. For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options Pass an optional `options` parameter in addition to `sdkKey` and `user` during initialization to customize the Statsig client. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | String | No | — | Default endpoint for all SDK network requests. Don't override unless you implement the Statsig API elsewhere. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableCurrentActivityLogging | Boolean | No | — | Include the current top-level activity on logged events by default. Set to `true` to disable. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableDiagnosticsLogging | Boolean | No | — | Deprecated. Previously prevented the SDK from sending diagnostic information. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initTimeoutMs | Long | No | — | Milliseconds to wait for the initial request before completing. Set to `0` to wait indefinitely. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableAutoValueUpdate | Boolean | No | — | Periodically fetch updated values for the current user when enabled. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | autoValueUpdateIntervalMinutes | Double | No | — | Frequency (in minutes) for auto value refresh. Minimum is `1` minute. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideStableID | String? | No | — | Override the SDK-generated `stableID` for the user. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loadCacheAsync | Boolean | No | — | Whether the SDK should block on loading saved values from disk. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeValues | Map<String, Any>? | No | — | Provide the initialize response directly to bootstrap the client synchronously. Go to the NodeJS Server SDK for generating values and the Bootstrap docs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableHashing | Boolean? | No | — | When `true`, gate/config/experiment names aren't hashed and remain readable. Requires special authorization from Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | customCacheKey | ((sdkKey: String, user: StatsigUser) -> String) | No | — | Override how Statsig generates the cache key for stored values when the default doesn't fit your needs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | evaluationCallback | ((config: BaseConfig) -> Unit) | No | — | Callback invoked whenever you check a gate, config, experiment, or layer. Receives the evaluated `BaseConfig`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | lifetimeCallback | IStatsigLifetimeCallback? | No | — | Callbacks that may trigger multiple times over the lifetime of the client SDK. The SDK calls them on the main thread.- `onValuesUpdated()` - called when new values are received and available for use. May be called after `Statsig.updateUser()`, `Statsig.updateUserAsync()`, or auto value updates (refer to `enableAutoValueUpdate`) | #### Methods - **setTier | setEnvironmentParameter | getEnvironment** - signals the environment tier the user is in. - `setTier` can be PRODUCTION, STAGING or DEVELOPMENT. For example, passing a value of `Tier.STAGING` lets your users pass any condition that passes for the staging environment tier. Those users fail any condition that only passes for other environment tiers. - use `setEnvironmentParameter` for custom tiers, for example `options.setEnvironmentParameter("tier", "test")` #### Runtime options Starting in `V4.43.0`, you can set a subset of options during initialization and later update them while the Statsig client is running. `StatsigRuntimeMutableOptions` (which `StatsigOptions` extends) defines these options. Call `Statsig.updateRuntimeOptions(runtimeMutableOptions: StatsigRuntimeMutableOptions)` or the corresponding method in `StatsigClient` to update the Statsig client with new values. - **loggingEnabled**: `Boolean`, default `true` - Setting this value to `false` prevents the Statsig client from sending logging events over the network or saving events to its on-disk cache. The Statsig client queues the 1000 most recent events in memory. You can log them to network (or cache them) by setting `loggingEnabled` to `true` later during that session. - Calling `Statsig.flush()` after setting `loggingEnabled` to `true` immediately clears the queue and minimizes loss of older log events. - This is useful for cases where users must grant permission before you log events, or any other case where you shouldn't enable logging. ## Shutting Statsig down To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, call `shutdown` when your app is closing: #### Java ```java Statsig.shutdown(); ``` #### Kotlin ```kotlin Statsig.shutdown() ``` ## Using persistent evaluations To ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, use persistent storage. The Android SDK supports a minimal implementation using the keepDeviceValues flag. Refer to the [Client Persistent Assignment Doc](https://docs.statsig.com/client/concepts/persistent_assignment#support-in-ios-and-android-sdks) for more information. ## Local overrides To locally override gates/configs/experiments/layers for testing, Statsig offers convenient methods for a quick local override. Unless you call the remove method, the SDK persists these session-to-session on the client's device. These overrides apply locally only and don't affect definitions in the console or elsewhere. ```kotlin // Overrides the given gate to the specified value overrideGate(gateName: String, value: Boolean) // Overrides the given config (dynamic config or experiment) to the provided value overrideConfig(configName: String, value: Map<String, Any>) // Removes any overrides associated with the provided gate/config/experiment name removeOverride(name: String) // Removes all overrides removeAllOverrides() // Returns the set of gate and config overrides currently in place on the client getAllOverrides(): StatsigOverrides class StatsigOverrides( @SerializedName("gates") val gates: MutableMap<String, Boolean>, @SerializedName("configs") val configs: MutableMap<String, Map<String, Any>> ) {} ``` ## Manual exposures > **Warning:** > > Manual logging is error-prone and can introduce issues like uneven exposures, which compromise experiment results. You can query your gates/experiments without triggering an exposure, and manually log the exposures later: #### Check Gate To check a gate without an exposure being logged: #### Kotlin ```kotlin val result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name") ``` #### Java ```java boolean result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name"); ``` Later, to manually log the gate exposure: #### Kotlin ```kotlin Statsig.manuallyLogGateExposure("a_gate_name") ``` #### Java ```java Statsig.manuallyLogGateExposure("a_gate_name"); ``` #### Get Config To get a dynamic config without an exposure being logged: #### Kotlin ```kotlin val config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name") ``` #### Java ```java DynamicConfig config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name"); ``` Later, to manually log the config exposure: #### Kotlin ```kotlin Statsig.manuallyLogConfigExposure("a_config_name") ``` #### Java ```java Statsig.manuallyLogConfigExposure("a_config_name"); ``` #### Get Experiment To get an experiment without an exposure being logged: #### Kotlin ```kotlin val experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name") ``` #### Java ```java DynamicConfig experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name"); ``` Later, to manually log the experiment exposure: #### Kotlin ```kotlin Statsig.manuallyLogExperimentExposure("an_experiment_name", false) ``` #### Java ```java Statsig.manuallyLogExperimentExposure("an_experiment_name", false); ``` #### Get Layer To get a layer parameter without an exposure being logged: #### Kotlin ```kotlin val layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name", false) val result = layer.getString("a_parameter_name", "fallback") ``` #### Java ```java Layer layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name"); String result = layer.getString("a_parameter_name", "fallback"); ``` Later, to manually log the layer parameter exposure: #### Kotlin ```kotlin Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false) ``` #### Java ```java Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name", false); ``` ## StableID Each client SDK has a stableID: a device-level identifier that the SDK generates the first time it initializes and stores locally for all future sessions. The stableID doesn't change unless you wipe storage or delete the app. The stableID enables device-level experiments and experiments where other user-identifiable information is unavailable, such as for logged-out users. ```kotlin // Retrieve the StableID Statsig.getStableID(); // Override the StableID before initializing, if you have something you'd prefer to use instead val opts = StatsigOptions(overrideStableID = "my_stable_id") Statsig.initialize(app, "client-xyx", options = opts) ``` ## Using multiple instances of the SDK The examples above use the SDK's singleton. The SDK also supports multiple instances. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly. > **Note:** > > You must use a different SDK key for each SDK instance you create. Various functionality of the Statsig client depends on the SDK key you use, so using the same key leads to collisions. All top-level static methods from the singleton are available as instance methods. To create an instance of the Statsig SDK: #### Java ```java StatsigClient client = new StatsigClient(); client.initializeAsync(application, sdkKey, user, callback, options); ``` #### Kotlin ```kotlin var client: StatsigClient = StatsigClient() client.initialize(application, sdkKey, user, options) ``` ## Initialize response The SDK provides a method to access the raw values used internally for gate, config, and layer evaluation. This is useful for debugging or advanced use cases where you need to access the underlying data. For example, you can use these values to bootstrap another SDK, such as the JavaScript SDK when opening an in-app browser. The `getInitializeResponseJson` method returns an `ExternalInitializeResponse` object that contains: 1. A JSON string representation of the initialize response values 2. Evaluation details that provide metadata about how the SDK obtained the values (network, cache, etc.) #### Java ```java // Get the raw values that the SDK is using internally to provide gate/config/layer results ExternalInitializeResponse response = Statsig.getInitializeResponseJson(); // Get the JSON string representation of the initialize response String jsonValues = response.getInitializeResponseJSON(); // Get the evaluation details EvaluationDetails details = response.getEvaluationDetails(); ``` #### Kotlin ```kotlin // Get the raw values that the SDK is using internally to provide gate/config/layer results val response = Statsig.getInitializeResponseJson() // Get the JSON string representation of the initialize response val jsonValues = response.getInitializeResponseJSON() // Get the evaluation details val details = response.getEvaluationDetails() ``` ================================================================================ # iOS/tvOS/macOS Client SDK URL: https://docs.statsig.com/client/iosClientSDK ================================================================================ # iOS/tvOS/macOS Client SDK - **Package:** `Statsig` ([cocoapods](https://cocoapods.org/pods/Statsig)) - **Latest version:** 1.62.9 ## Set up the SDK 1. **Install the SDK** To use the SDK in your project, add Statsig as a dependency. #### Swift Package Manager In your Xcode, select File > Swift Packages > Add Package Dependency and enter the URL https://github.com/statsig-io/statsig-kit.git. You can also include it directly in your project's Package.swift. Find the latest release version on the [GitHub page](https://github.com/statsig-io/statsig-kit/releases). ```swift //... dependencies: [ // see the latest version on https://github.com/statsig-io/statsig-kit/releases .package(url: "https://github.com/statsig-io/statsig-kit.git", .upToNextMinor("X.Y.Z")), ], //... targets: [ .target( name: "YOUR_TARGET", dependencies: ["Statsig"] ) ], //... ``` #### Cocoapods If you use CocoaPods, the pod name is 'Statsig'. Include the following line in your Podfile: ```ruby use_frameworks! target 'TargetName' do //... pod 'Statsig', '~> X.Y.Z' end ``` Find the latest versions by searching [cocoapods.org](https://cocoapods.org/) or on [Github](https://github.com/statsig-io/statsig-kit/releases). 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you want to target later in a gate or experiment. #### Swift ```swift Statsig.initialize( sdkKey: "my_client_sdk_key", user: StatsigUser(userID: "my_user_id"), options: StatsigOptions(environment: StatsigEnvironment(tier: .Staging))) { error in // Statsig has finished fetching the latest feature gate and experiment values for your user. // If you need the most recent values, you can get them now. // You can also check error.message and error.code for any debugging information. } ``` #### Objective C ```objective-c StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"my_user_id"]; [Statsig initializeWithSDKKey:@"my_client_sdk_key" user:user completion:^(StatsigClientError * error) { // Statsig has finished fetching the latest feature gate and experiment values for your user. // If you need the most recent values, you can get them now. // You can also check error.message and error.code for any debugging information. }]; ``` The SDK calls the completion block after the network request to fetch the latest feature gate and experiment values for your user. If you request any value before the SDK calls the completion block, you may get the cached value from the previous session or the default value. Wait for the completion block before requesting the latest value. ## Use the SDK ### Checking a Feature Flag/Gate Now that you've initialized your SDK, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. #### Swift ```swift if Statsig.checkGate("new_homepage_design") { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` #### Objective C ```objective-c if ([Statsig checkGateForName:@"new_homepage_design"]) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send different values (strings, numbers, and similar types) to your clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates but returns a full JSON object you can configure on the server and fetch typed parameters from. For example: #### Swift ```swift let config = Statsig.getConfig("awesome_product_details") // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. let itemName = config.getValue(forKey: "product_name", defaultValue: "Awesome Product v1") let price = config.getValue(forKey: "price", defaultValue: 10.0) let shouldDiscount = config.getValue(forKey: "discount", defaultValue: false) ``` #### Objective C ```objective-c DynamicConfig *config = [Statsig getConfigForName:@"awesome_product_details"]; // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. NSString *itemName = [config.getStringForKey:@"product_name" defaultValue:@"Awesome Product v1"]; double price = [config getDoubleForKey:@"price" defaultValue:10.0]; BOOL shouldDiscount = [config getBoolForKey:@"discount" defaultValue:false]; ``` ### Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. #### Swift ```swift // Values via getLayer let layer = Statsig.getLayer("user_promo_experiments") let promoTitle = layer.getValue(forKey: "title", defaultValue: "Welcome to Statsig!") let discount = layer.getValue(forKey: "discount", defaultValue: 0.1) // or, via getExperiment let titleExperiment = Statsig.getExperiment("new_user_promo_title") let priceExperiment = Statsig.getExperiment("new_user_promo_price") let promoTitle = titleExperiment.getValue(forKey: "title", defaultValue: "Welcome to Statsig") let discount = priceExperiment.getValue(forKey: "discount", defaultValue: 0.1) ... let price = msrp * (1 - discount); ``` #### Objective C ```objective-c DynamicConfig *expConfig = [Statsig getExperimentForName:@"new_user_promo"]; NSString *promoTitle = [expConfig.getStringForKey:@"title" defaultValue:@"Welcome to Statsig! Use discount code WELCOME10OFF for 10% off your first purchase!"]; double discount = [expConfig getDoubleForKey:@"discount" defaultValue:0.1]; double price = msrp * (1 - discount); ``` ### Logging an event After you set up a Feature Gate or an Experiment, you can track custom events to measure how your new features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and/or a metadata object to log together with the event: #### Swift ```swift Statsig.logEvent(withName: "purchase", value: 2.99, metadata: ["item_name": "remove_ads"]) ``` #### Objective C ```objective-c [Statsig logEvent:@"purchase" doubleValue:2.99 metadata:@{ @"item_name" : @"remove_ads" }]; ``` ## Parameter Stores Parameter Stores hold a set of parameters for your mobile app. You can remap these parameters dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers), so you can decouple your code from the configuration in Statsig. Go to [Parameter Stores](https://docs.statsig.com/client/concepts/parameter-stores) to learn more. ## Statsig User Provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. The `userID` field is usually required to provide a consistent experience for a given user. (Refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users.) Besides `userID`, StatsigUser also offers the `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion` top-level fields. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. After the user logs in or their attributes change, call `updateUserWithResult` with the updated `userID` and/or any other updated user attributes. #### Swift ```swift let user = StatsigUser( userID: "a-user-id", email: "user@example.com", ip: "192.168.1.1", userAgent: "Mozilla/5.0", country: "US", locale: "en_US", appVersion: "1.0.0", custom: [ "plan": "premium", "age": 25 ], customIDs: [ "stableID": "stable-id-123" ], privateAttributes: [ "email": "private@example.com" ] ) ``` #### Objective C ```objective-c StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"a-user-id"]; user.email = @"user@example.com"; user.ip = @"192.168.1.1"; user.userAgent = @"Mozilla/5.0"; user.country = @"US"; user.locale = @"en_US"; user.appVersion = @"1.0.0"; user.custom = @{ @"plan": @"premium", @"age": @25 }; user.customIDs = @{ @"stableID": @"stable-id-123" }; user.privateAttributes = @{ @"email": @"private@example.com" }; ``` ## Statsig Options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initTimeout | Double | No | — | Determines how long the Statsig client waits for the initial network request to respond before calling the completion block. The Statsig client returns either cached values (if any) or default values if you call checkGate/getConfig/getExperiment before the initial network request completes.If you always want to wait for the latest values the SDK fetches from Statsig server, set this to 0 to avoid timing out the network request. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableCurrentVCLogging | Bool | No | — | By default, any custom event your application logs with `Statsig.logEvent()` includes the current root View Controller. This allows Statsig to generate user journey funnels for your users. Set this parameter to `true` to disable this behavior. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | printHandler | ((String) -> Void)? | No | — | A handler for log messages from the SDK. If you don't provide one, the SDK prints logs to the console.The handler receives the message string the SDK would otherwise print to the console.Useful for redirecting logs to your own logging system, suppressing unnecessary console output, or debugging issues with the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | StatsigEnvironment is a class for setting environment variables that apply to all of your users in the same session. Statsig uses these variables for targeting purposes.For example, passing in a value of `StatsigEnvironment(tier: .Staging)` allows your users to pass any condition that passes for the staging environment tier, and fail any condition that only passes for other environment tiers. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | evaluationCallback | EvaluationCallbackData | No | — | EvaluationCallback provides a callback when an evaluation occurs against one of your configurations (gate, dynamic config, experiment, layer, and parameter stores). This is useful when you want to trigger specific actions or log evaluations based on the results you receive from Statsig.To use the EvaluationCallback, provide a callback function during SDK initialization through StatsigOptions. The SDK invokes the callback every time an evaluation occurs for feature gates, dynamic configs, experiments, layers, or parameter stores.The EvaluationCallbackData enum defines the different types of data that the evaluationCallback returns when the Statsig iOS SDK evaluates feature gates, dynamic configs, experiments, layers, or parameter stores.Here's the structure of the enum:```swift public enum EvaluationCallbackData { case gate (FeatureGate) case config (DynamicConfig) case experiment (DynamicConfig) case layer (Layer) case parameterStore (ParameterStore) } ```Here's an example of how to set up an evaluation callback:```swift func callback(data: StatsigOptions.EvaluationCallbackData) { switch data { case .gate(let gate): // Handle gate evaluation case .config(let config): // Handle dynamic config evaluation case .experiment(let experiment): // Handle experiment evaluation case .layer(let layer): // Handle layer evaluation case .parameterStore(let paramStore): // Handle parameter store evaluation } } let opts = StatsigOptions(evaluationCallback: callback) Statsig.initialize(sdkKey: "client-key", options: opts) ``` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | storageProvider | StorageProvider | No | — | Lets you implement a custom caching strategy by passing an object that conforms to the `StorageProvider` protocol.Default cache key: `com.statsig.cache````swift @objc public protocol StorageProvider { @objc func read(_ key: String) -> Data? @objc func write(_ value: Data, _ key: String) @objc func remove(_ key: String) } ``` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideStableID | String | No | — | Overrides the auto generated StableID the SDK sets for the device. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableCacheByFile | Bool | No | — | Use file caching instead of UserDefaults. Useful if you reach size limits with UserDefaults (ie tvOS). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingEnabled | Bool | No | — | Controls whether the SDK sends events over the network. Useful when you need user consent before sending events. The iOS SDK stores up to 1MB of unsent request payloads. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeValues | [String: Any] | No | — | Provide a Dictionary representing the "initialize response" required to synchronously initialize the SDK. Obtain this value from a Statsig server SDK and use it to [Bootstrap](https://docs.statsig.com/client/concepts/initialize/#2-bootstrap-initialization) the SDK when initializing. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableDiagnostics | Bool | No | — | Prevent the SDK from sending useful debug information to Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableHashing | Bool | No | — | When you disable it, the SDK doesn't hash gate/config/experiment names, and they remain readable as plain text.> **Info:** > > This requires special authorization from Statsig. Contact the support team or your sales contact, or ask in the [Slack community](https://statsig.com/slack), if you want to enable this. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | shutdownOnBackground | Bool | No | — | The SDK automatically shuts down when an app enters the background. If you need to use the SDK while your app is in the background, set this to `false`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializationURL | URL | No | — | Override the URL the SDK uses to initialize. Learn more at /custom\_proxy```swift StatsigOptions(initializationURL: URL(string: "https://example.com/setup")) ``` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingURL | URL | No | — | Override the URL the SDK uses to log events. Learn more at /custom\_proxy```swift StatsigOptions(eventLoggingURL: URL(string: "https://example.com/info")) ``` | ## StableID Each client SDK has the concept of stableID: a device-level identifier that the SDK generates the first time it initializes and stores locally for all future sessions. Unless you clear storage (or delete the app), the stableID doesn't change. This allows Statsig to run device-level experiments and experiments when other user-identifiable information is unavailable (logged-out users). #### Swift ```swift let options = StatsigOptions(overrideStableID: "my_stable_id") Statsig.initialize(sdkKey: "client-xyz", options: options) ``` #### Objective C ```objective-c StatsigOptions *options = [[StatsigOptions alloc] init]; options.overrideStableID = @"my_stable_id"; [Statsig initializeWithSDKKey:@"client-xyz" user:nil options:options completion:nil]; ``` ## Manual exposures > **Warning:** > > Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results. You can query your gates/experiments without triggering an exposure and manually log the exposures later. #### Feature Gates #### Swift ```swift // Swift - Check without logging exposure let result = Statsig.checkGateWithExposureLoggingDisabled("a_gate_name") // ... // Later, when ready to log the exposure Statsig.manuallyLogGateExposure("a_gate_name") ``` #### Objective-C ```objc // Objective C - Check without logging exposure bool result = [Statsig checkGateWithExposureLoggingDisabled:@"a_gate_name"]; // ... // Later, when ready to log the exposure [Statsig manuallyLogGateExposure:@"a_gate_name"]; ``` #### Dynamic Configs #### Swift ```swift // Swift - Get config without logging exposure let config = Statsig.getConfigWithExposureLoggingDisabled("a_config_name") // ... // Later, when ready to log the exposure Statsig.manuallyLogConfigExposure("a_config_name") ``` #### Objective-C ```objc // Objective C - Get config without logging exposure DynamicConfig *config = [Statsig getConfigWithExposureLoggingDisabled:@"a_config_name"]; // ... // Later, when ready to log the exposure [Statsig manuallyLogConfigExposure:@"a_config_name"]; ``` #### Experiments #### Swift ```swift // Swift - Get experiment without logging exposure let experiment = Statsig.getExperimentWithExposureLoggingDisabled("an_experiment_name") // ... // Later, when ready to log the exposure Statsig.manuallyLogExperimentExposure("an_experiment_name") ``` #### Objective-C ```objc // Objective C - Get experiment without logging exposure DynamicConfig *experiment = [Statsig getExperimentWithExposureLoggingDisabled:@"an_experiment_name"]; // ... // Later, when ready to log the exposure [Statsig manuallyLogExperimentExposure:@"an_experiment_name"]; ``` #### Layers #### Swift ```swift // Swift - Get layer without logging exposure let layer = Statsig.getLayerWithExposureLoggingDisabled("a_layer_name") let result = layer.getValue(forKey: "a_parameter_name", defaultValue: "fallback") // ... // Later, when ready to log the exposure Statsig.manuallyLogLayerParameterExposure("a_layer_name", "a_parameter_name") ``` #### Objective-C ```objc // Objective C - Get layer without logging exposure Layer *layer = [Statsig getLayerWithExposureLoggingDisabled:@"a_layer_name"]; NSString *result = [layer getStringForKey:@"a_parameter_name" defaultValue:@"fallback"]; // ... // Later, when ready to log the exposure [Statsig manuallyLogLayerParameterExposure:@"a_layer_name" parameterName:@"a_parameter_name"]; ``` ## Local overrides To locally override gates/configs/experiments/layers for testing, use the local override methods. Unless you call the remove method, these overrides persist session-to-session on the client's device. These overrides apply locally only and don't affect definitions in the console or elsewhere. ## Shutting Statsig down To save users' data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, call shutdown when your app is closing. #### Swift ```swift Statsig.shutdown() ``` #### Objective C ```objective-c [Statsig shutdown]; ``` ## Using multiple instances of the SDK The examples above use the SDK's singleton. Statsig also supports creating multiple instances of the SDK. The `Statsig` singleton wraps a single instance of the SDK (typically called a `StatsigClient`) that you can instantiate directly. > **Note:** > > Use a different SDK key for each SDK instance. The Statsig client keys various functionality on the SDK key you use. Using the same key causes collisions. All top-level static methods from the singleton carry over as instance methods. To create an instance of the Statsig SDK: #### Swift ```swift let client = StatsigClient( sdkKey: "client-xyz", user: StatsigUser(userID: "user-1"), options: StatsigOptions(environment: StatsigEnvironment(tier: .Production)) ) { error in // ready } let gateOn = client.checkGate("some_gate") ``` #### Objective C ```objective-c StatsigOptions *options = [[StatsigOptions alloc] initWithEnvironment:[[StatsigEnvironment alloc] initWithTier:StatsigEnvironmentTierProduction]]; StatsigUser *user = [[StatsigUser alloc] initWithUserID:@"user-1"]; StatsigClient *client = [[StatsigClient alloc] initWithSdkKey:@"client-xyz" user:user options:options completion:^(StatsigClientError * error) { // ready }]; BOOL gateOn = [client checkGate:@"some_gate"]; ``` > **Warning:** > > Use a unique SDK key per instance to avoid collisions. ## Initialize response The SDK provides a method to access the raw values it uses internally for gate, config, and layer values. This is useful for debugging or for advanced use cases where you need to access the underlying data. For example, you can use these values to bootstrap another SDK, such as the JavaScript SDK when you open an in-app browser. The `getInitializeResponseJson` method returns an `ExternalInitializeResponse` object that contains: 1. A JSON string representation of the initialize response values 2. Evaluation details that provide metadata about how the SDK obtained the values (network, cache, etc.) #### Swift ```swift let response = Statsig.getInitializeResponseJson() if let values = response.values { print(values) } let details = response.evaluationDetails ``` #### Objective C ```objective-c ExternalInitializeResponse *response = [Statsig getInitializeResponseJson]; NSString *values = response.values; if (values) { NSLog(@"%@", values); } EvaluationDetails *details = response.evaluationDetails; ``` ## Listening for changes In v1.14.0+, you can listen for SDK changes using `StatsigListening`. #### Swift ```swift class MyViewController: UIViewController, StatsigListening { override func viewDidLoad() { super.viewDidLoad() if Statsig.isInitialized() { render() } else { Statsig.addListener(self) renderLoading() } } private func render() { let showNewUI = Statsig.checkGate("new_ui_enabled") if showNewUI { // Render the new UI } else { // Render the old UI } } private func renderLoading() { /* loading UI */ } private func renderError(error: StatsigClientError) { /* error UI */ } // StatsigListening func onInitializedWithResult(_ error: StatsigClientError?) { if let error = error { renderError(error) return } render() } func onUserUpdatedWithResult(_ error: StatsigClientError?) { /* optional rerender */ } } ``` ================================================================================ # C++ Client SDK URL: https://docs.statsig.com/client/CPP ================================================================================ # C++ Client SDK - **Repository:** [cpp-client-sdk](https://github.com/statsig-io/cpp-client-sdk) ## Set up the SDK 1. **Install the SDK** #### Downloaded From GitHub ```cpp add_subdirectory(path/to/downloaded/statsig_sdk) target_link_libraries(${PROJECT_NAME} StatsigClientSDK) ``` #### FetchContent ```cpp include(FetchContent) FetchContent_Declare(statsig GIT_REPOSITORY https://github.com/statsig-io/cpp-client-sdk.git GIT_TAG main ) FetchContent_MakeAvailable(statsig) target_link_libraries(${PROJECT_NAME} StatsigClientSDK) ``` 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. ```cpp #include <statsig/statsig.h> using namespace statsig; StatsigUser user; user.user_id = "a-user"; user.custom_ids = { {"employeeID", "an-employee"} }; // Create your own instance StatsigClient client; // Initialize synchronously using cached values from the previous session client.InitializeSync("client-{YOUR_CLIENT_SDK_KEY}", user); // or, Initialize asynchronously from network client.InitializeAsync( "client-{YOUR_CLIENT_SDK_KEY}", [](StatsigResultCode result) { // completion callback }, user ); ``` **Synchronous** initialization uses cache (if available) and returns immediately. The SDK then fetches data for subsequent sessions in the background. **Asynchronous** initialization provides a callback, allowing you to wait for the SDK to fetch the most current data. For convenience, there is also a singleton instance accessible through `StatsigClient::Shared()`. ```cpp // Initialize synchronously using cached values from the previous session StatsigClient::Shared().InitializeSync("client-{YOUR_CLIENT_SDK_KEY}", user); // or, Initialize asynchronously from network StatsigClient::Shared().InitializeAsync( "client-{YOUR_CLIENT_SDK_KEY}", [](StatsigResultCode result) { // completion callback }, user ); ``` **Optional** - Configuration through StatsigOptions To adjust how the SDK works, pass a [StatsigOptions](#statsig-options) struct during initialization. ```cpp StatsigOptions options; options.environment = StatsigEnvironment{"staging"}; client.InitializeSync(..., options); // or client.InitializeAsync(..., options); ``` ## Use the SDK ### Checking a Feature Flag/Gate After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. ```cpp if (client.CheckGate("a_gate")) { // show new feature } // or, use the shared instance if (StatsigClient::Shared().CheckGate("a_gate")) { // show new feature } ``` ### Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example: ```cpp DynamicConfig config = client.GetDynamicConfig("a_config"); // or, use the shared instance DynamicConfig config = StatsigClient::Shared().GetDynamicConfig("a_config"); // then access the params std::cout << config.GetValue()["a_string_param"] << std::endl; ``` > **Info:** > > `DynamicConfig.GetValue` returns `JsonObj`, which is an unordered map of string to `nlohmann/json`. Refer to https://github.com/nlohmann/json ### Getting a Layer/Experiment **Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```cpp // Values via getLayer Layer layer = StatsigClient::Shared().GetLayer("name"); std::string promoTitle = layer.GetValue("title").get<std::string>(); double discount = layer.GetValue("discount").get<double>(); // or, via getExperiment Experiment titleExperiment = StatsigClient::Shared().GetExperiment("new_user_promo_title"); Experiment priceExperiment = StatsigClient::Shared().GetExperiment("new_user_promo_price"); std::string promoTitle = titleExperiment.GetValue()["title"].get<std::string>(); double discount = priceExperiment.GetValue()["discount"].get<double>(); ``` > **Info:** > > `Layer.GetValue` and `Experiment.GetValue` return `JsonObj`, which are unordered maps of string to `nlohmann/json`. Refer to https://github.com/nlohmann/json ### Logging an Event After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event: ```cpp std::unordered_map<std::string, std::string> metadata{ { "price", "9.99" }, { "item_name", "some_great_product" } }; StatsigEvent event("add_to_cart", "SKU_12345", metadata); StatsigClient::Shared().LogEvent(event); // Then, at some point later, you need to "flush" the events StatsigClient::Shared().Flush(); ``` ## Statsig User You need to provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. The `userID` field is required in most cases to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) for how to run experiments for logged-out users). In addition to `userID`, StatsigUser offers the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them. ```cpp StatsigUser user; user.user_id = "a-user"; user.email = "developer@statsig.com"; user.custom_ids = { {"employeeID", "an-employee"} }; ``` ### Private attributes To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from logs before sending them to the server. For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ### Updating users When user data changes, call an UpdateUser function to make Statsig aware of the new user. ```cpp client.UpdateUserSync(user); // or, use the shared instance StatsigClient::Shared().UpdateUserSync(user); ``` To ensure you have the latest values during an update (for example, when transitioning from logged out to logged in), use the asynchronous update function. ```cpp {client or StatsigClient::Shared()}.UpdateUserAsync( user, [](StatsigResultCode result) { if (result == StatsigResultCode::Ok) { // do something now that the latest values have been fetched } else { // error state } } ); ``` Asynchronous vs Synchronous behaviors are the same as the Initialize functions. ## Statsig Options `StatsigClient::Initialize`, in addition to `sdk_key` and `user`, takes an optional `options` parameter to customize the StatsigClient. The following list shows the current options: | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | std::string | No | — | The API to use for all SDK network requests. You don't need to override this unless you have another API that implements the Statsig API endpoints. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | providers | EvaluationsDataProvider | No | — | Array of EvaluationsDataProvider that customizes the initialization and update behavior. | ## Shutting Statsig down To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, call `Shutdown` when your app is closing: ```cpp client.Shutdown(); // or, use the shared instance StatsigClient::Shared().Shutdown(); ``` #### How do I run experiments for logged-out users Go to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ================================================================================ # Dart Client SDK URL: https://docs.statsig.com/client/Dart ================================================================================ # Dart Client SDK - **Package:** `statsig` ([pubdev](https://pub.dev/packages/statsig)) - **Latest version:** 1.3.0 - **Repository:** [dart-sdk](https://github.com/statsig-io/dart-sdk) ## Set up the SDK 1. **Install the SDK** With Dart: ```bash dart pub add statsig ``` With Flutter: ```bash flutter pub add statsig ``` > **Note:** > > If you are using **Flutter**, be sure to add Statsig as part of the [app lifecycle](#flutter-lifecycle-hooks) to avoid losing events. 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. ```dart import 'package:statsig/statsig.dart'; await Statsig.initialize('client-sdk-key', StatsigUser(userId: "a-user-id")); ``` ## Use the SDK ### Checking a Feature Flag/Gate After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. ```dart if (Statsig.checkGate("new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example: ```dart var config = Statsig.getConfig("awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. var itemName = config.get("product_name", "Awesome Product v1"); var price = config.get("price", 10.0); var shouldDiscount = config.get("discount", false); ``` ### Getting a Layer/Experiment **Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```dart // Values via getLayer var layer = Statsig.getLayer("user_promo_experiments"); var promoTitle = layer.getString("title", "Welcome to Statsig!"); var discount = layer.getDouble("discount", 0.1); // or, via getExperiment var titleExperiment = Statsig.getExperiment("new_user_promo_title"); var priceExperiment = Statsig.getExperiment("new_user_promo_price"); var promoTitle = titleExperiment.get("title", "Welcome to Statsig!"); var discount = priceExperiment.get("discount", 0.1); ``` ### Logging an Event After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event: ```dart // Provide a doubleValue argument for number values Statsig.logEvent("purchase", doubleValue: 2.99, metadata: {"item_name": "remove_ads"}); // or provide a stringValue argument for string values Statsig.logEvent("login", stringValue: "a.user@mail.com"); ``` ## Parameter Stores Parameter Stores hold a set of parameters for your mobile app. These parameters can be remapped dynamically from a static value to a Statsig entity (Feature Gates, Experiments, and Layers). Remapping lets you decouple your code from the configuration in Statsig. Refer to [Param Stores](https://docs.statsig.com/client/concepts/parameter-stores) for more information. ```dart var homepageStore = Statsig.getParameterStore("homepage"); var title = homepageStore.get("title", "Welcome"); var shouldShowUpsell = homepageStore.get("upsell_upgrade_now", false); ``` ## Statsig User You need to provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. The `userID` field is required in most cases to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) for how to run experiments for logged-out users). In addition to `userID`, StatsigUser offers the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: ```dart await Statsig.updateUser(StatsigUser("a_new_user")); ``` ### Private attributes To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from logs before sending them to the server. For example, suppose you have feature gates that should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initTimeout | int | No | — | Sets how long (in seconds) the Statsig client waits for the initial network request to respond before calling the completion block. If you call `checkGate`, `getConfig`, or `getExperiment` before the initial network request completes, the Statsig client returns either cached values (if any) or default values.If you always want to wait for the latest values fetched from the Statsig server, set this to `0` so the network request doesn't time out. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | The endpoint to use for all SDK network requests. Don't override this unless you have another API that implements the Statsig API endpoints. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | string | No | — | The environment tier to evaluate rules for the current user. Default is empty, which is the same as "production." On non-production tiers, events don't appear in downstream pulse results. | ## Lifecycle and advanced usage ## Shutting Statsig down To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, call `shutdown` when your app is closing: ```dart await Statsig.shutdown(); ``` ## Flutter lifecycle hooks The operating system can close mobile apps when they're no longer in the foreground. To ensure Statsig logs all events before the operating system closes the app, add Statsig to the app lifecycle events. This flushes all pending events when it detects an app state change. Something like the following: ```dart // An example App Lifecycle Observer class StatsigLifecycleObserver extends WidgetsBindingObserver { @override void didChangeAppLifecycleState(AppLifecycleState state) async { switch (state) { case AppLifecycleState.resumed: await Statsig.initialize('client-sdk-key'); break; case AppLifecycleState.paused: await Statsig.shutdown(); break; } } } ``` Then in your app code, add this observer to the WidgetsBinding instance. ```dart @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(StatsigLifecycleObserver()); } ``` ## FAQs ### How do I run experiments for logged out users Go to the guide on [device level experiments](https://docs.statsig.com/client/concepts/persistent_assignment). ================================================================================ # .NET Client SDK URL: https://docs.statsig.com/client/DotNet ================================================================================ # .NET Client SDK - **Repository:** [dotnet-sdk](https://github.com/statsig-io/dotnet-sdk) ## Set up the SDK 1. **Install the SDK** [Nuget](https://www.nuget.org/packages/Statsig/) hosts the package. Install it from your Visual Studio's Nuget package manager, or through the NuGet CLI: ```shell nuget install Statsig ``` 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. ```csharp using Statsig; using Statsig.Client; await StatsigClient.Initialize( "client-sdk-key", new StatsigUser { UserID = "some_user_id", Email = "user@email.com" }, new StatsigOptions(new StatsigEnvironment(EnvironmentTier.Development)) // optional, use when needed to customize certain behaviors ); ``` ## Use the SDK ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. ```csharp if (StatsigClient.CheckGate("new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server. You can then fetch typed parameters from it. For example: ```csharp DynamicConfig config = StatsigClient.GetConfig("awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. string itemName = config.Get<string>("product_name", "Awesome Product v1"); double price = config.Get<double>("price", 10.0); bool shouldDiscount = config.Get<bool>("discount", false); ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```csharp // Values via getLayer Layer layer = StatsigClient.GetLayer("user_promo_experiments"); var promoTitle = layer.Get("title", "Welcome to Statsig!"); var discount = layer.Get("discount", 0.1); // or, via getExperiment DynamicConfig titleExperiment = StatsigClient.GetExperiment("new_user_promo_title"); DynamicConfig priceExperiment = StatsigClient.GetExperiment("new_user_promo_price"); var promoTitle = titleExperiment.Get("title", "Welcome to Statsig!"); var discount = priceExperiment.Get("discount", 0.1); ... double price = msrp * (1 - discount); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: ```csharp StatsigClient.LogEvent( "add_to_cart", "SKU_12345", new Dictionary<string, string>() { { "price", "9.99" }, { "item_name", "diet_coke_48_pack" } } ); ``` ## Statsig user You need to provide a StatsigUser object to check/get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. Most of the time, you need the `userID` field to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users). Besides `userID`, Statsig also supports `email`, `ip`, `userAgent`, `country`, `locale` and `appVersion` as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the `custom` field and create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: ```csharp // if you want to update the existing user, or change to a different user, call updateUser await StatsigClient.UpdateUser( new StatsigUser { UserID = "new_user_id", Email = "new_user@email.com" }, ); ``` ### Private attributes To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses attributes set in `privateAttributes` only for evaluation and targeting, then removes them from any logs before sending them to the server. For example, suppose you have feature gates that pass only for users with emails ending in "@statsig.com", but you don't want to log your users' email addresses to Statsig. In that case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig options `Initialize()` takes an optional parameter `options` in addition to `sdkKey` and `user` that you can provide to customize the Statsig client. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | Set environment variables that apply to all users in the session for targeting purposes. Commonly used to set the environment tier, for example `new StatsigEnvironment(EnvironmentTier.Staging)`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | ClientRequestTimeoutMs | int | No | — | Maximum milliseconds to wait for `/initialize` before proceeding with cached/default values. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | PersistentStorageFolder | string | No | — | Directory path for persistent storage of cached values and logs. | ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because of this periodic flushing, the SDK may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```csharp StatsigClient.Shutdown(); ``` ## FAQs #### How do I run experiments for logged out users Refer to [Device-level experiments](https://docs.statsig.com/sdks/user#device-level-experiments). ================================================================================ # Expo Client SDK URL: https://docs.statsig.com/client/Expo ================================================================================ # Expo Client SDK - **Package:** `@statsig/expo-bindings` ([npm](https://www.npmjs.com/package/@statsig/expo-bindings)) - **Latest version:** 3.33.7 - **Package size:** 2.0 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK 1. **Install the SDK** ```shell npx expo install @statsig/expo-bindings ``` ### Peer dependencies The `@statsig/expo-bindings` package has peer dependencies which you may also need to install if they aren't already in your project. ```shell npx expo install expo-device expo-application @react-native-async-storage/async-storage ``` 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. The setup for an Expo environment is very similar to a plain [React environment](https://docs.statsig.com/client/React). The only difference is that you need to use the Expo specific `StatsigProviderExpo`. `StatsigProviderExpo` automatically switches the storage layer the SDK uses, using [AsyncStorage](https://github.com/react-native-async-storage) instead of LocalStorage (which isn't available in RN environments). ```tsx import { StatsigProviderExpo, useFeatureGate } from "@statsig/expo-bindings"; function Content() { const gate = useFeatureGate("a_gate"); return <Text>Reason: {gate.details.reason}</Text>; // Reason: Network or NetworkNotModified } function App() { return ( <StatsigProviderExpo sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} options={{ environment: { tier: "development" } }} // (Optional) loadingComponent={<Text>Loading...</Text>} > <Content /> </StatsigProviderExpo> ); } ``` ## Use the SDK You can get an instance of the StatsigClient to check gates, experiments, dynamic configs, layers, and log events. ```jsx import { useStatsigClient } from "@statsig/expo-bindings"; const { client } = useStatsigClient(); ``` The sections below describe the methods you can call on the client. ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. You can evaluate a gate by getting the client with the `useStatsigClient` hook, and then calling `checkGate` ```tsx const { client } = useStatsigClient(); return ( <div>Gate is {client.checkGate('check_user') ? 'passing' : 'failing'}.</div> ); ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: You can get a DynamicConfig value by getting the client with the `useStatsigClient` hook, and then calling `getConfig` ```tsx const { client } = useStatsigClient(); const config = client.getConfig('app_properties'); return ( <div>{config.get('title', 'Default Title')}</div> ); ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. You can access the experiment variant and parameters for the user by getting the client with the `useStatsigClient` hook, and then calling `getExperiment`. ```tsx const { client } = useStatsigClient(); const experiment = client.getExperiment('headline_test'); return ( <div>Headline Parameter: {experiment.get('headline', 'Default')}.</div> ); ``` You can access layers and layer parameters for the user by getting the client with the `useStatsigClient` hook, and then calling `getLayer`. ```tsx const { client } = useStatsigClient(); const layer = client.getLayer('homepage_layer'); return ( <div>Headline Parameter: {layer.get('hero_text', 'Welcome')}.</div> ); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event. Get the client with the `useStatsigClient` hook, then call `logEvent`: ```tsx const { client } = useStatsigClient(); return <button onClick={() => client.logEvent("button_click")}>Click Me</button> ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```tsx import { Button } from 'react-native'; import { useStatsigClient } from '@statsig/expo-bindings'; const { client } = useStatsigClient(); return ( <button onClick={async () => { await client.flush(); }} > Flush Events </button> ); ``` ## Loading state Depending on your setup, you may want to wait for the latest values before checking a gate or experiment. If you're using `StatsigProviderExpo`, pass in a `loadingComponent` prop to display a loading state while the SDK is initializing. If you're using the `useClientAsyncInitExpo` hook, check the `isLoading` prop to determine if the SDK is still loading. #### StatsigProviderExpo ```tsx export function App() { const loadingComponent = <div>Loading...</div>; return ( <StatsigProviderExpo ... loadingComponent={loadingComponent} // <- Pass in the loading component > <YourComponent /> </StatsigProviderExpo> ); } ``` #### useClientAsyncInitExpo ```tsx export function App() { const { client, isLoading } = useClientAsyncInitExpo(...); if (isLoading) { return <div>Loading...</div>; } return ( <StatsigProviderExpo client={client}> <YourComponent /> </StatsigProviderExpo> ); } ``` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```tsx import { useEffect } from 'react'; import { useStatsigClient } from '@statsig/expo-bindings'; const { client } = useStatsigClient(); useEffect(() => { return () => { void client.shutdown(); }; }, [client]); ``` ## Advanced ### Expo without React In some scenarios, you may need to use the `StatsigClient` outside the React component tree. For example, in background tasks or notification handlers, use the Expo-specific `StatsigClientExpo`. ```tsx import { StatsigClientExpo } from '@statsig/expo-bindings'; const myClient = new StatsigClientExpo( YOUR_CLIENT_KEY, { userID: "a-user" } ); await myClient.initializeAsync(); if (myClient.checkGate("my_gate")) { // do something cool } ``` ### Synchronous storage with MMKV If you're using [MMKV](https://github.com/mrousavy/react-native-mmkv) in your project and prefer it over the default ([AsyncStorage](https://github.com/react-native-async-storage)), provide your own `StorageProvider` through `StatsigOptions`. ```tsx import { MMKV } from "react-native-mmkv"; import { StorageProvider } from "@statsig/client-core"; import { StatsigProviderExpo } from "@statsig/expo-bindings"; function App() { const [storageProvider] = useState<StorageProvider>(() => { const mmkv = new MMKV(); return { isReady: () => true, isReadyResolver: () => null, getProviderName: () => "MMKV", getAllKeys: () => mmkv.getAllKeys(), getItem: (key: string) => mmkv.getString(key) ?? null, setItem: (key: string, value: string) => mmkv.set(key, value), removeItem: (key: string) => mmkv.delete(key), }; }); return ( <StatsigProviderExpo sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} options={{ storageProvider, // <- Passed into StatsigOptions }} > <Text>...</Text> </StatsigProviderExpo> ); } ``` ## Debugging ### Network issues Some users have reported `ERROR: A networking error occured during POST request` messages when first initializing Statsig. Statsig resolved this issue in SDK versions after 3.1.0. Upgrade your SDK to resolve the error. If the error persists, reach out through [Slack](https://statsig.com/slack). ================================================================================ # React Native Client SDK URL: https://docs.statsig.com/client/ReactNative ================================================================================ # React Native Client SDK - **Package:** `@statsig/react-native-bindings` ([npm](https://www.npmjs.com/package/@statsig/react-native-bindings)) - **Latest version:** 3.33.7 - **Package size:** 2.0 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK 1. **Install the SDK** ## Installation Statsig uses a multi-package strategy. Install both the Statsig client and the React Native specific bindings. #### NPM ```shell npm install @statsig/react-native-bindings ``` #### Yarn ```shell yarn add @statsig/react-native-bindings ``` ### Peer dependencies The `@statsig/react-native-bindings` package has peer dependencies which you may also need to install if they aren't already in your project. #### NPM ```shell npm install react-native-device-info @react-native-async-storage/async-storage ``` #### Yarn ```shell yarn add react-native-device-info @react-native-async-storage/async-storage ``` 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. ## React Native + React specific setup The setup for a ReactNative environment is very similar to a plain [React environment](https://docs.statsig.com/client/React). The only difference is that you need to use the ReactNative specific `StatsigProviderRN`. `StatsigProviderRN` automatically switches the SDK's storage layer, using [AsyncStorage](https://github.com/react-native-async-storage) instead of LocalStorage (which isn't available in RN environments). ```tsx import { StatsigProviderRN, useFeatureGate, } from "@statsig/react-native-bindings"; function Content() { const gate = useFeatureGate("a_gate"); // Reason: Network or NetworkNotModified return ( <View> <Text>Value: {gate.value ? "Pass" : "Fail"}</Text> <Text>Reason: {gate.details.reason}</Text> </View> ); } function App() { return ( <StatsigProviderRN sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} loadingComponent={<Text>Loading...</Text>} > <Content /> </StatsigProviderRN> ); } ``` ## Use the SDK Get an instance of the StatsigClient to check gates, experiments, dynamic configs, layers, and log events. ```jsx import { useStatsigClient } from "@statsig/react-native-bindings"; const { client } = useStatsigClient(); ``` The sections below list the available methods. ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. You can evaluate a gate by getting the client with the `useStatsigClient` hook, and then calling `checkGate` ```tsx const { client } = useStatsigClient(); return ( <div>Gate is {client.checkGate('check_user') ? 'passing' : 'failing'}.</div> ); ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: You can get a DynamicConfig value by getting the client with the `useStatsigClient` hook, and then calling `getConfig` ```tsx const { client } = useStatsigClient(); const config = client.getConfig('app_properties'); return ( <div>{config.get('title', 'Default Title')}</div> ); ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. You can access the experiment variant and parameters for the user by getting the client with the `useStatsigClient` hook, and then calling `getExperiment`. ```tsx const { client } = useStatsigClient(); const experiment = client.getExperiment('headline_test'); return ( <div>Headline Parameter: {experiment.get('headline', 'Default')}.</div> ); ``` You can access layers and layer parameters for the user by getting the client with the `useStatsigClient` hook, and then calling `getLayer`. ```tsx const { client } = useStatsigClient(); const layer = client.getLayer('homepage_layer'); return ( <div>Headline Parameter: {layer.get('hero_text', 'Welcome')}.</div> ); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or different experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event. Get the client with the `useStatsigClient` hook, then call `logEvent`: ```tsx const { client } = useStatsigClient(); return <button onClick={() => client.logEvent("button_click")}>Click Me</button> ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```tsx import { Button } from 'react-native'; import { useStatsigClient } from '@statsig/react-native-bindings'; const { client } = useStatsigClient(); return ( <Button title="Flush Events" onPress={async () => { await client.flush(); }} /> ); ``` ## Loading state Depending on your setup, you may want to wait for the latest values before checking a gate or experiment. If you're using `StatsigProviderRN`, pass in a `loadingComponent` prop to display a loading state while the SDK initializes. If you're using the `useClientAsyncInitRN` hook, check the `isLoading` prop to determine if the SDK is still loading. #### StatsigProviderRN ```tsx export function App() { const loadingComponent = <div>Loading...</div>; return ( <StatsigProviderRN ... loadingComponent={loadingComponent} // <- Pass in the loading component > <YourComponent /> </StatsigProviderRN> ); } ``` #### useClientAsyncInitRN ```tsx export function App() { const { client, isLoading } = useClientAsyncInitRN(...); if (isLoading) { return <div>Loading...</div>; } return ( <StatsigProviderRN client={client}> <YourComponent /> </StatsigProviderRN> ); } ``` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```tsx import { useEffect } from 'react'; import { useStatsigClient } from '@statsig/react-native-bindings'; const { client } = useStatsigClient(); useEffect(() => { return () => { void client.shutdown(); }; }, [client]); ``` ## Advanced ### StatsigClient outside the component tree In some scenarios, you may need to use the `StatsigClient` outside the React component tree. For example, in background tasks or notification handlers, use the RN-specific `StatsigClientRN`. ```tsx import { StatsigClientRN } from '@statsig/react-native-bindings'; const myClient = new StatsigClientRN( YOUR_CLIENT_KEY, { userID: "a-user" } ); await myClient.initializeAsync(); if (myClient.checkGate("my_gate")) { // do something cool } ``` To access the StatsigClient instance that the StatsigProvider creates, from outside the component tree, use the `StatsigClientRN.instance()` method. This returns the first created StatsigClient instance. If you have multiple instances, pass in the SDK key to get a specific instance. ```tsx // Inside the component tree function App() { return <StatsigProviderRN sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }}> <Text>...</Text> </StatsigProviderRN> } // Outside the component tree const client = StatsigClientRN.instance(); // get the first created instance const client = StatsigClientRN.instance(YOUR_CLIENT_KEY); // get a specific instance by SDK key ``` ### Synchronous storage with MMKV Because LocalStorage is unavailable in React Native environments, the SDK prefetches all Statsig cache entries during initialization by default. If you're using MMKV in your project and prefer it over the default (AsyncStorage), provide your own `StorageProvider` through `StatsigOptions`. ```tsx import { MMKV } from "react-native-mmkv"; import { StorageProvider } from "@statsig/client-core"; import { StatsigProviderRN } from '@statsig/react-native-bindings'; function App() { const [storageProvider] = useState<StorageProvider>(() => { const mmkv = new MMKV(); return { isReady: () => true, isReadyResolver: () => null, getProviderName: () => "MMKV", getAllKeys: () => mmkv.getAllKeys(), getItem: (key: string) => mmkv.getString(key) ?? null, setItem: (key: string, value: string) => mmkv.set(key, value), removeItem: (key: string) => mmkv.delete(key), }; }); return ( <StatsigProviderRN sdkKey={YOUR_CLIENT_KEY} user={{ userID: "a-user" }} options={{ storageProvider, // <- Passed into StatsigOptions }} > <Text>...</Text> </StatsigProviderRN> ); } ``` ================================================================================ # Statsig in Angular URL: https://docs.statsig.com/client/Angular ================================================================================ # Statsig in Angular - **Package:** `@statsig/angular-bindings` ([npm](https://www.npmjs.com/package/@statsig/angular-bindings)) - **Latest version:** 3.33.7 - **Package size:** 2.0 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) ## Set up the SDK 1. **Install the SDK** #### npm ```bash npm install @statsig/angular-bindings ``` #### yarn ```bash yarn add @statsig/angular-bindings ``` 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. The Statsig Angular bindings package provides a `StatsigService` that you can inject into your components. The way you provide and inject this service can vary depending on how you structure your app. ```ts import { STATSIG_INIT_CONFIG } from '@statsig/angular-bindings'; const StatsigConfig = { sdkKey: "client-KEY", user: {}, // initial user object options: {...} // optional } ``` ### Using app config ```ts // app.config.ts import { ApplicationConfig } from '@angular/core'; import { STATSIG_INIT_CONFIG } from '@statsig/angular-bindings'; export const appConfig: ApplicationConfig = { providers: [ { provide: STATSIG_INIT_CONFIG, useValue: StatsigConfig, }, ], }; //main.ts import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err), ); ``` ### Using app module ```ts // app.module.ts import { StatsigService } from '@statsig/angular-bindings'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [], providers: [ { provide: STATSIG_INIT_CONFIG, useValue: StatsigConfig, }, ], bootstrap: [AppComponent], }) export class AppModule {} ``` ## Use the SDK After providing the Statsig config token, you can inject the service into a component or another service and use it. ```ts // example.component.ts import { Component } from '@angular/core'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ selector: 'app-example', template: `...`, }) export class ExampleComponent { constructor(private statsigService: StatsigService) {} } ``` ### Checking a Feature Flag/Gate After the SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. ```ts // feature-gate.component.ts import { CommonModule } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-feature-gate', imports: [CommonModule], template: `<div *ngIf="isFeatureEnabled">Feature is enabled!</div>`, }) export class FeatureGateComponent implements OnInit { isFeatureEnabled = false; constructor(private statsigService: StatsigService) {} ngOnInit(): void { this.isFeatureEnabled = this.statsigService.checkGate('feature_gate_name'); } } ``` ### Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but returns an entire JSON object you configure on the server, from which you can fetch typed parameters. For example: ```ts // dynamic-config.component.ts import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-dynamic-config', imports: [CommonModule], template: `<div *ngIf="configValue">Config Value: {{ configValue }}</div>`, }) export class DynamicConfigComponent implements OnInit { configValue: string | null = null; constructor(private statsigService: StatsigService) {} ngOnInit(): void { const dynamicConfig = this.statsigService.getDynamicConfig('config_name'); this.configValue = dynamicConfig.get('key', 'default_value'); } } ``` ### Getting a Layer/Experiment **Layers/Experiments** support running A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```ts // experiment.component.ts import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-experiment', imports: [CommonModule], template: `<div *ngIf="experimentValue">Experiment Value: {{ experimentValue }}</div>`, }) export class ExperimentComponent implements OnInit { experimentValue: string | null = null; constructor(private statsigService: StatsigService) {} ngOnInit(): void { const experiment = this.statsigService.getExperiment('experiment_name'); this.experimentValue = experiment.get('experiment_key', 'default'); } } ``` ```ts // layer.component.ts import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-layer', imports: [CommonModule], template: `<div *ngIf="layerValue">Layer Value: {{ layerValue }}</div>`, }) export class LayerComponent implements OnInit { layerValue: string | null = null; constructor(private statsigService: StatsigService) {} ngOnInit(): void { const layer = this.statsigService.getLayer('layer_name'); this.layerValue = layer.get('layer_key', 'default_layer_value'); } } ``` ### Logging an Event After setting up a Feature Gate or an Experiment, you can track custom events to see how your new features or different experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and metadata object to log with the event: ```ts import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-log-event', imports: [CommonModule], template: ` <button (click)="logUserAction()">Click Me</button> <p *ngIf="message">{{ message }}</p> `, }) export class LogEventComponent { message: string | null = null; constructor(private statsigService: StatsigService) {} logUserAction(): void { this.statsigService.logEvent('UserClickedButton', 1, { buttonColor: 'blue', buttonText: 'Click Me', }); this.message = 'Event logged: UserClickedButton'; } } ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```ts import { Component } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ standalone: true, selector: 'app-flush-events', imports: [CommonModule], template: ` <button (click)="flushEvents()">Flush Events</button> <p *ngIf="message">{{ message }}</p> `, }) export class FlushEventsComponent { message: string | null = null; constructor(private statsigService: StatsigService) {} async flushEvents(): Promise<void> { await this.statsigService.getClient().flush(); this.message = 'Queued events flushed'; } } ``` ## Updating user properties (e.g., Login) Update user properties when the user logs in and you assign a userID, or when you identify new properties. Statsig fetches new values for all gate, experiment, and config evaluations in response. Call `updateUserAsync` from the service: ```ts import { Component } from '@angular/core'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ selector: 'app-user-update', template: ` <button (click)="updateUser()">Update User</button> `, }) export class UserUpdateComponent { constructor(private statsigService: StatsigService) {} updateUser(): void { const user = { userID: 'user-1234', email: 'user@example.com', // Add other user properties here }; this.statsigService.updateUserAsync(user) .then(() => { console.log('User updated successfully'); }) .catch((error) => { console.error('Error updating user:', error); }); } } ``` ## Loading state Depending on your setup, you may want to wait for the latest values before checking a gate or experiment. Use the `isLoading` observable to determine whether the SDK is still loading and display a loading state accordingly. ```ts import { CommonModule } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { StatsigService } from '@statsig/angular-bindings'; @Component({ selector: 'app-loading-state', imports: [CommonModule], template: ` <div *ngIf="isLoading | async; else content"> <p>Loading...</p> </div> <ng-template #content> <p>Content loaded successfully!</p> </ng-template> `, }) export class LoadingStateComponent implements OnInit { isLoading = this.statsigService.isLoading$; constructor(private statsigService: StatsigService) {} ngOnInit(): void { // other initialization logic here } } ``` ## Shutting Statsig down To save data and battery usage and avoid dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, the SDK may not have sent some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, call `shutdown` when your app is closing: ```ts import { StatsigService } from '@statsig/angular-bindings'; export class ShutdownStatsigComponent { constructor(private statsigService: StatsigService) {} ngOnDestroy(): void { void this.statsigService.getClient().shutdown(); } } ``` ## Angular directives ### Statsig Module To use the directives, you need to import the `StatsigModule` in your Angular module. ```ts // app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { StatsigModule } from '@statsig/angular-bindings'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, StatsigModule], bootstrap: [AppComponent] }) export class AppModule {} ``` ### Check gate directive The `stgCheckGate` directive conditionally displays content in your Angular templates based on the evaluation of a Feature Gate from Statsig. It listens for updates to the feature gate's value and dynamically adds or removes content based on whether the gate is enabled. ```ts // feature-demo.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-feature-demo', template: ` <div *stgCheckGate="'new_feature_gate'"> <p>This content will only show if the 'new_feature_gate' is enabled.</p> </div> `, }) export class FeatureDemoComponent {} ``` ## Session Replay By including the [`@statsig/session-replay`](https://www.npmjs.com/package/@statsig/session-replay) package in your project, you can automatically capture and log user sessions as videos. This is useful for debugging and understanding user behavior. Read more about [Session Replay](https://docs.statsig.com/session-replay/overview). ```ts import { STATSIG_INIT_CONFIG } from '@statsig/angular-bindings'; import { StatsigSessionReplayPlugin } from '@statsig/session-replay'; const StatsigConfig = { sdkKey: "client-KEY", user: { userID: 'a-user' }, options: { plugins: [ new StatsigSessionReplayPlugin() ] } } ``` ## Web analytics / auto capture By including the [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) package in your project, you can automatically capture common web events such as clicks and page views. For more information on filtering events, enabling console log capture, and other configuration options, refer to the [Web Analytics Configuration](https://docs.statsig.com/webanalytics/overview#event-filtering-and-console-configuration) documentation. ```ts import { STATSIG_INIT_CONFIG } from '@statsig/angular-bindings'; import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'; const StatsigConfig = { sdkKey: "client-KEY", user: { userID: 'a-user' }, options: { plugins: [ new StatsigAutoCapturePlugin() ] } } ``` ================================================================================ # Roku Client SDK URL: https://docs.statsig.com/client/Roku ================================================================================ # Roku Client SDK - **Repository:** [roku-sdk](https://github.com/statsig-io/roku-sdk) ## Set up the SDK 1. **Install the SDK** Start by downloading [the GitHub repository](https://github.com/statsig-io/roku-sdk). Roku doesn't have a package manager, so you copy the implementation files from this repository to integrate Statsig in your Roku app. You need the following files: ```plaintext Statsig -- components -- statsigsdk -- StatsigTask.brs -- StatsigTask.xml -- source -- DynamicConfig.brs -- Statsig.brs -- StatsigClient.brs -- StatsigUser.brs ``` The library consists of two main parts: - **source/Statsig**: an object used by SceneGraph components that connects a StatsigClient with the background StatsigTask. - **components/StatsigTask**: a SceneGraph Task that runs in the background to batch events and fetch values from Statsig servers. The `components` folder contains SceneGraph components and the `source` folder contains BrightScript files. You must include all of these files in their respective folders of the application. If you change the file paths, you must update the file references in `StatsigTask.xml` and include those references in your main XML file. 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. To initialize the SDK, first integrate the SDK files into your application. Include `StatsigClient.brs`, `StatsigUser.brs`, `DynamicConfig.brs`, and `Statsig.brs`: ```xml <script type="text/brightscript" uri="pkg:/source/Statsig.brs" /> <script type="text/brightscript" uri="pkg:/source/StatsigClient.brs" /> <script type="text/brightscript" uri="pkg:/source/StatsigUser.brs" /> <script type="text/brightscript" uri="pkg:/source/DynamicConfig.brs" /> ``` Next, initialize the library in your `init()` function and add a listener for when the SDK has fetched gates/experiments: ```xml <!-- in component xml --> <StatsigTask id="statsigTask" /> ``` ```brightscript statsigTask = m.top.findNode("statsigTask") statsigTask.observeField("initializeValues", "onStatsigReady") m.statsig = Statsig(statsigTask) user = StatsigUser() user.setUserID("456") m.statsig.initialize("<STATSIG_CLIENT_SDK_KEY>", user) ``` For more information on all of the user fields you can use, refer to the [StatsigUser docs](https://docs.statsig.com/sdks/user). Before the SDK has loaded the updated values, all APIs return default values (false for gates, empty configs and experiments). To implement a callback handler for Statsig being ready, and tell the SDK to load the updated values in the `onStatsigReady` function you registered with `observeField`: ```brightscript function onStatsigReady() as void m.statsig.load() // Check gates, log events, check experiments, etc gate = m.statsig.checkGate("gate_id") config = m.statsig.getConfig("config_id") experiment = m.statsig.getExperiment("experiment_id") m.statsig.logEvent("event_name", "event_value", {metadata: "event_metadata"}) end function ``` To update the user, `m.statsig.updateUser(newUser)` triggers the same `onStatsigReady` callback after the SDK fetches the new gate/config/experiment values from Statsig servers. ================================================================================ # Unity SDK URL: https://docs.statsig.com/client/Unity ================================================================================ # Unity SDK - **Repository:** [unity-sdk](https://github.com/statsig-io/unity-sdk) ## Set up the SDK 1. **Install the SDK** The project is on [GitHub](https://github.com/statsig-io/unity-sdk). Add the package to your Unity project through **Package Manager** > **Add package from Git URL**, then enter `https://github.com/statsig-io/unity-sdk.git` (include the `.git` part in the URL). 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. **Make all API calls to `Statsig` from the main thread.** Operations that take longer, such as network requests, run asynchronously and don't block the main thread. ```csharp using StatsigUnity; await Statsig.Initialize( "client-sdk-key", new StatsigUser { UserID = "some_user_id", Email = "user@email.com" }, new StatsigOptions // optional parameters to customize your Statsig client, see "Statsig Options" section below to see details on available options { EnvironmentTier = EnvironmentTier.Development, InitializeTimeoutMs = 5000, } ); ``` ## Use the SDK ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. ```csharp if (Statsig.CheckGate("show_new_loading_screen")) { // Gate is on, show new loading screen } else { // Gate is off, show old loading screen } ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: ```csharp var config = Statsig.GetConfig("awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. string itemName = config.Get<string>("product_name", "Awesome Product v1"); double price = config.Get<double>("price", 10.0); bool shouldDiscount = config.Get<bool>("discount", false); ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```csharp // Values via getLayer var layer = Statsig.GetLayer("user_promo_experiments"); var promoTitle = layer.Get("title", "Welcome to Statsig!"); var discount = layer.Get("discount", 0.1); // or, via getExperiment var titleExperiment = Statsig.GetExperiment("new_user_promo_title"); var priceExperiment = Statsig.GetExperiment("new_user_promo_price"); var promoTitle = titleExperiment.Get("title", "Welcome to Statsig!"); var discount = priceExperiment.Get("discount", 0.1); ... double price = msrp * (1 - discount); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or different experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: ```csharp Statsig.LogEvent( "purchase", "new_player_pack", new Dictionary<string, string>() { { "price", "9.99" } } ); ``` ## Statsig User You need to provide a StatsigUser object to check/get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. Most of the time, you need the `userID` field to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users). Besides `userID`, Statsig also supports `email`, `ip`, `userAgent`, `country`, `locale` and `appVersion` as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the `custom` field and create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: ```csharp // if you want to update the existing user, or change to a different user, call UpdateUser. // The API makes a network request to fetch values for the new user. await Statsig.UpdateUser( new StatsigUser { UserID = "new_user_id", Email = "new_user@email.com" }, ); ``` ### Private attributes To prevent logging sensitive user PII, use the `privateAttributes` field on the StatsigUser object. Statsig uses attributes set in `privateAttributes` only for evaluation and targeting, then removes them from any logs before sending them to the server. For example, if you have feature gates that pass only for users with emails ending in "@statsig.com" but don't want to log your users' email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options `Initialize()` takes an optional parameter `options` in addition to `clientKey` and `user` that you can provide to customize the Statsig client. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | EnvironmentTier | EnvironmentTier | No | — | Set the environment tier for the user. Values: `Production | Development | Staging`. Statsig includes users with `null` or `Production` tier in Pulse metrics by default. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | InitializeTimeoutMs | int | No | — | Maximum milliseconds `Statsig.Initialize()` waits before proceeding with cached/default values. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | LoggingIntervalMs | int | No | — | Interval for periodically flushing logging events to the Statsig backend. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | LoggingBufferMaxSize | int | No | — | Maximum number of events the logger batches before flushing. | ## Shutting Statsig down The SDK keeps event logs in client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```csharp // This function is async, and you can choose to await for it so that we make sure all the // events that are yet to be flushed get flushed await Statsig.Shutdown(); ``` ## FAQs #### How do I run experiments for logged out users Refer to [Device-level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ================================================================================ # On Device Client SDKs URL: https://docs.statsig.com/client/onDeviceOverview Updated: 2025-09-21 ================================================================================ # On Device Client SDKs ## How on-device eval SDKs work Statsig's client-side On-Device Eval SDKs provide an alternate client-side architecture. The device keeps the definition of each experiment or gate in memory, which allows faster evaluation when the user object changes frequently. (On regular client SDKs, a frequently changing user object requires re-initialization.) The trade-off is that the device exposes config definitions. Use the traditional client SDKs unless you have specific requirements that prevent doing so. If you choose to use the On-Device Eval SDKs, contact the Statsig team first to understand the privacy risks. ## Alternatives An alternative to On-Device Eval SDKs is the [Local Eval Adapter](https://docs.statsig.com/client/concepts/local-eval-adapter), which lets you evaluate locally for only the subset of experiments and gates you need at startup, rather than exposing all configs in your project. ================================================================================ # Swift On Device Evaluation SDK URL: https://docs.statsig.com/client/swiftOnDeviceEvaluationSDK ================================================================================ # Swift On Device Evaluation SDK - **Package:** `StatsigOnDeviceEvaluations` ([cocoapods](https://cocoapods.org/pods/StatsigOnDeviceEvaluations)) - **Latest version:** 1.6.0 - **Repository:** [swift-on-device-evaluations-sdk](https://github.com/statsig-io/swift-on-device-evaluations-sdk) > **Info:** > > Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only. These SDKs use a different paradigm than their precomputed counterparts: [JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK). On-device evaluation SDKs behave more like Server SDKs. Rather than requiring a user in advance, you can check gates, configs, and experiments for any set of user properties. The SDK downloads a complete representation of your project and evaluates checks in real time. ### Pros - No network request is needed when changing user properties: check the gate/config/experiment locally - You can bring your own CDN or synchronously initialize with a preloaded project definition - Lower latency to download configs cached at the edge, rather than evaluated for a given user (which Statsig can't cache as much) ### Cons - The client has the entire project definition: it exposes the names and configurations of all experiments and feature flags accessible by your client key. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions). - Payload size is larger than what the traditional SDKs require - Evaluation performance is slightly slower: rather than looking up the value, the SDK must evaluate targeting conditions and an allocation decision - Doesn't support ID list segments with > 1000 IDs - Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country) ## Set up the SDK 1. **Install the SDK** To use the SDK in your project, you must add Statsig as a dependency. #### Swift Package Manager ```swift // In your Xcode, select File > Swift Packages > Add Package Dependency // and enter the URL https://github.com/statsig-io/swift-on-device-evaluations-sdk.git. // // You can also include it directly in your project's Package.swift. // Find out the latest release version on our GitHub page: // https://github.com/statsig-io/swift-on-device-evaluations-sdk/releases dependencies: [ // see the latest version on https://github.com/statsig-io/swift-on-device-evaluations-sdk/releases .package(url: "https://github.com/statsig-io/swift-on-device-evaluations-sdk.git", .upToNextMinor("X.Y.Z")), ], //... targets: [ .target( name: "YOUR_TARGET", dependencies: ["StatsigOnDeviceEvaluations"] ) ], ``` #### CocoaPods ```ruby # If you are using CocoaPods, our pod name is 'StatsigOnDeviceEvaluations', # and you can include the following line to your Podfile: use_frameworks! target 'TargetName' do //... pod 'StatsigOnDeviceEvaluations', '~> X.Y.Z' end # Find the latest versions by searching cocoapods.org or on Github: # https://github.com/statsig-io/swift-on-device-evaluations-sdk/releases ``` 2. **Initialize the SDK** Next, initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you want to target later on in a gate or experiment. > **Warning:** > > For On-Device Evaluation, add the **"Allow Download Config Specs"** scope. Client keys, by default, can't download the project definition for on-device evaluation. > > While client keys are safe to include, always keep Server and Console keys private. #### How to add the scope #### New SDK Keys When creating a new client key, select **"Allow Download Config Specs"** ![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png) #### Existing SDK Keys To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**. ![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png) #### Async (Swift) ```swift import StatsigOnDeviceEvaluations // (optional) Configure the SDK if needed let opts = StatsigOptions() opts.environment.tier = "staging" Statsig.shared.initialize("client-sdk-key", options: opts) { err in if let err = err { print("Error \(err)") } } // or, create your own instance let myStatsigInstance = Statsig() myStatsigInstance.initialize("client-sdk-key", options: opts) { err in if let err = err { print("Error \(err)") } } ``` #### Objective C ```objective-c StatsigOptions *options = [StatsigOptions new]; StatsigEnvironment *env = [StatsigEnvironment new]; env.tier = @"staging"; options.environment = env; [[Statsig sharedInstance] initializeWithSDKKey:@"client-sdk-key" options:options completion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error %@", error); } }]; ``` #### Synchronous (Swift) ```swift import StatsigOnDeviceEvaluations // (optional) Configure the SDK if needed let opts = StatsigOptions() opts.environment.tier = "staging" let specs: NSString = "..." // JSON string of your configurations let error = client.initializeSync("client-sdk-key", initialSpecs: specs) if let err = error { print("Error \(err)") } ``` You can configure the SDK to use cached values if they are newer than the local file. This is useful when you ship your app with a local file but want it used only for the first session. In the following example, the SDK uses `initialSpecs` only when there is no cache or the cache is older than `initialSpecs`. ```swift let options = StatsigOptions() options.useNewerCacheValuesOverProvidedValues = true client.initializeSync( "client-sdk-key", initialSpecs: specs, options: options ) ``` > **Note:** > > You can get a copy of your current specs data by visiting: `https://api.statsigcdn.com/v1/download_config_specs/client-{YOUR_SDK_KEY}.json` ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. #### Swift ```swift // Simple Pass/Fail check let isPassing: Bool = Statsig.shared.checkGate("my_gate", user) // or, the verbose FeatureGate check let gate = Statsig.shared.getFeatureGate("my_gate", user) print(gate.evaluationDetails.reason) // "Network" | "Cache" | "Unrecognized" let isPassing: Bool = gate.value ``` #### Objective C ```objective-c BOOL isPassing = [[Statsig sharedInstance] checkGate:@"my_gate" forUser:user]; ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional advanced user targeting. If you need to send a different set of values (strings, numbers, and so on) to your clients based on specific user attributes (such as country), use **Dynamic Configs**. The API is similar to Feature Gates, but you receive an entire JSON object you can configure on the server and fetch typed parameters from. ```swift let config = Statsig.shared.getDynamicConfig("my_dynamic_config", user) let name: String? = config.value["product_name"] as? String let price: Double? = config.value["price"] as? Double ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs but recommends [layers](https://docs.statsig.com/experiments/layers-overview) because they enable quicker iterations with parameter reuse. ```swift // Getting values via getLayer let layer = Statsig.shared.getLayer("my_layer", user) let name: String? = layer.getValue(param: "product_name", fallback: "Unknown") as? String // or, using getExperiment let experiment = Statsig.shared.getExperiment("my_experiment", user) let name: String? = experiment.value["product_name"] as? String let price: Double? = experiment.value["price"] as? Double ``` ### Logging an event After you set up a Feature Gate or an Experiment, you can track custom events to see how your features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and an object of metadata to log with the event: ```swift let event = StatsigEvent( eventName: "add_to_cart", value: "SKU_1234", metadata: [ "price": "9.99", "item_name": "CoolProduct" ] ) Statsig.shared.logEvent(event, user) ``` ### Code examples Find working sample apps in the repository: - [Swift & Objective C Examples](https://github.com/statsig-io/swift-on-device-evaluations-sdk/tree/main/Sample/App/Examples/OnDeviceEvaluations) ## Statsig user Provide a `StatsigUser` object to check or get your configurations. Pass as much information as possible to use advanced gate and config conditions. You usually need the `userID` field to provide a consistent experience for a given user. Refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users. In addition to `userID`, `StatsigUser` has the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field to create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: #### Swift ```swift let user = StatsigUser( userID: "a-user", customIDs: ["EmployeeID": "an-employee"], email: "user@statsig.io", ip: "58.84.239.246", userAgent: "Mozilla/5.0 (iPad; CPU OS 13_4_1....", country: "NZ", locale: "en_NZ", appVersion: "3.2.1", custom: ["Level": "9001"], privateAttributes: ["SensitiveInfo": "shhh"] ) ``` #### Objective C ```objective-c StatsigUser *user = [StatsigUser userWithUserID:@"a-user"]; user.customIDs = @{ @"EmployeeID": @"an-employee" }; user.email = @"user@statsig.io"; user.ip = @"58.84.239.246"; user.userAgent = @"Mozilla/5.0 (iPad; CPU OS 13_4_1...."; user.country = @"NZ"; user.locale = @"en_NZ"; user.appVersion = @"3.2.1"; [user.custom setString:@"9001" forKey:@"Level"]; [user.privateAttributes setString:@"shhh" forKey:@"SensitiveInfo"]; ``` ### Private attributes The `StatsigUser` object has a `privateAttributes` field: an object/dictionary for setting private user attributes. Statsig uses any attribute set in `privateAttributes` only for evaluation and targeting, and removes it from any logs before sending them to the server. For example, you might have feature gates that should pass only for users with emails ending in "@statsig.com", but you don't want to log users' email addresses to Statsig. In this case, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ### Setting a global user To avoid passing the user object to every evaluation call, you can set a global user. The SDK uses the global user for all evaluations unless otherwise specified. ```swift Statsig.shared.setGlobalUser(myGlobalUser) Statsig.shared.checkGate("my_gate") // <- Will use myGlobalUser Statsig.shared.checkGate("my_gate", StatsigUser(userID: "user-123")) // <- Will NOT use myGlobalUser ``` > **Note:** > > Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in. ## Statsig options Configure the SDK behavior by passing a `StatsigOptions` object during initialization. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventQueueMaxSize | Int | No | — | The maximum number of events to batch before flushing logs to the server. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventQueueInternalMs | Double | No | — | How frequently to flush queued logs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingAPI | String | No | — | The API where Statsig sends all events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | configSpecAPI | String | No | — | The API the SDK uses to fetch the latest configurations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | An object you can use to set environment variables that apply to all of your users in the same session and Statsig uses for targeting purposes. | ## Lifecycle and advanced usage ## Shutting Statsig down The SDK keeps event logs in a client cache and flushes them periodically to save battery usage and prevent dropped events. Statsig may not send some events when your app shuts down before a flush occurs. To flush or save all logged events locally, call shutdown when your app is closing: #### Swift ```swift Statsig.shared.shutdown { err in if let err = err { print("An error occurred during Statsig shutdown: \(err)") } else { print("Statsig shutdown successfully") } } ``` #### Objective C ```objective-c [[Statsig sharedInstance] shutdownWithCompletion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"An error occurred during Statsig shutdown: %@", error); } else { NSLog(@"Statsig shutdown successfully"); } }]; ``` ## Post-init syncing ### From network By default, the SDK syncs only during initialization. To re-sync after initialization, call the `Statsig.update` method. This triggers a network call to fetch the latest changes from the server. ```swift Statsig.shared.update { err in if let err = err { print("Statsig update error: \(err)") } } ``` ### From a local file If you maintain your own copy of the "specs" json, pass it to `Statsig.updateSync()`. This skips the network call and uses the provided specs instead. ```swift let result = Statsig.shared.updateSync(updatedSpecs: myJsonData) ``` ### Scheduled polling To have the SDK regularly poll for updates, start the polling task with `Statsig.scheduleBackgroundUpdates()`. This calls `Statsig.update` internally to fetch the latest changes from the network. ```swift let pollingTask = Statsig.shared.scheduleBackgroundUpdates() // Defaults to 1 hour interval // or, specify a custom interval let pollingTask = Statsig.shared.scheduleBackgroundUpdates(intervalSeconds: 300) // and, if you need to cancel it later pollingTask?.cancel() ``` ## Local overrides Override the values the Statsig SDK returns for unit testing or for enabling features in local development. To set up local overrides, pass an instance of `LocalOverrideAdapter` to the SDK through the `StatsigOptions` object. > **Note:** > > You can write your own override adapter by implementing the [`OverrideAdapter`](https://github.com/statsig-io/swift-on-device-evaluations-sdk/blob/main/Sources/StatsigOnDeviceEvaluations/OverrideAdapter.swift) protocol and passing it in instead. #### Swift ```swift let user = StatsigUser(userID: "a-user") let overrides = LocalOverrideAdapter() // Override a gate overrides.setGate(user, FeatureGate.create("local_override_gate", true)) // Override a dynamic config (Similar for Layer and Experiment) overrides.setDynamicConfig(user, DynamicConfig.create("local_override_dynamic_config", ["foo": "bar"])) let opts = StatsigOptions() opts.overrideAdapter = overrides Statsig.shared.initialize(YOUR_SDK_KEY, options: opts) { _ in let gate = Statsig.shared.getFeatureGate("local_override_gate", user) print("Result: \(gate.value) (\(gate.evaluationDetails.reason))") } ``` #### Objective C ```objective-c StatsigUser *user = [StatsigUser userWithUserID:@"a-user"]; LocalOverrideAdapter *overrides = [LocalOverrideAdapter new]; // Override a gate [overrides setGateForUser:user gate:[FeatureGate createWithName:@"local_override_gate" andValue:true]]; // Override a dynamic config (Similar for Layer and Experiment) [_overrides setDynamicConfigForUser:user config:[DynamicConfig createWithName:@"local_override_dynamic_config" andValue:@{@"foo": @"bar"}]]; StatsigOptions *options = [StatsigOptions new]; options.overrideAdapter = overrides; [[Statsig sharedInstance] initializeWithSDKKey:YOUR_SDK_KEY options:options completion:^(NSError * _Nullable error) { FeatureGate *gate = [[Statsig sharedInstance] getFeatureGate:@"local_override_gate" forUser:user options:nil]; NSLog(@"Result: %d (%@)", gate.value, gate.evaluationDetails.reason); }]; ``` ## FAQs #### How do I run experiments for logged out users? Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ## Additional resources - [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview) - [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions) - [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging) ================================================================================ # Android On Device Evaluation SDK URL: https://docs.statsig.com/client/androidOnDeviceEvaluationSDK ================================================================================ # Android On Device Evaluation SDK - **Repository:** [android-local-eval](https://github.com/statsig-io/android-local-eval) > **Info:** > > Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only. These SDKs use a different paradigm than their precomputed counterparts ([JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK)). Rather than requiring a user upfront, you can check gates/configs/experiments for any set of user properties. You can do this because the SDK downloads a complete representation of your project and evaluates checks in real time. ### Pros - No network request needed when changing user properties: check the gate/config/experiment locally - Can bring your own CDN or synchronously initialize with a preloaded project definition - Lower latency to download configs cached at the edge, rather than evaluated for a given user (which can't be cached as much) ### Cons - The entire project definition lives client-side: your client key exposes the names and configurations of all experiments and feature flags. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions). - Payload size is strictly larger than what is required for the traditional SDKs - Evaluation performance is slightly slower - rather than looking up the value, the SDK must actually evaluate targeting conditions and an allocation decision - Doesn't support ID list segments with > 1000 IDs - Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country) ## Set up the SDK 1. **Install the SDK** You can install the SDK using JitPack. Go to https://jitpack.io/#statsig-io/android-local-eval for the latest version and installation steps. 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you want to target later in a gate or experiment. > **Warning:** > > For On-Device Evaluation, you need to add the **"Allow Download Config Specs"** scope. Client keys can't download the project definition for on-device evaluation by default. > > While client keys are safe to include, always keep Server and Console keys private. #### How to add the scope #### New SDK Keys When creating a new client key, select **"Allow Download Config Specs"** ![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png) #### Existing SDK Keys To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**. ![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png) #### Java ```java import com.statsig.androidlocalevalsdk.*; // ... android.app.Application app = // ref to your Application instance StatsigOptions opts = new StatsigOptions(); opts.setEnvironmentParameter("tier", "staging"); StatsigClient client = Statsig.INSTANCE.getClient(); client.initializeAsync( app, "client-YOUR_CLIENT_SDK_KEY", new IStatsigCallback() { @Override public void onStatsigInitialize(@NotNull InitializationDetails initDetails) { // Statsig Ready } @Override public void onStatsigInitialize() { // deprecated } }, opts ); // or, create your own instance of StatsigClient StatsigClient client = new StatsigClient(); client.initializeAsync(...); ``` #### Kotlin ```kotlin import com.statsig.androidlocalevalsdk.* // ... val opts = StatsigOptions() opts.setEnvironmentParameter("tier", "staging") Statsig.client.initializeAsync( application, // ref to your Application instance "client-YOUR_CLIENT_SDK_KEY", object : IStatsigCallback { override fun onStatsigInitialize(initDetails: InitializationDetails) { // Statsig Ready } override fun onStatsigInitialize() { // deprecated } }, opts ) // or, create your own instance of StatsigClient val client = StatsigClient() client.initializeAsync(...) ``` ### Synchronous initialization ```kotlin import com.statsig.androidlocalevalsdk.* // (optional) Configure the SDK if needed val opts = StatsigOptions() opts.environment.tier = "staging" val specs = "..." // JSON string of your configurations let details = Statsig.client.initializeSync(application, "client-YOUR_CLIENT_SDK_KEY", specs, opts) ``` You can configure the SDK to use cached values if they are newer than the local file. This is useful if you ship your app with a local file but want to use it only for the first session. In the following example, the SDK only uses initialSpecs if there is no cache or if the cache is older than initialSpecs. ```kotlin val options = StatsigOptions() options.useNewerCacheValuesOverProvidedValues = true Statsig.client.initializeSync( application, "client-YOUR_CLIENT_SDK_KEY", specs, options ) ``` > **Note:** > > You can get a copy of your current specs data by visiting: `https://api.statsigcdn.com/v1/download_config_specs/client-{YOUR_SDK_KEY}.json` ## Working with the SDK ### Checking a Feature Flag/Gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). You can use Feature Gates to create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. #### Java ```java StatsigUser user = new StatsigUser("a-user"); StatsigClient client = Statsig.INSTANCE.getClient(); if (client.checkGate(user, "new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` #### Kotlin ```kotlin val user = StatsigUser("user_id") if (Statsig.client.checkGate(user, "new_homepage_design")) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional advanced user targeting. To send a different set of values (strings, numbers, etc.) to clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates, but you get a complete JSON object you can configure on the server and fetch typed parameters from it. For example: #### Java ```java StatsigUser user = new StatsigUser("a-user"); StatsigClient client = Statsig.INSTANCE.getClient(); DynamicConfig config = client.getConfig(user, "awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. String itemName = config.getString("product_name", "Awesome Product v1"); Double price = config.getDouble("price", 10.0); Boolean shouldDiscount = config.getBoolean("discount", false); ``` #### Kotlin ```kotlin val user = StatsigUser("user_id") val config = Statsig.client.getConfig(user, "awesome_product_details") // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. val itemName = config.getString("product_name", "Awesome Product v1") val price = config.getDouble("price", 10.0) val shouldDiscount = config.getBoolean("discount", false) ``` ### Getting a Layer/Experiment **Layers/Experiments** let you run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) for quicker iterations with parameter reuse. #### Java ```java StatsigUser user = new StatsigUser("a-user"); StatsigClient client = Statsig.INSTANCE.getClient(); // Values via getLayer Layer layer = client.getLayer(user, "user_promo_experiments") String promoTitle = layer.getString("title", "Welcome to Statsig!"); Double discount = layer.getDouble("discount", 0.1); // or, via getExperiment DynamicConfig titleExperiment = client.getExperiment(user, "new_user_promo_title"); DynamicConfig priceExperiment = client.getExperiment(user, "new_user_promo_price"); String promoTitle = titleExperiment.getString("title", "Welcome to Statsig!"); Double discount = priceExperiment.getDouble("discount", 0.1); ... Double price = msrp * (1 - discount); ``` #### Kotlin ```kotlin val user = StatsigUser("user_id") // Values via getLayer val layer = Statsig.client.getLayer(user, "user_promo_experiments") val promoTitle = layer.getString("title", "Welcome to Statsig!") val discount = layer.getDouble("discount", 0.1) // or, via getExperiment val titleExperiment = Statsig.client.getExperiment(user, "new_user_promo_title") val priceExperiment = Statsig.client.getExperiment(user, "new_user_promo_price") val promoTitle = titleExperiment.getString("title", "Welcome to Statsig!") val discount = priceExperiment.getDouble("discount", 0.1) ... val price = msrp * (1 - discount); ``` ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or different experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: #### Java ```java StatsigUser user = new StatsigUser("user_id"); StatsigClient client = Statsig.INSTANCE.getClient(); client.logEvent(user, "purchase", 2.99, Map.of("item_name", "remove_ads")); ``` #### Kotlin ```kotlin val user = StatsigUser("user_id") Statsig.client.logEvent(user, "purchase", 2.99, mapOf("item_name" to "remove_ads")) ``` ## Statsig User You need to provide a StatsigUser object to check/get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. Most of the time, you need the `userID` field to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users). Besides `userID`, Statsig also supports `email`, `ip`, `userAgent`, `country`, `locale` and `appVersion` as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the `custom` field and create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: > **Note:** > > For the Android On-Device Evaluation SDK, you pass the `StatsigUser` object directly into each evaluation method (`checkGate`, `getConfig`, etc.) rather than during initialization. > **Note:** > > Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in. ### Setting a global user To avoid passing the user object to every evaluation call, set a global user. When checking a gate/experiment/layer, provide `null` for the user to use the global user. The SDK uses the global user for all evaluations unless you provide a specific user. ```kotlin Statsig.client.setGlobalUser(myGlobalUser) Statsig.client.checkGate(null, "my_gate") // <- Will use myGlobalUser Statsig.client.checkGate(StatsigUser(userID: "user-123"), "my_gate") // <- Will NOT use myGlobalUser ``` ## Statsig Options Pass an optional `options` parameter in addition to `sdkKey` and `user` during initialization to customize the Statsig client. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | configSpecAPI | String | No | — | The endpoint to use for downloading config spec network requests. You shouldn't need to override this (unless you have another API that implements the Statsig API endpoints). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingAPI | String | No | — | The endpoint to use for log events. You shouldn't need to override this (unless you have another API that implements the Statsig API endpoints). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initTimeoutMs | Long | No | — | Milliseconds to wait for the initial network request before calling the completion block. The Statsig client returns either cached values (if any) or default values if you call checkGate/getConfig/getExperiment before the initial network request completes. Set to `0` to wait indefinitely for the latest values. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideStableID | String? | No | — | Overrides the `stableID` in the SDK set for the user. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loadCacheAsync | Boolean | No | — | Whether or not the SDK should block on loading saved values from disk. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initializeValues | Map<String, Any>? | No | — | Provide the `download_config_specs` response values directly to the Android SDK to synchronously initialize the client. You can get a copy of your current specs data by visiting: `https://api.statsigcdn.com/v1/download_config_specs/client-{YOUR_SDK_KEY}.json` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableDiagnosticsLogging | Boolean | No | — | Prevent the SDK from sending useful debug information to Statsig. | #### Methods - **setTier | setEnvironmentParameter | getEnvironment** - Signals the environment tier for the user. - `setTier` can be PRODUCTION, STAGING or DEVELOPMENT. For example, passing `Tier.STAGING` allows your users to pass any condition set for the staging environment tier. Conditions set only for other environment tiers fail. - Use `setEnvironmentParameter` for custom tiers, eg `options.setEnvironmentParameter("tier", "test")` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: #### Java ```java Statsig.shutdown(); ``` #### Kotlin ```kotlin Statsig.shutdown() ``` ## Post init syncing ### From network By default, the SDK syncs only during initialization. To re-sync after initialization, call the `Statsig.client.updateAsync` method. This triggers a network call to fetch the latest changes from the server. ```kotlin val details = Statsig.client.updateAsync() ``` ### Scheduled polling To have the SDK regularly poll for updates, start the polling task with `Statsig.client.scheduleBackgroundUpdates()`. The SDK fetches the latest changes from the network on each interval. ```kotlin val pollingTask = Statsig.cloent.scheduleBackgroundUpdates() // Defaults to 1 hour interval // or, specify a custom interval val intervalSeconds = 300 val pollingTask = Statsig.client.scheduleBackgroundUpdates(intervalSeconds) // and, if you need to cancel it later pollingTask?.cancel() ``` ## Using persistent evaluations To ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting, implement the `UserPersistentStorageInterface` and set it in `StatsigOptions` when you initialize the SDK. #### Synchronous persistent evaluations The `UserPersistentStorageInterface` exposes two methods for synchronous persistent storage, which the SDK calls by default when evaluating an experiment. ```plaintext interface UserPersistentStorageInterface { suspend fun load(key: String): PersistedValues fun save(key: String, experimentName: String, data: String) fun delete(key: String, experiment: String) ... } ``` The `key` string is a combination of ID and ID Type: for example, `"123:userID"` or `"abc:stableID"`. The SDK constructs this key and calls `get` and `set` on it by default. Use this interface to persist evaluations synchronously to local storage. If you need an async interface, refer to Asynchronous persistent evaluations. #### Asynchronous persistent evaluations The `UserPersistentStorageInterface` exposes two methods for asynchronous persistent evaluations. Because the `getExperiment` call is synchronous, you must load the value first and pass it in as `userPersistedValues`. ```kotlin interface UserPersistentStorageInterface { fun loadAsync(key: String, callback: IPersistentStorageCallback) fun save(key: String, experimentName: String, data: String) fun delete(key: String, experiment: String) ... } interface IPersistentStorageCallback { fun onLoaded(values: PersistedValues) } ``` The SDK offers a top-level method to load the value for a given user and ID Type: ```kotlin // Asynchronous load values val userPersistedValues = Statsig.client.loadUserPersistedValuesAsync( user: StatsigUser, idType: string, // userID, stableID, customIDxyz, etc callback: IPersistentStorageCallback ); // Synchronous load values val userPersistedvalues = Statsig.client.loadUserPersistedValues( user: StatsigUser, idType: string, // userID, stableID, customIDxyz, etc ) ``` After implementing the `UserPersistentStorageInterface` and setting it on `StatsigOptions`, the call site looks like this: ```kotlin // Asynchronous val callback = object: IPersistentStorageCallback { @override fun onLoaded(values: PersistedValues) { Statsig.getExperiment(user, "sample_experiment", GetExperimentOptions(userPersistedValues = values)) } } val userValues = Statsig.client.loadUserPersistedValuesAsync(user, "userID", callback) // Synchronous val user = StatsigUser(userID = "user123") val userValues = Statsig.client.loadUserPersistedValues(user, 'userID'); const experiment = statsig.getExperiment({userID: "123"}, 'the_allocated_experiment', { userPersistedValues: userValues }); ``` If you're using Java, override only the `loadAsync` function and leave the `load` function empty. ## Local overrides You can override the values the Statsig SDK returns. This is useful in unit testing or for enabling features for local development. To set up local overrides, pass an instance of `LocalOverrideAdapter` to the SDK through the `StatsigOptions` object. > **Note:** > > You can write your own override adapter. You can implement the [`IOverrideAdapter`](https://github.com/statsig-io/android-local-eval/blob/main/src/main/java/com/statsig/androidlocalevalsdk/IOverrideAdapter.kt) interface and pass that in instead. #### Kotlin ```kotlin val user = StatsigUser("user-a") val overrides = LocalOverrideAdapter() // Override a gate overrides.setGate(user, "local_override_gate", true) // Override a dynamic config (Similar for Layer and Experiment) val config = DynamicConfig("local_override_dynamic_config", mapOf("key" to "val")) overrides.setConfig(user, config) val opts = StatsigOptions() opts.overrideAdapter = overrides Statsig.client.initializeAsync( app, YOUR_SDK_KEY, callback, opts // <- Pass in StatsigOptions ) ``` #### Java ```java StatsigUser user = new StatsigUser("a-user"); LocalOverrideAdapter overrides = new LocalOverrideAdapter(); // Override a gate overrides.setGate(user, "local_override_gate", true); // Override a dynamic config (Similar for Layer and Experiment) HashMap<String, Object> configValue = new HashMap<String, Object>() {}; DynamicConfig config = new DynamicConfig( "local_override_dynamic_config", configValue, "local_override", null, new ArrayList<Map<String, String>>(), null ); overrides.setConfig(user, config); StatsigOptions opts = new StatsigOptions(); opts.setOverrideAdapter(overrides); StatsigClient client = Statsig.INSTANCE.getClient(); client.initializeAsync( app, YOUR_SDK_KEY, callback, opts // <- Pass in StatsigOptions ); ``` ## FAQs #### How do I run experiments for logged out users? Refer to [Device-level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ## Additional resources - [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview) - [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions) - [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging) ================================================================================ # JavaScript On-Device Evaluation Client SDK URL: https://docs.statsig.com/client/jsOnDeviceEvaluationSDK ================================================================================ # JavaScript On-Device Evaluation Client SDK - **Package:** `@statsig/js-on-device-eval-client` ([npm](https://www.npmjs.com/package/@statsig/js-on-device-eval-client)) - **Latest version:** 3.33.7 - **Package size:** 27.0 kB gzip - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) > **Info:** > > Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only. These SDKs use a different paradigm than their precomputed counterparts ([JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK)) and behave more like Server SDKs. Rather than requiring a user in advance, you can check gates/configs/experiments for any set of user properties. The SDK downloads a complete representation of your project and evaluates checks in real time. ### Pros - No need for a network request when changing user properties: check the gate/config/experiment locally - Can bring your own CDN or synchronously initialize with a preloaded project definition - Lower latency to download configs cached at the edge, rather than evaluated for a given user (which Statsig can't cache as much) ### Cons - The client has the entire project definition: it exposes the names and configurations of all experiments and feature flags accessible by your client key. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions). - Payload size is strictly larger than what the traditional SDKs require - Evaluation performance is slightly slower: rather than looking up the value, the SDK must evaluate targeting conditions and an allocation decision - Doesn't support ID list segments with > 1000 IDs - Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country) ## Set up the SDK 1. **Install the SDK** Install the Statsig SDK using npm, yarn, or jsdelivr: #### npm ```bash npm install @statsig/js-on-device-eval-client ``` #### yarn ```bash yarn add @statsig/js-on-device-eval-client ``` #### CDN / <script> ```html <script src="https://cdn.jsdelivr.net/npm/@statsig/js-on-device-eval-client@1/build/statsig-js-on-device-eval-client.min.js"></script> ``` Statsig is hosted on the [jsDelivr](https://www.jsdelivr.com/package/npm/@statsig/js-client) CDN. To access the current primary JavaScript bundle, use: `https://cdn.jsdelivr.net/npm/@statsig/js-client/build/statsig-js-client.min.js` To access specific files/versions: `https://cdn.jsdelivr.net/npm/@statsig/js-client@{version}/build/statsig-js-client.min.js` 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later in a gate or experiment. > **Warning:** > > For On-Device Evaluation, you need to add the **"Allow Download Config Specs"** scope. Client keys, by default, can't download the project definition for on-device evaluation. > > While client keys are safe to include, always keep Server and Console keys private. #### How to add the scope #### New SDK Keys When creating a new client key, select **"Allow Download Config Specs"** ![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png) #### Existing SDK Keys To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**. ![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png) ```typescript import { StatsigOnDeviceEvalClient } from '@statsig/js-on-device-eval-client'; const myStatsigClient = new StatsigOnDeviceEvalClient( YOUR_CLIENT_KEY, { environment: {tier: 'development'} } ); // initialize and wait for the latest values await myStatsigClient.initializeAsync(); ``` > **Note:** > > In advanced use cases, you may want to Prefetch or Bootstrap (Provide) values for initialization. Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn how to do this. ## Working with the SDK ## Setup a StatsigUser To interact with the SDK, create a `StatsigUser` object. The full definition of this object is [here](#statsig-user). ```typescript const myUser = { userID: "a-user", email: "user@statsig.com" }; ``` ### Checking a feature flag/gate Now that your SDK is initialized, check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (think `return false;`) by default. ```typescript if (myStatsigClient.checkGate("new_homepage_design", myUser)) { // Gate is on, show new home page } else { // Gate is off, show old home page } ``` ### Reading a dynamic config Feature Gates work well for simple on/off switches with optional advanced user targeting. To send different values (strings, numbers, and similar types) to your clients based on specific user attributes such as country, use **Dynamic Configs**. The API is similar to Feature Gates but returns a full JSON object you can configure on the server and fetch typed parameters from. For example: ```typescript const dynamicConfig = myStatsigClient.getDynamicConfig("awesome_product_details", myUser); const itemName = dynamicConfig.value["product_name"] ?? "Some Fallback"; const price = dynamicConfig.value["price"] ?? 10.0; if (dynamicConfig.value["is_discount_enabled"] === true) { // apply some discount logic } ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Statsig offers two APIs, but recommends [layers](https://docs.statsig.com/experiments/layers-overview) to enable quicker iterations with parameter reuse. ```typescript // Values via getLayer const layer = myStatsigClient.getLayer("user_promo_experiments", myUser); const promoTitle = layer.get("title") ?? "Welcome to Statsig!"; const discount = layer.get("discount") ?? 0.1; // or, via getExperiment const titleExperiment = myStatsigClient.getExperiment("new_user_promo_title", myUser); const priceExperiment = myStatsigClient.getExperiment("new_user_promo_price", myUser); const promoTitle = titleExperiment.value["title"] ?? "Welcome to Statsig!"; const discount = priceExperiment.value["discount"] ?? 0.1; ``` ### Logging an event After you set up a Feature Gate or an Experiment, you can track custom events to measure how your new features or experiment groups affect those events. Call the Log Event API for the event, and optionally provide a value and/or a metadata object to log together with the event: ```typescript import type { StatsigEvent } from '@statsig/client-core'; // log a simple event myStatsigClient.logEvent('my_simple_event'); // or, include more information by using a StatsigEvent object const myEvent: StatsigEvent = { eventName: 'add_to_cart', value: 'SKU_12345', metadata: { price: '9.99', item_name: 'diet_coke_48_pack', }, }; myStatsigClient.logEvent(myEvent); ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```typescript await myStatsigClient.flush(); ``` ### Code examples Find working sample apps in the repository: - [JavaScript & TypeScript Examples](https://github.com/statsig-io/js-client-monorepo/tree/main/samples) ## Statsig user Provide a StatsigUser object to check or get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. You usually need the `userID` field to provide a consistent experience for a given user. (Refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users.) Besides `userID`, StatsigUser has the following top-level fields: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. > **Note:** > > For the JavaScript On-Device Evaluation SDK, you pass the `StatsigUser` object into each evaluation method (`checkGate`, `getConfig`, etc.) rather than during initialization. > **Note:** > > Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in. ## Client event emitter You can subscribe to StatsigClientEvents (not to be confused with [StatsigEvent](#logging-an-event)). These events occur at various stages while using the Statsig client. Subscribe to specific events by specifying the StatsigClientEvent name, or subscribe to all events using the wildcard token `'*'`. ```typescript import type { AnyStatsigClientEvent, StatsigClientEvent, StatsigClientEventCallback, } from '@statsig/client-core'; const onAnyClientEvent = (event: AnyStatsigClientEvent) => { console.log("Any Client Event", event); }; const onLogsFlushed = (event: StatsigClientEvent<'logs_flushed'>) => { console.log("Logs", event.events); }; // subscribe to an individual StatsigClientEvent myStatsigClient.on('logs_flushed', onLogsFlushed); // or, subscribe to all StatsigClientEvents myStatsigClient.on('*', onAnyClientEvent); // then later, unsubscribe from the events myStatsigClient.off('logs_flushed', onLogsFlushed); myStatsigClient.off('*', onAnyClientEvent); ``` The full list of events and descriptions can be found [here](https://github.com/statsig-io/js-client-monorepo/blob/main/packages/client-core/src/StatsigClientEventEmitter.ts). ## Statsig options Configure the SDK's behavior by passing a StatsigOptions object during initialization. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | The API to use for all SDK network requests. You don't need to override this unless you have another API that implements the Statsig API endpoints. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | The URL used to flush queued events through a POST request. Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventBeaconUrl | string | No | — | The URL used to flush queued events through `window.navigator.sendBeacon` (web only). Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | downloadConfigSpecsUrl | string | No | — | The URL used to fetch your latest Statsig specifications. Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | An object you can use to set environment variables that apply to all of your users in the same session. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideStableID | string | No | — | Overrides the auto-generated stableID that is set for the device. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logLevel | LogLevel | No | — | How much information Statsig can print to the console. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | SpecsDataAdapter | No | — | Implementing this type allows customization of the initialization. Refer to [Using SpecsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn more. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkTimeoutMs | number | No | — | The maximum amount of time (in milliseconds) that any network request can take before timing out. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingBufferMaxSize | number | No | — | The maximum number of events to batch before flushing logs to Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | — | How often (in milliseconds) to flush logs to Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideAdapter | OverrideAdapter | No | — | An implementor of `OverrideAdapter`, used to alter evaluations before Statsig returns them to the caller of a check API (checkGate/getExperiment etc). | ## Manual exposures > **Warning:** > > Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results. You can query your gates/experiments without triggering an exposure and manually log the exposures later. ### Gates ```typescript // Check gate with exposure disabled const result = myStatsigClient.checkGate('a_gate_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.checkGate('a_gate_name', { user }); ``` ### Configs ```typescript // Get config with exposure disabled const config = myStatsigClient.getConfig('a_dynamic_config_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.getConfig('a_dynamic_config_name', { user }); ``` ### Experiments ```typescript // Get experiment with exposure disabled const experiment = myStatsigClient.getExperiment('an_experiment_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.getExperiment('an_experiment_name', { user }); ``` ### Layers ```typescript // Get layer with exposure disabled const layer = myStatsigClient.getLayer('a_layer_name', { user, disableExposureLog: true }); const paramValue = layer.get('a_param_name', 'fallback_value'); // Manually log the exposure const layer = myStatsigClient.getLayer('a_layer_name', { user }); const paramValue = layer.get('a_param_name', 'fallback_value'); ``` ## Lifecycle and advanced usage ## Shutting Statsig down To save users' data and battery usage and prevent dropping logged events, the SDK keeps event logs in client cache and flushes them periodically. Because of this periodic flushing, Statsig may not have sent some events when your app shuts down. To ensure Statsig flushes or saves all logged events locally, call shutdown when your app is closing. ```typescript await myStatsigClient.shutdown(); ``` ## Data adapter The `EvaluationsDataAdapter` type outlines how the `StatsigClient` fetches and caches data during initialize and update operations. By default, the `StatsigClient` uses `StatsigEvaluationsDataAdapter`, a Statsig-provided implementor of the `EvaluationsDataAdapter` type. `StatsigEvaluationsDataAdapter` provides ways to fetch data synchronously from Local Storage and asynchronously from Statsig's servers. Go to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) to learn more and see example usage. ## FAQs #### Does the SDK use the browser local storage or cookies? If so, for what purposes? The SDK doesn't use any cookies. It does use local storage for feature targeting and experimentation purposes only. The SDK caches values for feature gates, dynamic configs, and experiments in local storage as a backup if your website/app can't reach the Statsig server to fetch the latest values. If the SDK logged events but couldn't send them to the Statsig server because of issues like network failure, Statsig also saves them in local storage and sends them again when the network restores. #### How do I run experiments for logged out users? Go to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ## Additional resources - [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview) - [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions) - [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) - [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging) ================================================================================ # React Native On-Device Evaluation URL: https://docs.statsig.com/client/ReactNativeOnDeviceEvaluation ================================================================================ # React Native On-Device Evaluation - **Package:** `@statsig/react-native-bindings-on-device-eval` ([npm](https://www.npmjs.com/package/@statsig/react-native-bindings-on-device-eval)) - **Latest version:** 3.33.7 - **Repository:** [js-client-monorepo](https://github.com/statsig-io/js-client-monorepo) > **Info:** > > **Tip:** Get started quickly with one of the [sample apps](https://github.com/statsig-io/js-client-monorepo/tree/main/samples)! > **Info:** > > Statsig recommends its normal (remote evaluation) SDKs for most client applications. Understand the use case and privacy risks by reading the [On-Device Eval SDK overview](https://docs.statsig.com/client/onDeviceOverview). On-device evaluation SDKs are for Enterprise & Pro Tier only. These SDKs use a different paradigm than their precomputed counterparts ([JS](https://docs.statsig.com/client/javascript-sdk), [Android](https://docs.statsig.com/client/Android), [iOS](https://docs.statsig.com/client/iosClientSDK)). Rather than requiring a user upfront, you can check gates/configs/experiments for any set of user properties. You can do this because the SDK downloads a complete representation of your project and evaluates checks in real time. ### Pros - No network request needed when changing user properties: check the gate/config/experiment locally - Can bring your own CDN or synchronously initialize with a preloaded project definition - Lower latency to download configs cached at the edge, rather than evaluated for a given user (which can't be cached as much) ### Cons - The client has access to the entire project definition: your client key exposes the names and configurations of all experiments and feature flags. Refer to [client key with server permission best practices](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions). - Payload size is strictly larger than what the traditional SDKs require - Evaluation performance is slightly slower - rather than looking up the value, the SDK must actually evaluate targeting conditions and an allocation decision - Doesn't support ID list segments with > 1000 IDs - Doesn't support IP or User Agent based checks (Browser Version/Name, OS Version/Name, IP, Country) > **Note:** > > Since `@statsig/react-native-bindings-on-device-eval` works in conjunction with `@statsig/js-on-device-eval-client`, documentation on the [JavaScript On-Device Evaluation SDK](https://docs.statsig.com/client/jsOnDeviceEvaluationSDK) is also relevant for React Native implementations. ## Set up the SDK 1. **Install the SDK** ## Installation Statsig uses a multi-package strategy. Install both the Statsig client and the React Native specific bindings. #### npm ```shell npm install @statsig/react-native-bindings-on-device-eval ``` #### yarn ```shell yarn add @statsig/react-native-bindings-on-device-eval ``` ### Peer dependencies The `@statsig/react-native-bindings-on-device-eval` package has peer dependencies which you may also need to install if they aren't already in your project. #### npm ```shell npm install @react-native-async-storage/async-storage ``` #### yarn ```shell yarn add @react-native-async-storage/async-storage ``` 2. **Initialize the SDK** Initialize the SDK with a client SDK key from the ["API Keys" tab on the Statsig console](https://console.statsig.com/api_keys). These keys are safe to embed in a client application. Along with the key, pass in a [User Object](#statsig-user) with the attributes you'd like to target later on in a gate or experiment. > **Warning:** > > For On-Device Evaluation, you need to add the **"Allow Download Config Specs"** scope. Client keys can't download the project definition for on-device evaluation by default. > > While client keys are safe to include, always keep Server and Console keys private. #### How to add the scope #### New SDK Keys When creating a new client key, select **"Allow Download Config Specs"** ![Add DCS Scope to New Key](https://docs.statsig.com/images/local-eval/new-keys.png) #### Existing SDK Keys To add the scope to an existing key, under **Project Settings** → **API Keys** → **Client API Keys**, select **Actions** → **Edit Scopes**, and select **"Allow Download Config Specs"**, then **Save**. ![Add DCS Scope to Existing Key](https://docs.statsig.com/images/local-eval/existing-keys.png) ## React Native specific setup To set up Statsig in a React Native component tree, use the RN-specific `StatsigProviderOnDeviceEvalRN`. `StatsigProviderOnDeviceEvalRN` automatically switches the SDK's storage layer, using [AsyncStorage](https://github.com/react-native-async-storage) instead of LocalStorage (which is unavailable in RN environments). ```tsx import { StatsigProviderOnDeviceEvalRN, useFeatureGate, } from '@statsig/react-native-bindings-on-device-eval'; function Content() { const gate = useFeatureGate('a_gate'); return <div>Reason: {gate.details.reason}</div>; // Reason: Network or NetworkNotModified } function App() { return ( <StatsigProviderOnDeviceEvalRN sdkKey={YOUR_CLIENT_KEY} loadingComponent={<Text>...</Text>} > <Content /> </StatsigProviderOnDeviceEvalRN> ); } ``` ## Working with the SDK ## Set up a StatsigUser To interact with the SDK, you need to create a `StatsigUser` object. You can find the full definition of this object in the [StatsigUser reference](#statsig-user). ```typescript const myUser = { userID: "a-user", email: "user@statsig.com" }; ``` ## React hooks ### useGateValue or useFeatureGate ```typescript import { useGateValue } from '@statsig/react-native-bindings-on-device-eval'; const gateValue = useGateValue('a_gate', { userID: "a-user" }); // <-- Returns the boolean value if (gateValue) { // } ``` ```typescript import { useFeatureGate } from '@statsig/react-native-bindings-on-device-eval'; const gate = useFeatureGate('a_gate', { userID: "a-user" }); // <-- Returns the FeatureGate object if (gate.value) { // } ``` ### useDynamicConfig ```typescript import { useDynamicConfig } from '@statsig/react-native-bindings-on-device-eval'; function MyComponent() { const config = useDynamicConfig('a_config', { userID: 'a-user' }); // <-- Returns the DynamicConfig object const bgColor = config.value['bg_color'] as string; return <View style={{backgroundColor: bgColor}}></View>; } ``` ### useExperiment ```typescript import { useExperiment } from '@statsig/react-native-bindings-on-device-eval'; function MyComponent() { const experiment = useExperiment('an_experiment', { userID: 'a-user' }); // <-- Returns the Experiment object const bgColor = experiment.value['bg_color'] as string; return <View style={{backgroundColor: bgColor}}></View>; } ``` ### useLayer ```typescript import { useLayer } from '@statsig/react-native-bindings-on-device-eval'; function MyComponent() { const layer = useLayer('a_layer', { userID: 'a-user' }); // <-- Returns the Layer object const bgColor = layer.getValue('bg_color') as string; return <View style={{backgroundColor: bgColor}}></View>; } ``` ### Code examples The repository includes working sample apps: - [React Native Examples](https://github.com/statsig-io/js-client-monorepo/tree/main/samples) ### Logging custom events ### Logging an event After setting up a Feature Gate or Experiment, you may want to track custom events to see how new features or different experiment groups affect those events. Call the Log Event API for the event. You can also provide a value and metadata object to log with the event: ```typescript import type { StatsigEvent } from '@statsig/client-core'; // log a simple event myStatsigClient.logEvent('my_simple_event'); // or, include more information by using a StatsigEvent object const myEvent: StatsigEvent = { eventName: 'add_to_cart', value: 'SKU_12345', metadata: { price: '9.99', item_name: 'diet_coke_48_pack', }, }; myStatsigClient.logEvent(myEvent); ``` ### Flushing logged events `flush()` sends queued events immediately. Use `shutdown()` when your app is exiting. ```typescript await myStatsigClient.flush(); ``` ## Statsig User You need to provide a StatsigUser object to check/get your configurations. Pass as much information as possible to take advantage of advanced gate and config conditions. Most of the time, you need the `userID` field to provide a consistent experience for a given user (refer to [logged-out experiments](https://docs.statsig.com/guides/first-device-level-experiment) to understand how to correctly run experiments for logged-out users). Besides `userID`, Statsig also supports `email`, `ip`, `userAgent`, `country`, `locale` and `appVersion` as top-level fields on StatsigUser. In addition, you can pass any key-value pairs in an object/dictionary to the `custom` field and create targeting based on them. After the user logs in or their attributes change, call `updateUser` with the updated `userID` and any other updated user attributes: > **Note:** > > For the React Native On-Device Evaluation SDK, you pass the `StatsigUser` object directly into each evaluation method (`checkGate`, `getConfig`, etc.) rather than during initialization. > **Note:** > > Unlike precomputed evaluation SDKs, the on-device evaluation SDK doesn't have an `updateUser` method since it evaluates gates/configs/experiments in real-time for any user object you pass in. ## Client event emitter You can subscribe to StatsigClientEvents (not to be confused with [StatsigEvent](#logging-an-event)). These events occur at various stages while using the Statsig client. Subscribe to specific events by specifying the StatsigClientEvent name, or subscribe to all events by using the wildcard token `'*'`. ```typescript import type { AnyStatsigClientEvent, StatsigClientEvent, StatsigClientEventCallback, } from '@statsig/client-core'; const onAnyClientEvent = (event: AnyStatsigClientEvent) => { console.log("Any Client Event", event); }; const onLogsFlushed = (event: StatsigClientEvent<'logs_flushed'>) => { console.log("Logs", event.events); }; // subscribe to an individual StatsigClientEvent myStatsigClient.on('logs_flushed', onLogsFlushed); // or, subscribe to all StatsigClientEvents myStatsigClient.on('*', onAnyClientEvent); // then later, unsubscribe from the events myStatsigClient.off('logs_flushed', onLogsFlushed); myStatsigClient.off('*', onAnyClientEvent); ``` You can find the [full list of events and descriptions](https://github.com/statsig-io/js-client-monorepo/blob/main/packages/client-core/src/StatsigClientEventEmitter.ts). ## Statsig Options You can configure SDK behavior by passing a `StatsigOptions` object during initialization. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | The API to use for all SDK network requests. You shouldn't need to override this unless you have another API that implements the Statsig API endpoints. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | The URL used to flush queued events through a POST request. Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventBeaconUrl | string | No | — | The URL used to flush queued events through `window.navigator.sendBeacon` (web only). Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | downloadConfigSpecsUrl | string | No | — | The URL used to fetch your latest Statsig specifications. Takes precedence over `StatsigOptions.api`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | An object you can use to set environment variables that apply to all of your users in the same session. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideStableID | string | No | — | Overrides the auto-generated stableID that Statsig sets for the device. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logLevel | LogLevel | No | — | How much information the SDK prints to the console. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | SpecsDataAdapter | No | — | Implementing this type allows customization of the initialization. Refer to [Using SpecsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) for details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | networkTimeoutMs | number | No | — | The maximum amount of time (in milliseconds) that any network request can take before timing out. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingBufferMaxSize | number | No | — | The maximum number of events to batch before flushing logs to Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | — | How often (in milliseconds) to flush logs to Statsig. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrideAdapter | OverrideAdapter | No | — | An implementor of `OverrideAdapter` that alters evaluations before returning them to the caller of a check api (checkGate/getExperiment etc). | ## Manual exposures > **Warning:** > > Manual logging is error-prone and can often introduce issues like uneven exposures, which compromise experiment results. You can query your gates/experiments without triggering an exposure, and manually log the exposures later: ### Gates ```typescript // Check gate with exposure disabled const result = myStatsigClient.checkGate('a_gate_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.checkGate('a_gate_name', { user }); ``` ### Configs ```typescript // Get config with exposure disabled const config = myStatsigClient.getConfig('a_dynamic_config_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.getConfig('a_dynamic_config_name', { user }); ``` ### Experiments ```typescript // Get experiment with exposure disabled const experiment = myStatsigClient.getExperiment('an_experiment_name', { user, disableExposureLog: true }); // Manually log the exposure myStatsigClient.getExperiment('an_experiment_name', { user }); ``` ### Layers ```typescript // Get layer with exposure disabled const layer = myStatsigClient.getLayer('a_layer_name', { user, disableExposureLog: true }); const paramValue = layer.get('a_param_name', 'fallback_value'); // Manually log the exposure const layer = myStatsigClient.getLayer('a_layer_name', { user }); const paramValue = layer.get('a_param_name', 'fallback_value'); ``` ## Lifecycle & advanced usage ## Shutting Statsig down The SDK keeps event logs in the client cache and flushes them periodically to save data and battery usage. Because the SDK flushes only periodically, it may not have flushed some events when your app shuts down. To ensure the SDK flushes or saves all logged events locally, shut down Statsig when your app is closing: ```typescript await myStatsigClient.shutdown(); ``` ## Data adapter The `EvaluationsDataAdapter` type defines how the `StatsigClient` fetches and caches data during initialize and update operations. By default, the `StatsigClient` uses `StatsigEvaluationsDataAdapter`, which fetches data synchronously from local storage and asynchronously from Statsig's servers. Refer to [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) for details and example usage. ## Additional resources - [On-Device Evaluation SDK Overview](https://docs.statsig.com/client/onDeviceOverview) - [JavaScript On-Device Evaluation SDK](https://docs.statsig.com/client/jsOnDeviceEvaluationSDK) - [Client Keys with Server Permissions](https://docs.statsig.com/access-management/api-keys#client-keys-with-server-permissions) - [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) - [Debugging SDK Evaluations](https://docs.statsig.com/sdks/debugging) ================================================================================ # Migrating to @statsig/js-client URL: https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient ================================================================================ # Migrating to @statsig/js-client > **Warning:** > > ### Deprecated > > Migrate soon! Official support for statsig-js ended Jan 31, 2025. The updated SDK retains the architecture and most APIs. However, some modifications address common pitfalls, resolve existing issues, and streamline the SDK logic, resulting in some breaking changes. ## Breaking changes - The SDK now offers both a synchronous and asynchronous [initialization](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#initialization) and [updateUser](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#updating-the-user) methods. - The "getConfig" method has [changed to "getDynamicConfig"](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#getconfig-is-now-getdynamicconfig) - When Bootstrapping, you now [pass the hash parameter as 'djb2'](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#bootstrapping) - The top-level static instance has moved to a static method, [StatsigClient.instance()](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#static-instance) - Overrides have moved into their own package: [js-local-overrides](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#overrides) - Parameters for GDPR compliance have [changed and been centralized](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#gdpr) - The method to retrieve a stableID [has changed](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#stableid-and-getstableid) - The structure of [cached values has changed](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#cached-values), with implications on first-run experience - Several StatsigOptions [have changed](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient#legacy-statsigoptions) - Statsig has deprecated the manual exposure logging methods (`getExperimentWithExposureLoggingDisabled`, `checkGateWithExposureLoggingDisabled`). The checkGate and getExperiment methods now support a second argument that [disables exposure logging](https://docs.statsig.com/client/javascript-sdk/#manual-exposures). ### Initialization Previously, the SDK used a single method for initialization. Because waiting for a method call during app startup can be impractical, the new SDK provides two distinct initialization approaches: one synchronous and one asynchronous. Synchronous initialization uses cache (if available) and returns immediately. The SDK then fetches data for subsequent sessions in the background. Asynchronous initialization is awaitable and ensures the SDK fetches and uses the most current data. #### statsig-js (Legacy) ```typescript import Statsig from "statsig-js"; // initialize returns a promise which always resolves await Statsig.initialize( "client-sdk-key", { userID: "some_user_id" }, { environment: { tier: "staging" } } // optional, pass options here if needed ); ``` #### New - Async ```typescript import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient( 'client-sdk-key', { userID: 'some_user_id' }, { environment: { tier: 'staging' } } ); // Async - waits for latest values await client.initializeAsync(); ``` #### New - Sync ```typescript import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient( 'client-sdk-key', { userID: 'some_user_id' }, { environment: { tier: 'staging' } } ); // Sync - uses cache, fetches in background client.initializeSync(); ``` > **Tip:** > > View a full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/precomputed-client/sample-precomp-initialize.tsx) or read more about StatsigClient initialization [here](https://docs.statsig.com/client/javascript-sdk#initialize-the-sdk). ### getConfig is now getDynamicConfig Update your `getConfig` call sites to call the new method, `getDynamicConfig`. In addition, `DynamicConfig` and `Layer` are no longer classes but JavaScript objects. Convenience `get` methods remain unchanged. ```js // old statsig.getConfig('config_name'); // new statsigClient.getDynamicConfig('config_name'); ``` ### Bootstrapping When bootstrapping from a server SDK, update how the server SDK generates values. The new `js-client` SDK uses a `djb2` hash instead of `sha256` for hashing gate/experiment names. By default, all server SDKs generate `sha256` hashes in the `getClientInitializeResponse` method. Set the hash algorithm parameter to `"djb2"` to bootstrap the new client SDK. This change also reduces the overall payload size, benefiting package size and speed. This doesn't change any bucketing logic, only the obfuscation method used for the payload. For example, if you're bootstrapping from a nodejs app, you need to: ```js statsig.getClientInitializeResponse( user, '[client-key]', { hash: 'djb2', }, ); ``` ### Updating the user Similar to initialization, the `updateUser` method now supports both synchronous and asynchronous approaches, working the same way as the corresponding initialization approach. #### statsig-js (Legacy) ```typescript import Statsig from "statsig-js"; const user = { userID: "a-user" }; await Statsig.updateUser(user); ``` #### New - Async ```typescript import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient('client-sdk-key', { userID: 'initial-user' }); await client.initializeAsync(); // Update to new user - async const newUser = { userID: 'a-user' }; await client.updateUserAsync(newUser); ``` #### New - Sync ```typescript import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient('client-sdk-key', { userID: 'initial-user' }); client.initializeSync(); // Update to new user - sync const newUser = { userID: 'a-user' }; client.updateUserSync(newUser); ``` > **Tip:** > > View a full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/precomputed-client/sample-precomp-update-user.tsx) ## Static instance In the previous SDK version, there was a top-level static interface for using Statsig. To improve support for multiple instances, a static method that retrieves an instance now replaces it. #### statsig-js (Legacy) ```typescript import Statsig from "statsig-js"; await Statsig.initialize(YOUR_CLIENT_KEY, { userID: 'a-user' }); // then later, at some other location in your code base if (Statsig.checkGate('a_gate')) { // do something... } ``` #### New ```typescript import { StatsigClient } from '@statsig/js-client'; // Initialize once in your app const client = new StatsigClient(YOUR_CLIENT_KEY, { userID: 'a-user' }); await client.initializeAsync(); // then later, at some other location in your code base const instance = StatsigClient.instance(YOUR_CLIENT_KEY); if (instance.checkGate('a_gate')) { // do something... } ``` > **Tip:** > > View a full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/precomputed-client/sample-precomp-static-instance.tsx) or read more about StatsigClient multi-instance support [here](https://docs.statsig.com/client/javascript-sdk#multiple-client-instances). ## Overrides Previously, the client had top-level methods for managing overrides for gates/configs/experiments/layers. Statsig removed this functionality from the main SDK and moved it to its own package. You can implement your own overrides, or use `@statsig/js-local-overrides` and set it as the local override adapter in `StatsigOptions`. ```plaintext import { StatsigClient } from '@statsig/js-client'; import { LocalOverrideAdapter } from '@statsig/js-local-overrides'; const overrideAdapter = new LocalOverrideAdapter(); overrideAdapter.overrideGate('gate_a', false); overrideAdapter.overrideGate('gate_b', true); const client = new StatsigClient( DEMO_CLIENT_KEY, { userID: 'a-user' }, { overrideAdapter, }, ); ``` Full example here: https://github.com/statsig-io/js-client-monorepo/blob/0e7201635f71e77633de04c4c19c1006030a3a81/samples/next-js/src/app/override-adapter-example/OverrideAdapterExample.tsx#L14 ## GDPR In consent management use cases, you must suspend cache and network usage until the user grants specific permissions. Previously, the approach was fragmented. The new SDK consolidates these settings for consistency and ease of implementation. #### statsig-js (Legacy) ```typescript // start the SDK without storage or logging Statsig.initialize( 'client-key', { userID: 'a_user' }, { disableAllLogging: true, disableLocalStorage: true }, ); // then, once permission was granted Statsig.shutdown(); Statsig.initialize( 'client-key', { userID: 'a_user' }, { disableAllLogging: false, disableLocalStorage: false }, ); // or, by manually flipping the related flags Statsig.reenableAllLogging(); StatsigLocalStorage.disabled = false; ``` #### New ```typescript import { StatsigClient } from '@statsig/js-client'; // start the SDK without storage or logging const client = new StatsigClient( 'client-key', { userID: 'a_user' }, { disableLogging: true, disableStorage: true, networkConfig: { preventAllNetworkTraffic: true }, } ); await client.initializeAsync(); // then, once permission was granted client.updateRuntimeOptions({ disableLogging: false, disableStorage: false, networkConfig: { preventAllNetworkTraffic: false }, }); ``` > **Tip:** > > View a full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/precomputed-client/sample-precomp-gdpr.tsx) ## stableID and getStableID `statsig.getStableID()` no longer exists. You can get the stableID like this: `myStatsigClient.getContext().stableID` The key for the stableID in local storage has changed. The new key is a function of the SDK key used to initialize the SDK, which allows multiple SDK instances to coexist on a single page without overlapping cached data. To keep the existing stableID, access it in local storage from the old key `STATSIG_LOCAL_STORAGE_STABLE_ID` and set it in `customIDs` to override the stableID. ## Cached values The structure of cached values has changed significantly, and there is no supported migration path from the old format to the new format. To pre-populate cached values, run the new SDK without issuing checks against it for some time before switching to use it for all checks. ## Legacy StatsigOptions The options for parameterizing SDK initialization have changed. In some cases, Statsig removed or moved the underlying features, and you can enable or disable them in a different way. In other cases, there is a new API for managing them. The following maps old options to their equivalents in the new SDK. #### disableErrorLogging > This feature doesn't exist in the new Javascript SDK, so there is no option to disable it. #### disableAutoMetricsLogging > Moved to optional package [`@statsig/web-analytics`](https://www.npmjs.com/package/@statsig/web-analytics) #### disableAllLogging > This is now `StatsigOptions.disableLogging` #### disableCurrentPageLogging > This is now `StatsigOptions.includeCurrentPageUrlWithEvents` #### disableLocalStorage > This is now `StatsigOptions.disableStorage` #### localMode > This is now `StatsigOptions.networkConfig.preventAllNetworkTraffic` #### loggingIntervalMillis > This is now `StatsigOptions.loggingIntervalMs` #### loggingBufferMaxSize > Unchanged #### environment > Unchanged #### disableNetworkKeepalive > Statsig completely removed this. Control network requests with `StatsigOptions.networkConfig.networkOverrideFunc`. #### api > This is now `StatsigOptions.networkConfig.api` #### overrideStableID > stableID is now just part of `StatsigUser.customIDs`. This brings it inline with Statsig server SDKs and helps avoid mis-configuration between client and server #### initTimeoutMs > Timeouts now live as part of the `async` call. > > eg: `myStatsigClient.initializeAsync(1000); // 1 sec timeout` #### initializeValues > Replaced by the usage of [StatsigEvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) #### eventLoggingApi > Replaced by `StatsigOptions.networkConfig.logEventUrl` #### prefetchUsers > Replaced by the usage of [StatsigEvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) #### initCompletionCallback > Replaced by the usage of [StatsigClientEventEmitter](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) ```js statsigClient.on('values_updated', function(evt) { if(evt.status && evt.status === 'Ready') { /* client has initialized */ } }); ``` #### updateUserCompletionCallback > Replaced by the usage of [StatsigClientEventEmitter](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) #### fetchMode > Replaced by the usage of [StatsigEvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter) #### disableDiagnosticsLogging > There currently is no diagnostics logging in the new SDK #### initRequestRetries > Statsig completely removed this. Control network requests with `StatsigOptions.networkConfig.networkOverrideFunc`. #### ignoreWindowUndefined > No longer applicable #### disableHashing > This is now StatsigOptions.networkConfig.initializeHashAlgorithm #### logLevel > Statsig hasn't changed this, but the enum values are no longer `UPPERCASED`. #### logger > Not yet supported #### evaluationCallback > Replaced by the usage of [StatsigClientEventEmitter](https://docs.statsig.com/client/javascript-sdk#client-event-emitter) ================================================================================ # Migrating to @statsig/react-bindings URL: https://docs.statsig.com/client/migration-guides/MigrationFromOldReact ================================================================================ # Migrating to @statsig/react-bindings > **Warning:** > > ### Deprecated > > Migrate soon! Official support for statsig-react ended Jan 31, 2025. > **Note:** > > Also refer to the [migration from js-client guide](https://docs.statsig.com/client/migration-guides/MigrationFromOldJsClient), which lists other impacts on statsig-react installations. Breaking changes: - The [initialization pattern](https://docs.statsig.com/client/migration-guides/MigrationFromOldReact#initialize) has changed, along with [waitForInitialization and initializeComponent](https://docs.statsig.com/client/migration-guides/MigrationFromOldReact#waitforinitialization-and-initializingcomponent). - Bootstrapping has changed, now requiring a new hashing parameter: [Bootstrapping the StatsigClient](https://docs.statsig.com/client/migration-guides/MigrationFromOldReact#bootstrapping-the-statsigclient). ### Initialize In the old `statsig-react` package, you had to give all values to the StatsigProvider, which internally set up the Statsig client instance. This approach caused issues in managing state between the Statsig client and the StatsigProvider, making it fragile and likely to break if you used the Statsig client directly. The new approach runs everything through the Statsig client instance and passes it to the StatsigProvider. #### statsig-react (Legacy) ```jsx import { StatsigProvider } from "statsig-react"; function App() { return ( <StatsigProvider sdkKey="<STATSIG_CLIENT_SDK_KEY>" user={{ userID: "a-user" }} waitForInitialization={true} // StatsigOptions (Not Required) options={{ environment: { tier: "staging" }, }} > <div className="App">{/* Rest of App ... */}</div> </StatsigProvider> ); } ``` #### New ```tsx import { StatsigProvider } from '@statsig/react-bindings'; import { StatsigClient } from '@statsig/js-client'; // Create the client const client = new StatsigClient( '<STATSIG_CLIENT_SDK_KEY>', { userID: 'a-user' }, { environment: { tier: 'staging' }, } ); function App() { return ( <StatsigProvider client={client} loadingComponent={<div>Loading...</div>}> <div className="App">{/* Rest of App ... */}</div> </StatsigProvider> ); } ``` > **Tip:** > > View the full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/react-precomp/sample-react-precomp-initialize.tsx) ### waitForInitialization and initializingComponent In older versions of the `StatsigProvider`, you could set `waitForInitialization` to block children from rendering until the SDK fetched the latest values from Statsig. When you set `initializeComponent`, the SDK displayed that component while fetching values. You could also set `waitForInitialization` to `false`, causing the StatsigProvider to render immediately before values were ready. Statsig didn't recommend this because values could change between checks, resulting in unexpected layout changes. **Where did waitForInitialization go?** The newer `StatsigProvider` removes this option to prevent developers from unintentionally allowing values to change mid-session. You can still replicate the `waitForInitialization=false` behavior, but Statsig doesn't recommend it. Go to the [Initialization Strategies](https://docs.statsig.com/client/concepts/initialize) guide to learn how to replicate that behavior and for recommended synchronous initialization approaches. ### Bootstrapping the StatsigClient When bootstrapping the Statsig Client in your React app from a Statsig Server SDK, you may need to update how the server SDK generates values. The `@statsig/js-client` SDK uses a `djb2` hash instead of `sha256` for hashing gate/experiment names. This doesn't change any bucketing logic, only the obfuscation method used for the payload. By default, all server SDKs generate `sha256` hashes in the `getClientInitializeResponse` method. Set the hash algorithm parameter to `"djb2"` to bootstrap the new client SDK. This change also reduces the overall payload size, which benefits package size and speed. For example, if you bootstrap from the Statsig Node SDK: ```js statsig.getClientInitializeResponse( user, '[client-key]', { hash: 'djb2', // <- New Hashing Algorithm }, ); ``` ### Updating the user #### statsig-react (Legacy) ```jsx import { useContext, useState } from "react"; import { StatsigUser, StatsigProvider, StatsigContext } from "statsig-react"; function UpdateUserButton() { const { updateUser } = useContext(StatsigContext); return <button onClick={() => updateUser({ userID: "b-user" })}>Update</button> } function App() { const [user, setUser] = useState<StatsigUser>({ userID: "a-user" }); return ( <StatsigProvider sdkKey="<STATSIG_CLIENT_SDK_KEY>" user={user} setUser={setUser} > <UpdateUserButton /> </StatsigProvider> ); } ``` #### New ```tsx import { StatsigProvider, useClientAsyncInit } from '@statsig/react-bindings'; import { StatsigClient } from '@statsig/js-client'; const client = new StatsigClient('<STATSIG_CLIENT_SDK_KEY>', { userID: 'a-user' }); function UpdateUserButton() { const { client } = useClientAsyncInit(client); const handleUpdate = async () => { await client.updateUserAsync({ userID: 'b-user' }); }; return <button onClick={handleUpdate}>Update</button>; } function App() { return ( <StatsigProvider client={client}> <UpdateUserButton /> </StatsigProvider> ); } ``` > **Tip:** > > View the full example on [GitHub](https://github.com/statsig-io/js-client-monorepo/blob/main/samples/react/src/samples/react-precomp/sample-react-precomp-update-user.tsx) ================================================================================ # Server Core Overview URL: https://docs.statsig.com/server-core ================================================================================ # Server Core Overview ## Statsig Server Core Statsig Server Core is the second generation of Server SDKs. Server Core is a full rewrite built on a shared, performance-focused core library that improves performance and feature maturity across all Server SDKs. Server Core SDKs include: - **Faster evaluation**: A shared Rust evaluation engine that evaluates 3-5x faster than native code SDKs. - **Better non-evaluation performance**: More efficient network and CPU usage, plus ongoing performance optimizations. - **Features new to Server SDKs**: Parameter Stores, Contextual Multi-Armed Bandits, and more. - **Additional capabilities**: Observability Interface, streaming config changes (from the Statsig Forward Proxy), and more. ### Availability across SDKs Server Core SDKs are available on an opt-in basis, with native SDKs still available and supported in all languages. If you are new to Statsig, use a Server Core SDK when convenient. Statsig continues to apply bug fixes to [Legacy SDKs](https://docs.statsig.com/server-core/legacy-sdks) until it announces end-of-support dates. Statsig provides migration guidance at that time. | SDK | Status | Package | Migration Guide | | --- | --- | --- | --- | | [Node](https://docs.statsig.com/server-core/node-core) | Stable | [npm](https://www.npmjs.com/package/@statsig/statsig-node-core) | [Link](https://docs.statsig.com/server-core/migration-guides/node) | | [Python](https://docs.statsig.com/server-core/python-core) | Stable | [PyPI](https://pypi.org/project/statsig-python-core/) | [Link](https://docs.statsig.com/server-core/migration-guides/python) | | [Java](https://docs.statsig.com/server-core/java-core) | Stable | [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore/overview) | [Link](server-core/migration-guides/java) | | [PHP](https://docs.statsig.com/server-core/php-core) | Stable | [Packagist](https://packagist.org/packages/statsig/statsigsdk) | | | [Rust](https://docs.statsig.com/server-core/rust-core) | Stable | [Crates.io](https://crates.io/crates/statsig-rust) | | | [Elixir](https://docs.statsig.com/server-core/elixir-core) | Stable | | | | [C++](https://docs.statsig.com/server-core/cpp-core) | Stable | | | | [.NET](https://docs.statsig.com/server-core/dotnet-core) | Stable | [NuGet](https://www.nuget.org/packages/Statsig.Dotnet) | | | Ruby | In Development | | | | [Go](https://docs.statsig.com/server-core/go-core) | Stable | | | ### Technical differences **Build process:** Statsig Server Core uses a core library written in Rust, with bindings for other languages. In most cases, the development experience is unchanged and performance is superior. Because the Rust code must compile into a binary compatible with your development and deployment environments, consider the following: - **Choosing the right build**: In most cases, the SDK's package manager automatically installs the correct version. The exception is Java, where the SDK prints the correct build if it isn't included at runtime. - **Managing lockfiles**: If your deployment and development environments require different builds (which is common), include both versions in a lockfile such as `package-lock.json`. - **Untested environments**: Certain environments, such as the edge, aren't compatible with this build process. Use [native SDKs](https://docs.statsig.com/server-core/legacy-sdks) in those cases. **New Configuration Spec:** Server Core uses a smaller "ruleset", or configuration spec. If you use the spec directly, your logic and parsing must change. **Event Logging** Server Core SDKs, starting in v0.4.0, use a new event logging architecture. During normal operation, events stream to Statsig servers. During outages on the event logging endpoint, the SDK throttles or drops events to allow the service to start healthy before processing steady-state traffic. The following parameters tune this behavior: ```plaintext - event_logging_max_queue_size: Controls batch size (default 2000). Note that exceeding the backend request size limit (10MB) will drop requests - event_logging_max_pending_batch_queue_size: Controls max pending batches (default: 20). The tradeoff here is increased memory usage to buffer events when requests fail if you increase it, and losing additional events if you decrease it - disable_all_logging: Completely disables event logging ``` ```plaintext +----------------+ +----------------+ +----------------+ | Event Sources | | Event Queue | | Flush Triggers | |----------------| |----------------| |----------------| | - Gate Checks |---->| - Pending | | - Scheduled | | - Config Reads | | Events | | (Time-based) | | - Custom Events| | - Batches |<----| - Manual | +----------------+ +----------------+ | - Shutdown | | +----------------+ v +----------------+ | Flush Process | |----------------| | - Batch Events | | - Send to API | | - Process | | Response | +----------------+ / \ / \ v v +---------------------------+---------------------------+ | On Request Failure | On Request Success | |---------------------------|---------------------------| | - Double interval | - Halve interval | | (max: 60000ms) | (min: 1000ms) | | - Retry errors | - No specific limit | | up to 5 times | flush mechanism | +---------------------------+---------------------------+ ``` ### Support If you have trouble with a Server Core SDK, share your feedback in [Slack](https://statsig.com/slack). ================================================================================ # Node Server SDK URL: https://docs.statsig.com/server-core/node-core ================================================================================ # Node Server SDK - **Package:** `@statsig/statsig-node-core` ([npm](https://www.npmjs.com/package/@statsig/statsig-node-core)) - **Latest version:** 0.24.0 - **Package size:** 4.2 kB gzip - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-node) > **Tip:** > > Migrating from the legacy Node SDK? Refer to our [Migration Guide](https://docs.statsig.com/server-core/migration-guides/node). ## Set up the SDK 1. **Install the SDK** ```shell npm i @statsig/statsig-node-core ``` The Node SDK is pre-built and compiled for different operating systems and CPU architectures. Package managers resolve the correct version automatically. #### Frozen Lockfile Setup If your service has locked dependencies with package-lock.json or pnpm-lock.yml, include all required platform versions. For example, if you develop locally on macOS and deploy to Linux: ```plaintext dependencies { "@statsig/statsig-node-core-darwin-arm64": "0.1.0" // for macOS "@statsig/statsig-node-core-linux-x64-gnu": "0.1.0" // for linux x64 machines } ``` #### Usage with Next.js/Webpack/esbuild `statsig-node-core` uses native binary files that you can't package with webpack/esbuild. To prevent errors, take the following steps: #### Next.js In your `next.config.js` file, add the `@statsig/statsig-node-core` package to the `serverExternalPackages` array: ```jsx const nextConfig = { serverExternalPackages: ['@statsig/statsig-node-core'], } ``` #### esbuild Add the `--packages=external` flag to your build script: ```shell esbuild --packages=external ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. The optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. ```jsx // Basic initialization import { Statsig, StatsigUser } from '@statsig/statsig-node-core'; //Or, in common JS, const { Statsig, StatsigUser } = require('@statsig/statsig-node-core'); const statsig = new Statsig("secret-key"); await statsig.initialize(); // or with StatsigOptions const options: StatsigOptions = { environment: "staging" }; const statsigWithOptions = new Statsig("secret-key", options); await statsigWithOptions.initialize(); ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). For example: ```jsx const user = new StatsigUser({ userID: "a-user" }); if (statsig.checkGate(user, "a_gate")) { // Gate is on, enable new feature } else { // Gate is off } ``` ### Reading a dynamic config Feature Gates are useful for on/off switches with optional user targeting. To send different values (strings, numbers, and similar types) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a full JSON object configurable on the server, from which you can fetch typed parameters. ```jsx // Get the dynamic config const config = statsig.getDynamicConfig(user, "a_config"); // Get typed values using the getValue() method const itemName = config.getValue("product_name", "Awesome Product v1"); const price = config.getValue("price", 10.0); const shouldDiscount = config.getValue("discount", false); // Or access the entire value object directly const value = config.value; ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available. Statsig recommends [Layers](https://docs.statsig.com/experiments/layers-overview) because they make parameters reusable and support mutually exclusive experiments. ```jsx // Or, via individual experiments const titleExp = statsig.getExperiment(user, "new_user_promo_title"); const priceExp = statsig.getExperiment(user, "new_user_promo_price"); const experimentTitle = titleExp.getValue("title", "Welcome to Statsig!"); const experimentDiscount = priceExp.getValue("discount", 0.1); // Get values via Layer const layer = statsig.getLayer(user, "user_promo_experiments"); const title = layer.getValue("title", "Welcome to Statsig!"); const discount = layer.getValue("discount", 0.1); ``` ### Retrieving feature gate metadata In certain scenarios, you may need more information about a gate evaluation than a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object: ```jsx const gate = statsig.getFeatureGate(statsigUser, "example_gate") console.log(gate.rule_id) console.log(gate.value) ``` ### Parameter stores Use Parameter Stores when you want to define a parameter without deciding whether it should be a Feature Gate, Experiment, or Dynamic Config. Parameter Stores let you change the parameter type at any point in the Statsig console without a new deployment. Parameter Stores are optional, but parameterizing your application provides future flexibility and allows non-technical Statsig users to turn parameters into experiments. ```jsx const paramStore = statsig.getParameterStore(statsigUser, "my_parameters") const paramStoreValue = paramStore.getValue('my_parameter_value') ``` ### Logging an event To track custom events, call the Log Event API. Specify the user, event name, and an optional value or metadata object: ```jsx statsig.logEvent( user, "add_to_cart", null, { price: "9.99", item_name: "diet_coke_48_pack" } ); ``` Learn more about identifying users, group analytics, and best practices for logging events in the [logging events guide](https://docs.statsig.com/guides/logging-events). ### Sending events to Log Explorer You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log. ```jsx const user = new StatsigUser({ userID: "a-user", custom: { service: "my-service", pod: "my-pod", namespace: "my-namespace", container: "my-container", // ...include any service-specific metadata } }); // levels: trace, debug, info, log, warn, error statsig.forwardLogLineEvent(user, "warn", "script failed to load", { cusom_metadata: "script_name:my-script" // ... include any event-specific metadata }); ``` ## Using shared instance To create a single Statsig instance accessible globally throughout your codebase, use the shared instance functionality, which provides a singleton pattern: ```jsx // Create a shared instance that can be accessed globally const statsig = Statsig.newShared("secret-key"); await statsig.initialize(); // Access the shared instance from anywhere in your code const sharedStatsig = Statsig.shared(); const isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name"); // Check if a shared instance exists if (Statsig.hasSharedInstance()) { // Use the shared instance } // Remove the shared instance when no longer needed Statsig.removeShared(); ``` The shared instance helps when multiple parts of your codebase need Statsig without passing an instance between them. - `Statsig.newShared(sdkKey, options)`: Creates a new shared instance of Statsig that you can access globally - `Statsig.shared()`: Returns the shared instance - `Statsig.hasSharedInstance()`: Checks if a shared instance exists (useful when the shared instance may not be ready yet) - `Statsig.removeShared()`: Removes the shared instance (useful when you want to switch to a new shared instance) > **Note:** > > `hasSharedInstance()` and `removeShared()` are helpful in specific scenarios but aren't required in most use cases where the shared instance is set up near the top of your application. > > Also note that only one shared instance can exist at a time. Attempting to create a second shared instance results in an error. ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call get() on a parameter in a layer. To delay exposure logging (for example, to log only after the user actually uses the feature), use manual exposures. All main SDK functions (`checkGate`, `getDynamicConfig`, `getExperiment`, `getLayer`) accept an optional `disableExposureLogging` parameter. When set to `true`, the SDK doesn't automatically log an exposure. You can then log the exposure manually at a later time: #### Feature Gates ```jsx const result = statsig.checkGate(aUser, 'a_gate_name', {disableExposureLogging: true}); ``` ```jsx statsig.manuallyLogGateExposure(aUser, 'a_gate_name'); ``` #### Dynamic Configs ```jsx const config = statsig.getDynamicConfig(aUser, 'a_dynamic_config_name', {disableExposureLogging: true}); ``` ```jsx statsig.manuallyLogDynamicConfigExposure(aUser, 'a_dynamic_config_name'); ``` #### Experiments ```jsx const experiment = statsig.getExperiment(aUser, 'an_experiment_name', {disableExposureLogging: true}); ``` ```jsx statsig.manuallyLogExperimentExposure(aUser, 'an_experiment_name'); ``` #### Layers ```jsx const layer = statsig.getLayer(aUser, 'a_layer_name', {disableExposureLogging: true}); const paramValue = layer.get('a_param_name', 'fallback_value'); ``` ```jsx statsig.manuallyLogLayerParameterExposure(aUser, 'a_layer_name', 'a_param_name'); ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. Complete user information lets you take advantage of advanced gate and config conditions (like country or OS/browser-level checks) and correctly measure the impact of experiments on metrics and events. As explained in [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks), you must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. In addition to userID, the top-level fields on StatsigUser are: email, ip, userAgent, country, locale, and appVersion. You can also pass any key-value pairs in an object or dictionary to the custom field and create targeting based on them. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. They are useful for PII or sensitive data that you don't want to send to third-party services. ```typescript const user = new StatsigUser({ userID: "a-user-id", email: "user@example.com", ip: "192.168.1.1", userAgent: "Mozilla/5.0...", country: "US", locale: "en_US", appVersion: "1.0.0", custom: { // Custom fields plan: "premium", age: 25 }, customIDs: { // Custom ID types stableID: "stable-id-123" }, privateAttributes: { // Private attributes not forwarded to integrations email: "private@example.com" } }); ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions ### Parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | string | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specsUrl | string | No | — | Custom URL for fetching feature specifications. Provide the full endpoint URL, which the SDK uses as-is. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | idListsUrl | string | No | — | Custom URL for fetching the ID list manifest (the `get_id_lists` endpoint). Provide the full endpoint URL, which the SDK uses as-is. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | downloadIdListFileApi | string | No | — | Origin (scheme and host only, no path) for downloading individual ID list files. Unlike `specsUrl` and `idListsUrl`, this takes an origin, not a full endpoint URL: the SDK appends each per-file path from the ID list manifest. Refer to [Routing endpoints through a forward proxy](#routing-endpoints-through-a-forward-proxy). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specsSyncIntervalMs | number | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallbackToStatsig | boolean | No | — | Turn this on if you proxy `download_config_specs` / `get_id_lists` and want to fall back to the default Statsig endpoint to increase reliability. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableAllLogging | boolean | No | — | If true, the SDK doesn't collect any logging within the session, including custom events and config check exposure events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableIdLists | boolean | No | — | Required to be `true` when using segments with more than 1000 IDs. Refer to [ID List segments](https://docs.statsig.com/segments/add-id-list). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableUserAgentParsing | boolean | No | — | If true, the SDK doesn't parse User-Agent strings into `browserName`, `browserVersion`, `systemName`, `systemVersion`, and `appVersion` when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | waitForUserAgentInit | boolean | No | — | When true, the SDK waits until user agent parsing data is fully loaded during initialization (~1 second), ensuring parsing is ready before any evaluations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableUserCountryLookup | boolean | No | — | If true, the SDK doesn't parse IP addresses (from `user.ip`) into country codes when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | waitForCountryLookupInit | boolean | No | — | When true, the SDK waits for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization (~1 second), ensuring IP-to-country parsing is ready at evaluation time. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingFlushIntervalMs | number | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingMaxQueueSize | number | No | — | Maximum number of events to queue before forcing a flush. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataStore | DataStore | No | — | An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network. Refer to [Data Stores](#data-store). For an example, go to the 1P Redis implementation [statsig-node-redis](https://github.com/statsig-io/node-js-server-sdk-redis). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specAdaptersConfig | SpecAdapterConfig[] | No | — | Advanced settings to fetch from different sources (e.g., [statsig forward proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction), your own proxy server, data store) or to use different network protocols (HTTP vs gRPC streaming). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | observabilityClient | ObservabilityClient | No | — | Interface to integrate observability metrics exposed by the SDK (e.g., config propagation delay, initialization time). Refer to [details](#observability-client). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | persistentStorage | PersistentStorage | No | — | Interface to use persistent storage within the SDK. Refer to [details](#persistent-storage). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyConfig | ProxyConfig | No | — | Configuration for connecting through a proxy server. | #### ProxyConfig | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyHost | string | No | — | Proxy server host. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyPort | number | No | — | Proxy server port. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyAuth | string | No | — | Proxy authentication in the form "username:password". | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyProtocol | string | No | — | Protocol (e.g., "http", "https"). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | caCertPath | string | No | — | Optional path to a PEM CA bundle for outbound TLS. | ### Proxy and custom network routing Use `proxyConfig` if your service needs a standard outbound HTTP proxy. Use `specAdaptersConfig` if you are routing spec downloads through [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) or another custom spec source. ```typescript // Example usage: const options: StatsigOptions = { environment: "staging", initTimeoutMs: 3000, proxyConfig: { proxyHost: "proxy.example.com", proxyPort: 8080, // proxyAuth: set if authentication is required proxyProtocol: "https", caCertPath: "/etc/ssl/certs/corporate-ca.pem", }, }; const statsig = new Statsig("secret-key", options); await statsig.initialize(); ``` Set `caCertPath` when your environment requires a custom PEM CA bundle for outbound TLS. ### Routing endpoints through a forward proxy To send Statsig network traffic through your own proxy or CDN, override the endpoint options. These options don't all take the same kind of value: - `specsUrl` and `idListsUrl` take a **full endpoint URL**. The SDK requests each URL as-is. - `downloadIdListFileApi` takes an **origin only** (scheme and host, no path). Per-file download URLs are dynamic. Each one carries a unique file ID and signature embedded in the ID list manifest, so the SDK can't use a fixed URL. Instead, it takes each per-file path from the manifest and appends it to this origin. ```typescript const options: StatsigOptions = { // Full endpoint URLs, used as-is: specsUrl: "https://proxy.example.com/v1/download_config_specs", idListsUrl: "https://proxy.example.com/v1/get_id_lists", // Origin only. The SDK appends each manifest file path: downloadIdListFileApi: "https://proxy.example.com", }; const statsig = new Statsig("secret-key", options); await statsig.initialize(); ``` > **Warning:** > > Set `downloadIdListFileApi` to an origin only, such as `https://proxy.example.com`. If you include a path such as `/v1/download_id_list_file`, the SDK appends the manifest path on top of it, producing a doubled path such as `.../v1/download_id_list_file/v1/download_id_list_file/<fileId>` and a 401 response. Overriding only `specsUrl` and `idListsUrl` routes the ID list manifest through your proxy, but individual ID list **file** downloads still go to the Statsig CDN. Set `downloadIdListFileApi` to route those file downloads through your proxy as well. ## Shutting Statsig down Statsig batches and periodically flushes events. To flush all logged events before shutdown, call `shutdown()` before your app or server shuts down: ```jsx await statsig.shutdown(); ``` ## Client SDK bootstrapping | SSR If you use the Statsig client SDK in a browser or mobile app, you can bootstrap the client SDK with values from the server SDK to avoid a network request on the client. This is useful for server-side rendering (SSR) or to reduce network requests on the client. ## Client initialize response The Node Core SDK provides a method to generate a client initialize response that you can use to bootstrap client SDKs without requiring network requests. ```typescript // Get client initialize response for a user const values = statsig.getClientInitializeResponse(user, options); // Pass values to a client SDK to initialize without a network request ``` #### Initialize Response Options The `getClientInitializeResponse` method accepts an optional `options` parameter with the following properties: ```typescript export interface ClientInitializeResponseOptions { hashAlgorithm?: string; // Algorithm used for hashing gate/experiment names (default: 'djb2') clientSdkKey?: string; // Client SDK key to use for initialization includeLocalOverrides?: boolean; // Whether to include local overrides in the response featureGateFilter?: Set<string>; // Filter to only include specific feature gates experimentFilter?: Set<string>; // Filter to only include specific experiments dynamicConfigFilter?: Set<string>; // Filter to only include specific dynamic configs layerFilter?: Set<string>; // Filter to only include specific layers paramStoreFilter?: Set<string>; // Filter to only include specific parameter stores } ``` #### Hash Algorithm The `hashAlgorithm` option specifies which algorithm to use for hashing gate and experiment names in the client initialize response. The default is `'djb2'` for better performance and smaller payload size. ```typescript // Use djb2 hashing algorithm for better performance const values = statsig.getClientInitializeResponse(user, { hashAlgorithm: 'djb2', }); ``` #### Client SDK Key The `clientSdkKey` option lets you filter the response to only the specific feature gates, experiments, dynamic configs, layers, or parameter stores that a particular client key has access to, effectively letting you apply [target apps](https://docs.statsig.com/sdks/target-apps). ```typescript // Specify a client SDK key const values = statsig.getClientInitializeResponse(user, { clientSdkKey: 'client-key', }); ``` #### Filtering The filter options allow you to reduce the payload size by only including specific feature gates, experiments, dynamic configs, layers, or parameter stores in the response. ```typescript // Only include specific feature gates and experiments const values = statsig.getClientInitializeResponse(user, { featureGateFilter: new Set(['my_gate_1', 'my_gate_2']), experimentFilter: new Set(['my_experiment']), }); ``` #### Include Local Overrides The `includeLocalOverrides` option determines whether to consider [local overrides](#local-overrides) you've set when evaluating each config in the response. ```typescript // Include local overrides in the response const values = statsig.getClientInitializeResponse(user, { includeLocalOverrides: true, }); ``` #### Full Code Example Below is a complete example of using the client initialize response to bootstrap a client SDK. You can parallelize or inline the initialize response data with other requests to your server to eliminate additional round trips and latency. ```typescript // Server-side code import { Statsig, StatsigUser } from '@statsig/node-core'; // Initialize the server SDK await Statsig.initialize('server-secret-key'); // In your API endpoint handler app.get('/statsig-bootstrap', (req, res) => { // Create a user object from the request const user = new StatsigUser({ userID: req.query.userID || '', email: req.query.email, ip: req.ip, userAgent: req.headers['user-agent'], }); // Generate the client initialize response with filters const values = Statsig.getClientInitializeResponse(user, { hashAlgorithm: 'djb2', featureGateFilter: new Set(['onboarding_v2', 'new_checkout']), experimentFilter: new Set(['pricing_experiment']), layerFilter: new Set(['ui_layer']), }); // Return the values to the client res.json({ statsigValues: values }); }); ``` ```typescript // Client-side code using @statsig/js-client import { Statsig } from '@statsig/js-client'; // Fetch bootstrap values from your API const response = await fetch('/statsig-bootstrap'); const { statsigValues } = await response.json(); // Initialize the client SDK with the bootstrap values await Statsig.initialize({ sdkKey: 'client-sdk-key', initializeValues: statsigValues, }); ``` ## SDK event subscriptions The Statsig SDK provides an event subscription system that lets you listen for evaluation events and lifecycle events in real time. This is useful for debugging, analytics, custom logging, and integration with external systems. ### Supported events The SDK supports subscribing to the following evaluation events: - **`gate_evaluated`** - Fired when a feature gate is evaluated for a user - **`dynamic_config_evaluated`** - Fired when a dynamic config is retrieved for a user - **`experiment_evaluated`** - Fired when an experiment is evaluated for a user - **`layer_evaluated`** - Fired when a layer is evaluated for a user - **`specs_updated`** - Fired when the SDK updates its cached specs, including where the specs were loaded from - **`"*"`** - Subscribe to all evaluation events ### SDK event data Each event includes relevant context about the evaluation: - **Gate Evaluated Events** include: `gate_name`, `value` (boolean), `rule_id`, `reason` - **Dynamic Config Events** include: the full `dynamic_config` object with values and metadata - **Experiment Events** include: the full `experiment` object with variant assignment and parameters - **Layer Events** include: the full `layer` object with allocated experiment and parameters - **Specs Updated Events** include `source`, `source_api`, and `values` metadata, where `values.time` is the timestamp of the last update to the project in the Statsig console ### Use cases Event subscriptions are particularly useful for: - **Debugging**: Monitor which features are being evaluated and their results - **Analytics**: Track feature usage patterns and user segments - **Custom Logging**: Send evaluation data to your own logging systems - **Integration**: Forward events to external analytics or monitoring tools - **Testing**: Verify that features are being evaluated as expected ### Best practices - **Clean up subscriptions**: Always unsubscribe when you no longer need to listen for events to prevent memory leaks - **Handle event data carefully**: Event objects may contain sensitive user information depending on your configuration - **Use specific event types**: Subscribe to specific events rather than "\*" when possible for better performance - **Avoid heavy processing**: Keep event handlers lightweight to avoid impacting SDK performance ```javascript const statsig = new Statsig('server-secret-key'); // Subscribe to gate evaluation events const gateSubId = statsig.subscribe('gate_evaluated', (event) => { console.log('Gate evaluated:', { gateName: event.gate_name, value: event.value, ruleId: event.rule_id, reason: event.reason }); }); // Subscribe to dynamic config evaluation events const configSubId = statsig.subscribe('dynamic_config_evaluated', (event) => { console.log('Config evaluated:', { configName: event.dynamic_config.name, values: event.dynamic_config.value }); }); // Subscribe to experiment evaluation events const experimentSubId = statsig.subscribe('experiment_evaluated', (event) => { console.log('Experiment evaluated:', { experimentName: event.experiment.name, groupName: event.experiment.group_name, parameters: event.experiment.value }); }); // Subscribe to layer evaluation events const layerSubId = statsig.subscribe('layer_evaluated', (event) => { console.log('Layer evaluated:', { layerName: event.layer.name, allocatedExperiment: event.layer.allocated_experiment_name, parameters: event.layer.value }); }); // Subscribe to specs updated events const specsUpdatedSubId = statsig.subscribe('specs_updated', (event) => { console.log('Specs updated:', { source: event.data.source, sourceApi: event.data.source_api, projectLastUpdated: event.data.values.time, }); }); // Subscribe to all events const allEventsSubId = statsig.subscribe('*', (event) => { console.log('Event received:', event.event_name, event); }); // Unsubscribe from specific event types statsig.unsubscribe('gate_evaluated'); statsig.unsubscribe('specs_updated'); // Unsubscribe using subscription ID statsig.unsubscribeById(configSubId); // Unsubscribe from all events statsig.unsubscribeAll(); ``` ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing. This is useful for local development or testing when you want to force a specific value without changing the configuration in the Statsig console. #### Feature Gates ```jsx // Overrides the given gate to the specified value Statsig.overrideGate("a_gate_name", true); // Optional third parameter, overrides the gate only for a given ID Statsig.overrideGate("a_gate_name", true, "userID-123"); ``` #### Dynamic Configs ```jsx // Overrides the given dynamic config to the provided value Statsig.overrideDynamicConfig("a_config_name", { key: "value" }); // Optional third parameter, overrides the dynamic config only for a given ID Statsig.overrideDynamicConfig("a_config_name", { key: "value" }, "userID-123"); ``` #### Experiments ```jsx // Overrides the given experiment to the provided value Statsig.overrideExperiment("an_experiment_name", { key: "value" }); // Optional third parameter, overrides the experiment only for a given ID Statsig.overrideExperiment("an_experiment_name", { key: "value" }, "userID-123"); // Overrides the given experiment to a particular groupname Statsig.overrideExperimentByGroupName("an_experiment_name", "a_group_name"); // Alternatively, get the Experiment object for a given groupName const groupExp = statsig.getExperimentByGroupName("pricing_experiment", "premium_group"); const premiumPrice = groupExp.getValue("price", 9.99); ``` #### Layers ```jsx // Overrides the given layer to the provided value Statsig.overrideLayer("a_layer_name", { key: "value" }); // Optional third parameter, overrides the layer only for a given ID Statsig.overrideLayer("a_layer_name", { key: "value" }, "userID-123"); ``` ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups when a user returns. This is useful for client-side A/B testing where users must always receive the same variant. ```typescript export interface PersistentStorage { load: (key: string) => UserPersistedValues | null; save: (key: string, config_name: string, data: StickyValues) => void; delete: (key: string, config_name: string) => void; } export interface StickyValues { value: boolean; json_value: Record<string, unknown>; rule_id: string; group_name: string | null; secondary_exposures: SecondaryExposure[]; undelegated_secondary_exposures: SecondaryExposure[]; config_delegate: string | null; explicit_parameters: string[] | null; time: number; configVersion?: number | undefined; } export type UserPersistedValues = Record<string, StickyValues>; export interface SecondaryExposure { gate: string; gateValue: string; ruleId: string; } ``` ### Usage example ```typescript import { PersistentStorage, StickyValues, UserPersistedValues } from '@statsig/statsig-node-core'; class MyPersistentStorage implements PersistentStorage { private storage = new Map<string, UserPersistedValues>(); constructor() { this.load = this.load.bind(this); this.save = this.save.bind(this); this.delete = this.delete.bind(this); } load(key: string): UserPersistedValues | null { return this.storage.get(key) || null; } save(key: string, config_name: string, data: StickyValues): void { const existing = this.storage.get(key) || {}; existing[config_name] = data; this.storage.set(key, existing); } delete(key: string, config_name: string): void { const existing = this.storage.get(key); if (existing) { delete existing[config_name]; this.storage.set(key, existing); } } getUserPersistedValue(user: StatsigUser, idType: string): UserPersistedValues | null { const storageKey = this.getStorageKey(user, idType); if (storageKey !== null) { return this.load(storageKey); } return null; } private getStorageKey(user: StatsigUser, idType: string): string | null { const lowerCaseIdType = idType.toLowerCase(); if (lowerCaseIdType === "user_id" || lowerCaseIdType === "userid") { const id = user.userID; return id ? `${id}:userID` : null; } else if (user.customIDs) { const id = user.customIDs[idType]; return id ? `$\{id\}:${idType}` : null; } return null; } } ``` > **Note:** > > Statsig added persistent storage support in version 0.6.1 of the Node.js SDK. ## Data store Use a `DataStore` to cache configuration specs and ID lists in Redis or another store you control. The SDK reads cached data during initialization and can keep it updated from Statsig. You implement storage access; the SDK manages cache keys, downloads, and ID-list serialization. ID-list DataStore support is available in `@statsig/statsig-node-core@0.23.2-rc.2610201817`, but not stable version `0.23.2`. Enable `enableIdLists: true` and the ID-list capabilities described here. ### DataStore interface Implement the asynchronous callbacks for your storage client: | Callback | Purpose | | --- | --- | | `initialize()` | Open the storage connection before SDK reads and writes. | | `get(key)` | Read the requested entry and return `{ result, time }`. Return `{}` if the entry is missing. Preserve empty strings and the optional timestamp. | | `set(key, value, time)` | Save the SDK-provided value and optional timestamp under the supplied key. Omit this callback for an adapter that never writes. | | `shutdown()` | Close connections owned by the adapter when the SDK shuts down. | | `supportsFeature(feature)` | Declare support for config specs, ID-list reads, and ID-list writes separately. | | `supportPollingUpdatesFor(key)` | Choose whether scheduled updates read the DataStore or Statsig HTTP. For ID lists, the SDK passes `"id_list_snapshot"`: return `true` to poll the store or `false` to poll HTTP. | | `getBytes(key)` / `setBytes(key, value, time)` | Optional byte-oriented storage callbacks. The string callbacks are sufficient for this example. | ### Configure the adapter Treat keys and values as opaque. Save the values passed to `set` and return them from `get` without changing their contents. You don't need to construct keys, fetch ID-list files, or parse list members. This example wraps an existing cache client. It stores `{result,time}` as JSON and unwraps that envelope when reading. Use the same format in every reader and writer. Use a separate connection per SDK instance, or manage shared connections outside the adapter's lifecycle callbacks. ```typescript import { Statsig, type DataStore, type DataStoreResponse, } from "@statsig/statsig-node-core"; interface AsyncCache { connect(): Promise<unknown>; quit(): Promise<unknown>; get(key: string): Promise<string | null>; set(key: string, value: string): Promise<unknown>; } function createDataStore( cache: AsyncCache, pollCache = true, writeIdLists = false, ): DataStore { return { async initialize() { await cache.connect(); }, async shutdown() { await cache.quit(); }, async get(key): Promise<DataStoreResponse> { const value = await cache.get(key); return value === null ? {} : (JSON.parse(value) as DataStoreResponse); }, async set(key, value, time) { await cache.set(key, JSON.stringify({ result: value, time })); }, async supportsFeature(feature) { if (feature === "id_list_snapshot_write") return writeIdLists; return feature === "config_specs" || feature === "id_list_snapshot"; }, async supportPollingUpdatesFor() { return pollCache; }, }; } async function startClient( key: string, cache: AsyncCache, pollCache = true, writeIdLists = false, ) { const statsig = new Statsig(key, { dataStore: createDataStore(cache, pollCache, writeIdLists), enableIdLists: true, }); const result = await statsig.initialize(); if (!result.isSuccess) { // Application policy: stop rather than wait for background recovery. await statsig.shutdown(); throw new Error("Statsig initialization failed"); } return statsig; } ``` Pass your server SDK key and cache client to `startClient`. Await `statsig.shutdown()` during application shutdown. Keep SDK keys and cached data private, and configure connection timeouts and access controls in your storage client. ### Select a publisher and readers Run one writer service to keep the shared store up to date. With the example adapter, call `startClient(key, cache, false, true)`: initialize from the cache, poll Statsig HTTP for updates, and save supported data back to the store. In application processes, call `startClient(key, cache)` with the same SDK key and cache namespace. These clients initialize from the cache and poll it for updates without writing ID lists. They can still fall back to HTTP if cached data is missing or invalid. The `writeIdLists` argument controls ID-list writes only. The example still implements `set` for configuration specs. For a completely read-only adapter, omit both `set` and `setBytes`. Keep the writer running: the storage service doesn't fetch Statsig updates itself. ### Enable ID-list snapshots and choose polling Use `supportsFeature` to opt into each data type: | Feature | Effect | | --- | --- | | `"config_specs"` | Cache project configuration: gates, configs, experiments, layers, and their rules. | | `"id_list_snapshot"` | Read complete ID-list snapshots from the store. Also requires `enableIdLists: true`. Without this capability, ID lists stay HTTP-backed. | | `"id_list_snapshot_write"` | Allow the SDK to save downloaded ID lists. Defaults to `false` and requires the ID-list read capability as well. | ID-list storage includes a lookup of the available lists and a separate entry for each list's complete membership. The SDK maintains these entries through `get` and `set`; your adapter only stores and retrieves the supplied keys and values. For ID lists, `supportPollingUpdatesFor("id_list_snapshot")` defaults to `true` after read support is enabled. Returning `false` selects HTTP for scheduled updates, but initialization still tries the DataStore first. The example applies one polling choice to both config specs and ID lists. `idListsSyncIntervalMs` controls the ID-list polling interval and defaults to 60 seconds. ### Initialization, refresh, and failure behavior - Missing, invalid, incomplete, or failed ID-list reads trigger HTTP fallback. The SDK installs a complete snapshot, not a mix of partial cached and downloaded lists. - If initialization fails after cache and HTTP attempts, `initialize()` returns `isSuccess: false`. A running client can recover through background polling; the example instead shuts down on failure. - Later refresh failures keep the last known good in-memory lists. DataStore support isn't a fail-closed or no-network mode. - The SDK doesn't expire valid ID-list snapshots using `time`. Keep the writer running and configure expiry in your store if needed. - With writes enabled, a successful HTTP refresh saves validated ID lists. Write failures don't discard the downloaded in-memory update. Unchanged snapshots can skip writes, so don't rely on every poll to renew a cache TTL. - ID-list updates span multiple storage entries; DataStore support doesn't make those writes transactional. - Automatic DataStore ID-list recovery after `fork()` isn't supported. Create the storage connection, adapter, and SDK in the child process instead. ## Custom output logger The Output Logger interface lets you customize how the SDK logs messages, enabling integration with your own logging system and control over log verbosity. #### Logger Interface ```typescript interface OutputLoggerProvider { initialize?: () => void; debug?: (tag: string, message: string) => void; info?: (tag: string, message: string) => void; warn?: (tag: string, message: string) => void; error?: (tag: string, message: string) => void; shutdown?: () => void; } ``` #### Implementation Example ### Implementation example ```typescript import { OutputLoggerProvider } from '@statsig/statsig-node-core'; class CustomOutputLogger implements OutputLoggerProvider { initialize = () => { console.log('Logger initialized'); }; debug = (tag: string, message: string) => { console.debug(`[$\{tag\}] ${message}`); }; info = (tag: string, message: string) => { console.info(`[$\{tag\}] ${message}`); }; warn = (tag: string, message: string) => { console.warn(`[$\{tag\}] ${message}`); }; error = (tag: string, message: string) => { console.error(`[$\{tag\}] ${message}`); }; shutdown = () => { console.log('Logger shutdown'); }; } ``` #### Usage with StatsigOptions ```typescript import { Statsig, StatsigOptions } from '@statsig/statsig-node-core'; const customLogger = new CustomOutputLogger(); const options: StatsigOptions = { outputLoggerProvider: customLogger, outputLogLevel: 'info', // 'none' | 'debug' | 'info' | 'warn' | 'error' }; const statsig = new Statsig('secret-key', options); await statsig.initialize(); ``` #### Notes - All methods in the `OutputLoggerProvider` interface are optional - The `tag` parameter indicates the SDK component or category generating the log message - Use `outputLogLevel` in StatsigOptions to control which log levels are actually called - The logger initializes when the Statsig client initializes and shuts down when the client shuts down ## Observability client The Observability Client interface lets you monitor the health of the SDK by integrating with your own observability systems. This enables you to track metrics, errors, and performance data. For more information on the metrics Statsig SDKs emit, refer to the [Monitoring documentation](https://docs.statsig.com/infrastructure/sdk-monitoring). ```typescript export interface ObservabilityClient { initialize?: () => void; increment?: (metricName: string, value: number, tags: Record<string, string>) => void; gauge?: (metricName: string, value: number, tags: Record<string, string>) => void; dist?: (metricName: string, value: number, tags: Record<string, string>) => void; error?: (tag: string, error: string) => void; } ``` ## FAQs ### How do I run experiments for logged out users ### Common problems while installing 1. **Seeing SSL Error** The binary files require certain SSL versions. ```shell // Try run this apt-get update && apt-get install libcurl4-openssl-dev -y && rm -rf /var/lib/apt/lists/* ``` 2. **Docker build failing with platform-specific dependencies** When building in Docker (Linux environment), the build may fail if your local `package-lock.json` or `yarn.lock` contains platform-specific dependencies for macOS. This happens because `npm install` on Mac pulls down Apple-specific variants, but Docker tries to use those locked dependencies on Linux. **Solution:** Either install the Linux-specific variant during your Docker build step: ```dockerfile RUN npm install @statsig/statsig-node-core-linux-x64-gnu ``` Or add both platform variants as dependencies in your `package.json`: ```json "dependencies": { "@statsig/statsig-node-core": "X.Y.Z", // Common (Required) "@statsig/statsig-node-core-darwin-arm64": "X.Y.Z", // Mac Specific "@statsig/statsig-node-core-linux-x64-gnu": "X.Y.Z" // Linux Specific } ``` ## Reference #### All API Methods - `checkGate(user: StatsigUser, gateName: string, options?: EvaluationOptions): boolean` - `getDynamicConfig(user: StatsigUser, configName: string, options?: EvaluationOptions): DynamicConfig` - `getExperiment(user: StatsigUser, experimentName: string, options?: EvaluationOptions): DynamicConfig` - `getLayer(user: StatsigUser, layerName: string, options?: EvaluationOptions): Layer` - `getFeatureGate(user: StatsigUser, gateName: string, options?: EvaluationOptions): FeatureGate` - `getParameterStore(user: StatsigUser, parameterStoreName: string, options?: EvaluationOptions): ParameterStore` - `getPrompt(user: StatsigUser, promptName: string, options?: EvaluationOptions): Prompt` - `getPromptSet(user: StatsigUser, promptSetName: string, options?: EvaluationOptions): PromptSet` - `logEvent(user: StatsigUser, eventName: string, value?: string | number | null, metadata?: Record<string, string>): void` - `forwardLogLineEvent(user: StatsigUser, level: string, message: string, metadata?: Record<string, string>): void` - `manuallyLogGateExposure(user: StatsigUser, gateName: string): void` - `manuallyLogDynamicConfigExposure(user: StatsigUser, configName: string): void` - `manuallyLogExperimentExposure(user: StatsigUser, experimentName: string): void` - `manuallyLogLayerParameterExposure(user: StatsigUser, layerName: string, parameterName: string): void` - `overrideExperimentByGroupName(experimentName: string, groupName: string, id?: string | null): void` - `getClientInitializeResponse(user: StatsigUser, options?: ClientInitializeResponseOptions): ClientInitializeResponse` - `shutdown(): Promise<void>` #### Fields Needed Methods The following methods return information about which user fields evaluation requires: - `getGateFieldsNeeded(gateName: string): string[]` - `getDynamicConfigFieldsNeeded(configName: string): string[]` - `getExperimentFieldsNeeded(experimentName: string): string[]` - `getLayerFieldsNeeded(layerName: string): string[]` These methods return an array of strings representing the user fields required to properly evaluate the specified gate, config, experiment, or layer. Use these methods to: - Optimize user object creation by including only necessary fields - Understand which user attributes affect a particular feature - Debug evaluation issues ================================================================================ # Python Server SDK URL: https://docs.statsig.com/server-core/python-core ================================================================================ # Python Server SDK - **Package:** `statsig-python-core` ([pypi](https://pypi.org/project/statsig-python-core)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-pyo3) > **Tip:** > > Migrating from the legacy Python SDK? Refer to our [Migration Guide](https://docs.statsig.com/server-core/migration-guides/python). ## Set up the SDK 1. **Install the SDK** ## Installation ```shell pip install statsig-python-core ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a StatsigOptions object to customize the SDK. ```python from statsig_python_core import Statsig, StatsigOptions # note, import statement has underscores while install has dashes options = StatsigOptions() options.environment = "development" statsig = Statsig("secret-key", options) statsig.initialize().wait() # If you're running this in a script, be sure to wait for shutdown at the end to flush event logs to statsig statsig.shutdown().wait() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ### Python Core SDK and prefork workers > **Warning:** Python-specific prefork support > > The Python Core SDK provides the prefork lifecycle integration described here. Other Server Core language SDKs share underlying Rust recovery logic, but don't provide the same lifecycle integration or establish support for initializing before a fork. For other language bindings, initialize the SDK separately in each child process after forking unless that SDK explicitly documents prefork support. Python Core SDK 0.24.0 and later includes recovery for initialized SDK instances when a Unix process forks. The fork callback marks recovery as pending; background work resumes later at a safe child lifecycle point. For earlier Python Core versions, initialize the SDK separately in each child process after forking. #### Celery prefork on Linux For Linux Celery workers using `--pool=prefork`, the Python Core SDK registers a handler for Celery's `worker_process_init` signal. Import Celery before importing the SDK in the parent process so the SDK can register the handler. Initialize the SDK in the parent before Celery creates its worker pool. You don't need to register another signal handler. Recovery also runs when Celery recycles workers. Install `statsig-python-core` 0.24.0 or later and `celery[redis]`. Run a Redis broker accessible to the worker. Set `CELERY_BROKER_URL` to its URL and `STATSIG_SERVER_SECRET_KEY` to your project's server secret key. Then create `worker.py`: ```python import os from celery import Celery from statsig_python_core import Statsig, StatsigUser app = Celery("worker", broker=os.environ["CELERY_BROKER_URL"]) statsig = Statsig(os.environ["STATSIG_SERVER_SECRET_KEY"]) statsig.initialize().wait() @app.task def check_example_gate(user_id): return statsig.check_gate(StatsigUser(user_id), "example_gate") ``` Replace `example_gate` with a gate in your project. Start the worker with `celery -A worker worker --pool=prefork --concurrency=2 --loglevel=INFO`. In another terminal with the same environment, submit a task: ```bash celery -A worker call worker.check_example_gate --args '["example-user"]' ``` Check the worker log for the task result. The `celery -A worker` command also imports `worker.py` and initializes a separate SDK instance in the submitting process. A `False` result can be a valid gate evaluation. It doesn't by itself indicate a recovery failure. Recovery schedules background work. It doesn't guarantee a network refresh has completed before the first task runs. The child doesn't resend events queued in the parent before the fork. #### Other Unix prefork hosts For another Unix prefork host, call `recover_after_fork` once per child from the framework's child-ready callback. Call it after child initialization and before processing work: ```python from statsig_python_core import recover_after_fork def on_worker_child_ready(): if not recover_after_fork(): # Report the failed recovery through your worker startup diagnostics. # Later SDK operations can retry recovery. pass ``` The function covers all live ordinary and shared SDK instances. Don't call it from a raw `os.register_at_fork(after_in_child=...)` callback. A `True` return means the SDK scheduled or re-armed recovery within its shared callback budget. It doesn't mean fresh configuration has arrived. A `False` return means recovery didn't finish scheduling for every instance. Record the failure and allow later SDK operations to retry. Statsig has integration coverage for Linux Celery prefork. This guidance doesn't establish support for macOS child forks, Windows, `spawn`, `forkserver`, or other process managers. ### Initializing with WSGI servers For production deployments using WSGI servers like uWSGI or Gunicorn, initialize Statsig **after** the worker processes are forked, not in the main process. #### uWSGI #### ✅ Correct: uWSGI example ```python # app.py from statsig_python_core import Statsig, StatsigOptions from flask import Flask app = Flask(__name__) statsig = None def init_statsig(): global statsig if statsig is None: options = StatsigOptions() options.environment = "production" statsig = Statsig("your-server-secret-key", options) statsig.initialize().wait() # Initialize in each worker process @app.before_first_request def before_first_request(): init_statsig() @app.route('/') def index(): # Use statsig here return "Hello World" ``` ```ini # uwsgi.ini [uwsgi] module = app:app master = true processes = 4 # Statsig will be initialized in each worker process ``` #### Gunicorn #### ✅ Correct: Gunicorn example ```python # gunicorn_config.py def post_fork(server, worker): # Initialize Statsig after worker process is forked from app import init_statsig init_statsig() # as defined above # ...app.py ``` ```bash # Start Gunicorn with post-fork hook gunicorn --config gunicorn_config.py app:app ``` #### FastAPI #### ✅ Correct: FastAPI example ```python from fastapi import FastAPI from statsig_python_core import Statsig, StatsigOptions app = FastAPI() statsig = None @app.on_event("startup") async def startup_event(): global statsig options = StatsigOptions() options.environment = "production" statsig = Statsig("your-server-secret-key", options) statsig.initialize().wait() @app.on_event("shutdown") async def shutdown_event(): if statsig: statsig.shutdown().wait() @app.get("/") async def root(): # Use statsig here return {"message": "Hello World"} ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example: ```python user = StatsigUser("a-user") if statsig.check_gate(user, "a_gate"): # Gate is on, enable new feature else: # Gate is off ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and similar types) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a full JSON object configurable on the server from which you can fetch typed parameters. ```python # Get a dynamic config for a specific user config = statsig.get_dynamic_config(StatsigUser("my_user"), "a_config") # Access config values with type-safe getters and fallback values product_name = config.get_string("product_name", "Awesome Product v1") # returns String price = config.get_float("price", 10.0) # returns float should_discount = config.get_bool("discount", False) # returns bool quantity = config.get_integer("quantity", 1) # returns int64 # Advanced Usage: # You can disable exposure logging for this specific check options = DynamicConfigEvaluationOptions(disable_exposure_logging=True) config = statsig.get_dynamic_config(user, "a_config", options) # The config object also provides metadata about the evaluation print(config.rule_id) # The ID of the rule that served this config print(config.id_type) # The type of the evaluation (experiment, config, etc) ``` The `get_dynamic_config()` method returns a DynamicConfig object that allows you to: - Fetch typed values with fallback defaults using `get_string()`, `get_float()`, `get_boolean()`, and `get_integer()` - Access evaluation metadata through properties like `rule_id` and `id_type` - Configure evaluation behavior using `DynamicConfigEvaluationOptions` By default, Statsig automatically logs exposures when it evaluates configs. You can disable exposure logging for specific checks using the evaluation options. ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available. Statsig recommends [Layers](https://docs.statsig.com/experiments/layers-overview) because they make parameters reusable and support mutually exclusive experiments. ```Python # Values via get_layer layer = statsig.get_layer(StatsigUser("my_user"), "user_promo_experiments") title = layer.get_string("title", "Welcome to Statsig!") discount = layer.get_float("discount", 0.1) # Via get_experiment title_exp = statsig.get_experiment(StatsigUser("my_user"), "new_user_promo_title") price_exp = statsig.get_experiment(StatsigUser("my_user"), "new_user_promo_price") title = title_exp.get_string("title", "Welcome to Statsig!") discount = price_exp.get_float("discount", 0.1) ``` ### Retrieving feature gate metadata In certain scenarios, you may need more information about a gate evaluation than a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object: ```python gate = statsig.get_feature_gate(user, "example_gate") print(gate.rule_id) print(gate.value) ``` ### Parameter stores Use Parameter Stores when you want to define a parameter without deciding whether it should be a Feature Gate, Experiment, or Dynamic Config. Parameter Stores let you change the parameter type at any point in the Statsig console without a new deployment. Parameter Stores are optional, but parameterizing your application provides future flexibility and allows non-technical Statsig users to turn parameters into experiments. ```python # Get a Parameter Store by name param_store = statsig.get_parameter_store(user, "my_parameter_store") ``` ### Retrieving parameter values Parameter Store provides methods for retrieving values of different types with fallback defaults. ```python # String parameters string_value = param_store.get_string("string_param", "default_value") # Boolean parameters bool_value = param_store.get_bool("bool_param", False) # Numeric parameters float_value = param_store.get_float("float_param", 0.0) integer_value = param_store.get_integer("integer_param", 0) # Complex parameters default_array = ["item1", "item2"] array_value = param_store.get_array("array_param", default_array) default_map = {"key": "value"} map_value = param_store.get_map("map_param", default_map) ``` ### Evaluation options You can disable exposure logging when retrieving a parameter store: ```python from statsig_python_core import ParameterStoreEvaluationOptions options = ParameterStoreEvaluationOptions(disable_exposure_logging=True) param_store = statsig.get_parameter_store(user, "my_parameter_store", options) ``` ### Logging an event To track custom events, call the Log Event API. Specify the user, event name, and an optional value or metadata object: ```Python statsig.log_event( user=StatsigUser("user_id"), # Replace with your user object event_name="add_to_cart", value="SKU_12345", metadata={ "price": "9.99", "item_name": "diet_coke_48_pack" } ) ``` ### Sending events to Log Explorer You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log. ```python user = StatsigUser( user_id="a-user", custom={ "service": "my-service", "pod": "my-pod", "namespace": "my-namespace", "container": "my-container", # ...include any service-specific metadata } ) # levels: trace, debug, info, log, warn, error statsig.forward_log_line_event(user, "warn", "script failed to load", { "custom_metadata": "script_name:my-script" # ... include any event-specific metadata }) ``` ## Using shared instance To create a single Statsig instance accessible globally throughout your codebase, use the shared instance functionality, which provides a singleton pattern: ```python # Create a shared instance that can be accessed globally statsig = Statsig.new_shared("secret-key", options) statsig.initialize().wait() # Access the shared instance from anywhere in your code shared_statsig = Statsig.shared() is_feature_enabled = shared_statsig.check_gate(StatsigUser("user_id"), "feature_name") # Check if a shared instance exists if Statsig.has_shared_instance(): # Use the shared instance pass # Remove the shared instance when no longer needed Statsig.remove_shared() ``` The shared instance helps when multiple parts of your codebase need Statsig without passing an instance between them. - `Statsig.new_shared(sdk_key, options)`: Creates a new shared instance of Statsig that you can access globally - `Statsig.shared()`: Returns the shared instance - `Statsig.has_shared_instance()`: Checks if a shared instance exists (useful when the shared instance may not be ready yet) - `Statsig.remove_shared()`: Removes the shared instance (useful when you want to switch to a new shared instance) > **Note:** > > `has_shared_instance()` and `remove_shared()` are helpful in specific scenarios but aren't required in most use cases where the shared instance is set up near the top of your application. > > Also note that only one shared instance can exist at a time. Attempting to create a second shared instance results in an error. ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call get() on a parameter in a layer. To delay exposure logging (for example, to log only after the user actually uses the feature), use manual exposures. All main SDK functions (`check_gate`, `get_dynamic_config`, `get_experiment`, `get_layer`) accept an optional `disable_exposure_logging` parameter. When set to `True`, the SDK doesn't automatically log an exposure. You can then log the exposure manually at a later time: #### Feature Gates ```python result = statsig.check_gate(aUser, 'a_gate_name', FeatureGateEvaluationOptions(disable_exposure_logging=True)) ``` ```python statsig.manually_log_gate_exposure(aUser, 'a_gate_name') ``` #### Dynamic Configs ```python config = statsig.get_dynamic_config(aUser, 'a_dynamic_config_name', DynamicConfigEvaluationOptions(disable_exposure_logging=True)) ``` ```python statsig.manually_log_dynamic_config_exposure(aUser, 'a_dynamic_config_name') ``` #### Experiments ```python experiment = statsig.get_experiment(aUser, 'an_experiment_name', ExperimentEvaluationOptions(disable_exposure_logging=True)) ``` ```python statsig.manually_log_experiment_exposure(aUser, 'an_experiment_name') ``` #### Layers ```python layer = statsig.get_layer(aUser, 'a_layer_name', LayerEvaluationOptions(disable_exposure_logging=True)) paramValue = layer.get('a_param_name', 'fallback_value') ``` ```python statsig.manually_log_layer_parameter_exposure(aUser, 'a_layer_name', 'a_param_name') ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. Complete user information lets you take advantage of advanced gate and config conditions (like country or OS/browser-level checks) and correctly measure the impact of experiments on metrics and events. As explained in [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks), you must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. In addition to userID, the top-level fields on StatsigUser are: email, ip, userAgent, country, locale, and appVersion. You can also pass any key-value pairs in an object or dictionary to the custom field and create targeting based on them. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. They are useful for PII or sensitive data that you don't want to send to third-party services. ```python from statsig_python_core import StatsigUser user = StatsigUser( user_id="a-user-id", email="user@example.com", ip="192.168.1.1", user_agent="Mozilla/5.0...", country="US", locale="en_US", app_version="1.0.0", custom={ # Custom fields "plan": "premium", "age": 25 }, custom_ids={ # Custom ID types "stable_id": "stable-id-123" }, private_attributes={ # Private attributes not forwarded to integrations "email": "private@example.com" } ) ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_url | Optional[str] | No | — | Custom URL for fetching feature specifications. Provide the full endpoint URL, which the SDK uses as-is. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_sync_interval_ms | Optional[int] | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | init_timeout_ms | Optional[int] | No | — | Sets the maximum timeout for initialization requests (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | log_event_url | Optional[str] | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_all_logging | Optional[bool] | No | — | When `true`, disables all event logging. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_network | Optional[bool] | No | — | When `true`, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called "localMode". | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_flush_interval_ms | Optional[int] | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_queue_size | Optional[int] | No | — | Maximum number of events to queue before forcing a flush.- Default is `2000` - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - Refer to `event_logging_max_pending_batch_queue_size` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_pending_batch_queue_size | Optional[int] | No | — | Maximum number of event batches to hold in buffer to retry.- Default is `100`. - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - eg: 2000 \* 100 means the SDK can process 200k event per second before events start getting dropped - Refer to `event_logging_max_queue_size`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enable_id_lists | Optional[bool] | No | — | Enable/disable ID list functionality. **Required to be `true` when using segments with more than 1000 IDs.** Refer to [ID List segments](https://docs.statsig.com/segments/add-id-list) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_user_agent_parsing | Optional[bool] | No | — | If set to true, the SDK doesn't attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_user_agent_init | Optional[bool] | No | — | When set to true, the SDK waits until user agent parsing data is fully loaded during initialization. This may slow down startup by ~1 second but ensures that parsing of the user's userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_country_lookup | Optional[bool] | No | — | If set to true, the SDK doesn't attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_country_lookup_init | Optional[bool] | No | — | When set to true, the SDK waits for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down startup by ~1 second but ensures that IP-to-country parsing is ready at evaluation time. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_url | Optional[str] | No | — | Custom URL for fetching the ID list manifest (the `get_id_lists` endpoint). Provide the full endpoint URL, which the SDK uses as-is. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | download_id_list_file_api | Optional[str] | No | — | Origin (scheme and host only, no path) for downloading individual ID list files. Unlike `specs_url` and `id_lists_url`, which take a full endpoint URL, this takes an origin only: the SDK appends each per-file path from the ID list manifest. Setting a full path (for example, one ending in `/v1/download_id_list_file`) produces a doubled path and a 401. Overriding only `specs_url` and `id_lists_url` leaves individual ID list file downloads going to the Statsig CDN; set this option to route them through your proxy. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_sync_interval_ms | Optional[int] | No | — | How often the SDK updates ID lists from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallback_to_statsig_api | Optional[bool] | No | — | Whether to fall back to the Statsig API if custom endpoints fail. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | Optional[str] | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | output_log_level | Optional[str] | No | — | Controls the verbosity of SDK logs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | persistent_storage | Optional[PersistentStorage] | No | — | Adapter / Interface to use persistent assignment within SDK. Refer to [Persistent Assignment](https://docs.statsig.com/server/concepts/persistent_assignment/) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | observability_client | Optional[ObservabilityClient] | No | — | Adapter to monitor the health of the SDK. Refer to [SDK Monitoring](https://docs.statsig.com/infrastructure/sdk-monitoring) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | data_store | Optional[DataStore] | No | — | Custom data store implementation for storing and retrieving configuration data. Used for advanced caching or storage strategies. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_pending_batch_queue_size | Optional[int] | No | — | Maximum number of batches of events to hold in buffer to retry. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | global_custom_fields | Optional[Dict] | No | — | Custom fields to include in all events logged by the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | config_compression_mode | Optional[str] | No | — | Compression method for exposure logging. Options: "gzip", "dictionary" | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxy_config | Optional[ProxyConfig] | No | — | Configuration for connecting through a proxy server. The `ProxyConfig` object has the following properties:- `proxy_host`: Optional string specifying the proxy server host - `proxy_port`: Optional number specifying the proxy server port - `proxy_auth`: Optional string for proxy authentication (format: "username:password") - `proxy_protocol`: Optional string specifying the protocol (e.g., "http", "https") - `ca_cert_path`: Optional path to a PEM CA bundle for outbound TLS | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | spec_adapter_configs | Optional[List[SpecAdapterConfig]] | No | — | Advanced configuration for customizing how the SDK fetches feature specifications. Allows you to configure multiple spec adapters with different priorities and settings.Each `SpecAdapterConfig` object has the following properties:- `adapter_type`: String specifying the adapter type (e.g., "http", "grpc") - `specs_url`: Optional custom URL for fetching specifications - `init_timeout_ms`: Optional timeout for initialization (in milliseconds)> **Note:** > > **Migration note:** Statsig previously named this parameter `init_resources` in earlier versions. If you're upgrading from an older version, replace `init_resources` with `spec_adapter_configs`. | ### Proxy and custom network routing Use `proxy_config` if your service needs a standard outbound HTTP proxy. Use `spec_adapter_configs` if you need to route spec downloads through [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) or another custom spec source. ```python from statsig_python_core import ProxyConfig, Statsig, StatsigOptions proxy_config = ProxyConfig( proxy_host="proxy.example.com", proxy_port=8080, proxy_protocol="https", ca_cert_path="/etc/ssl/certs/corporate-ca.pem", # Optional ) options = StatsigOptions() options.proxy_config = proxy_config statsig = Statsig("secret-key", options) statsig.initialize().wait() ``` Set `ca_cert_path` when your environment requires a custom PEM CA bundle for outbound TLS. ### Using spec\_adapter\_configs with multiple sources ```python from statsig_python_core import StatsigOptions, SpecAdapterConfig # Configure multiple spec adapters with priority order # First source: Statsig CDN primary_adapter = SpecAdapterConfig( adapter_type="http", specs_url="https://api.statsigcdn.com/v2/download_config_specs", init_timeout_ms=3000 ) # Second source: Data Store adapter # The SDK will try this source if the primary source fails data_store_adapter = SpecAdapterConfig( adapter_type="data_store", init_timeout_ms=5000 ) options = StatsigOptions() options.spec_adapter_configs = [primary_adapter, data_store_adapter] options.environment = "production" statsig = Statsig("secret-key", options) statsig.initialize().wait() ``` ## Shutting Statsig down Statsig batches and periodically flushes events. To flush all logged events before shutdown, call `shutdown()` before your app or server shuts down: ```python statsig.shutdown().wait() ``` ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing. This is useful for local development or testing when you want to force a specific value without changing the configuration in the Statsig console. ```python # Overrides the given gate to the specified value statsig.override_gate("a_gate_name", True) # Overrides the given dynamic config to the provided value statsig.override_dynamic_config("a_config_name", {"key": "value"}) # Overrides the given experiment to the provided value statsig.override_experiment("an_experiment_name", {"key": "value"}) # Overrides the given layer to the provided value statsig.override_layer("a_layer_name", {"key": "value"}) # Overrides the given experiment to a particular groupname, available for experiments only: statsig.override_experiment_by_group_name("an_experiment_name", "a_group_name") ``` ## Client SDK bootstrapping | SSR If you use the Statsig client SDK in a browser or mobile app, you can bootstrap the client SDK with values from the server SDK to avoid a network request on the client. This is useful for server-side rendering (SSR) or to reduce network requests on the client. ## Client initialize response The Python Core SDK provides a method to generate a client initialize response that you can use to bootstrap client SDKs without requiring network requests. ```python import json from statsig_python_core import Statsig, StatsigUser # Get client initialize response for a user response_data = statsig.get_client_initialize_response(user) response = json.loads(response_data) # Pass response to a client SDK to initialize without a network request ``` #### Initialize Response Parameters The `get_client_initialize_response` method accepts the following parameters: ```python def get_client_initialize_response( user: StatsigUser, hash: Optional[str] = None, client_sdk_key: Optional[str] = None, include_local_overrides: Optional[bool] = None ) -> str: ``` - **`user`**: `StatsigUser` - The user to generate the initialize response for - **`hash`**: `Optional[str]` - Algorithm used for hashing gate/experiment names (default: 'djb2') - **`client_sdk_key`**: `Optional[str]` - Client SDK key to use for initialization - **`include_local_overrides`**: `Optional[bool]` - Whether to include local overrides in the response #### Hash Algorithm The `hash` parameter specifies which algorithm to use for hashing gate and experiment names in the client initialize response. The default is `'djb2'` for better performance and smaller payload size. Available options: - `'djb2'` (default) - DJB2 hashing algorithm for better performance - `'sha256'` - SHA-256 hashing algorithm - `'none'` - No hashing applied ```python # Use djb2 hashing algorithm (default) response_data = statsig.get_client_initialize_response(user, hash='djb2') # Use SHA-256 hashing algorithm response_data = statsig.get_client_initialize_response(user, hash='sha256') # Disable hashing response_data = statsig.get_client_initialize_response(user, hash='none') ``` #### Client SDK Key The `client_sdk_key` parameter lets you filter the response to only the specific feature gates, experiments, dynamic configs, layers, or parameter stores that a particular client key has access to, effectively letting you apply [target apps](https://docs.statsig.com/sdks/target-apps). ```python # Specify a client SDK key response_data = statsig.get_client_initialize_response( user, client_sdk_key='client-key' ) ``` #### Local Overrides The `include_local_overrides` parameter determines whether to consider [local overrides](#local-overrides) you've set when evaluating each config in the response. ```python # Include local overrides in the response response_data = statsig.get_client_initialize_response( user, include_local_overrides=True ) ``` #### Full Code Example Below is a complete example of using the client initialize response to bootstrap a client SDK. You can parallelize or inline the initialize response data with other requests to your server to eliminate additional round trips and latency. ```python # Server-side code import json from statsig_python_core import Statsig, StatsigUser, StatsigOptions from flask import Flask, request, jsonify app = Flask(__name__) # Initialize the server SDK options = StatsigOptions() statsig = Statsig('server-secret-key', options) statsig.initialize().wait() # In your API endpoint handler @app.route('/statsig-bootstrap') def statsig_bootstrap(): # Create a user object from the request user = StatsigUser( user_id=request.args.get('userID', ''), email=request.args.get('email'), ip=request.remote_addr, user_agent=request.headers.get('User-Agent') ) # Generate the client initialize response response_data = statsig.get_client_initialize_response( user, hash='djb2', client_sdk_key='client-sdk-key' ) # Parse the JSON response statsig_values = json.loads(response_data) # Return the values to the client return jsonify({'statsigValues': statsig_values}) ``` ```javascript // Client-side code using @statsig/js-client import { Statsig } from "@statsig/js-client"; // Fetch bootstrap values from your API const response = await fetch("/statsig-bootstrap"); const { statsigValues } = await response.json(); // Initialize the client SDK with the bootstrap values await Statsig.initialize({ sdkKey: "client-sdk-key", initializeValues: statsigValues, }); ``` #### Response Format The method returns a JSON string containing the client initialize response. You need to parse this string to access the data: ```python response_data = statsig.get_client_initialize_response(user) response = json.loads(response_data) # Access different parts of the response feature_gates = response.get('feature_gates', {}) dynamic_configs = response.get('dynamic_configs', {}) layer_configs = response.get('layer_configs', {}) ``` The response includes: - `feature_gates`: Feature gate evaluations for the user - `dynamic_configs`: Dynamic config and experiment evaluations - `layer_configs`: Layer evaluations - `has_updates`: Boolean indicating if there are updates - `time`: Timestamp of the response ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups when a user returns. This is useful for client-side A/B testing where users must always receive the same variant. ```python class PersistentStorage(PersistentStorageBaseClass): def __init__(): # When you initialize, remember to call super.__init__() super().__init__() self.load_fn = self.load self.save_fn = self.save self.delete_fn = self.delete def load(self, key: str) -> Optional[UserPersistedValues]: """ Load persisted values for a user from storage Args: key: A string key that uniquely identifies a user Returns: Dictionary mapping config names to their persisted values """ pass def save(self, key: str, config_name: str, data: StickyValues): """ Save a persistent value for a user Args: key: A string key that uniquely identifies a user config_name: The name of the config/experiment data: The values to persist """ pass def delete(self, key: str, config_name: str): """ Delete a persistent value for a user Args: key: A string key that uniquely identifies a user config_name: The name of the config/experiment to delete """ pass ``` ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems. ```python class DataStore(DataStoreBase): def initialize(self): """ Initialize the data store. Called when the Statsig client initializes. """ pass def shutdown(self): """ Clean up resources when the Statsig client shuts down. """ pass def get(self, key: str) -> Optional[DataStoreResponse]: """ Retrieve value from the data store. Args: key: The key to retrieve the value for Returns: DataStoreResponse containing the result and time """ pass def set(self, key: str, value: str, time: Optional[int] = None): """ Store a value in the data store. Args: key: The key to store the value under value: The value to store time: Optional timestamp """ pass def support_polling_updates_for(self, key: str) -> bool: """ Whether the data store supports polling for updates for the given key. Args: key: The key to check Returns: True if polling is supported, False otherwise """ return False ``` ## Custom output logger The Output Logger Provider interface lets you customize how the SDK logs internal messages. ```python class OutputLoggerProvider(OutputLoggerProviderBase): def init(self): """ Initialize the logger. Called when the Statsig client initializes. """ pass def debug(self, tag: str, msg: str): """ Log a debug message. Args: tag: Category/component tag for the message msg: The message to log """ pass def info(self, tag: str, msg: str): """ Log an info message. Args: tag: Category/component tag for the message msg: The message to log """ pass def warn(self, tag: str, msg: str): """ Log a warning message. Args: tag: Category/component tag for the message msg: The message to log """ pass def error(self, tag: str, msg: str): """ Log an error message. Args: tag: Category/component tag for the message msg: The message to log """ pass def shutdown(self): """ Clean up resources when the Statsig client shuts down. """ pass ``` ## Observability client The Observability Client interface lets you monitor the health of the SDK by integrating with your own observability systems. This enables you to track metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, refer to the [Monitoring documentation](https://docs.statsig.com/infrastructure/sdk-monitoring). ```python class ObservabilityClient(ObservabilityClientBase): def init(self): """ Initialize the observability client. Called when the Statsig client initializes. """ pass def increment(self, metric_name: str, value: float, tags: Optional[Dict[str, str]] = None): """ Report a counter metric. Args: metric_name: The name of the metric value: The amount to increment by tags: Optional tags to associate with the metric """ pass def gauge(self, metric_name: str, value: float, tags: Optional[Dict[str, str]] = None): """ Report a gauge metric. Args: metric_name: The name of the metric value: The current value tags: Optional tags to associate with the metric """ pass def dist(self, metric_name: str, value: float, tags: Optional[Dict[str, str]] = None): """ Report a distribution metric. Args: metric_name: The name of the metric value: The value to record tags: Optional tags to associate with the metric """ pass def error(self, tag: str, error: str): """ Report an error. Args: tag: Category/component tag for the error error: The error message """ pass def should_enable_high_cardinality_for_this_tag(self, tag: str) -> bool: """ Determine if high cardinality should be enabled for a tag. Args: tag: The tag to check Returns: True if high cardinality should be enabled, False otherwise """ pass ``` ## FAQ #### How do I run experiments for logged out users? Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ## Reference ### API methods - `check_gate(user: StatsigUser, gate_name: str, options: Optional[FeatureGateEvaluationOptions] = None) -> bool` - `get_dynamic_config(user: StatsigUser, config_name: str, options: Optional[DynamicConfigEvaluationOptions] = None) -> DynamicConfig` - `get_experiment(user: StatsigUser, experiment_name: str, options: Optional[ExperimentEvaluationOptions] = None) -> DynamicConfig` - `get_layer(user: StatsigUser, layer_name: str, options: Optional[LayerEvaluationOptions] = None) -> Layer` - `get_feature_gate(user: StatsigUser, gate_name: str, options: Optional[FeatureGateEvaluationOptions] = None) -> FeatureGate` - `get_parameter_store(user: StatsigUser, parameter_store_name: str, options: Optional[ParameterStoreEvaluationOptions] = None) -> ParameterStore` - `log_event(user: StatsigUser, event_name: str, value: Optional[Union[str, float]] = None, metadata: Optional[Dict[str, str]] = None) -> None` - `manually_log_gate_exposure(user: StatsigUser, gate_name: str) -> None` - `manually_log_dynamic_config_exposure(user: StatsigUser, config_name: str) -> None` - `manually_log_experiment_exposure(user: StatsigUser, experiment_name: str) -> None` - `manually_log_layer_parameter_exposure(user: StatsigUser, layer_name: str, parameter_name: str) -> None` - `override_experiment_by_group_name(experiment_name: str, group_name: str, id: Optional[str] = None) -> None` - `get_client_initialize_response(user: StatsigUser, options: Optional[ClientInitializeResponseOptions] = None) -> ClientInitializeResponse` - `shutdown() -> AsyncResult[None]` ### Fields needed methods The following methods return information about which user fields evaluation requires: - `get_gate_fields_needed(gate_name: str) -> List[str]` - `get_dynamic_config_fields_needed(config_name: str) -> List[str]` - `get_experiment_fields_needed(experiment_name: str) -> List[str]` - `get_layer_fields_needed(layer_name: str) -> List[str]` These methods return a list of strings representing the user fields that are required to properly evaluate the specified gate, config, experiment, or layer. ================================================================================ # Java Server SDK URL: https://docs.statsig.com/server-core/java-core ================================================================================ # Java Server SDK - **Package:** `com.statsig:javacore` ([maven](https://search.maven.org/artifact/com.statsig/javacore)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-java) > **Tip:** > > Migrating from the Legacy Java SDK? Refer to the [Migration Guide](https://docs.statsig.com/server-core/migration-guides/java). ## Setup the SDK 1. **Install the SDK** ## Requirements - Java 8 or higher (Java 8 support added in version 0.4.3) - Compatible with all platforms listed in the Supported OS and Architecture Combinations section, including: - macOS (x86\_64, arm64) - Windows (x86\_64) - Amazon Linux 2 and 2023 (x86\_64, arm64) ## Overview You can install the Statsig Java SDK in two ways: **Recommended: Single JAR installation** (since version 0.4.0) - Use the "uber" JAR which contains both the core library and popular platform-specific native libraries in a single package - Simplifies dependency management and deployment across different environments **Advanced: Two-part installation** 1. The platform-independent core library 2. An OS/architecture-specific native library for your specific platform ## Installation steps ### Recommended: Using the uber JAR (all-in-one) Since version 0.4.0, Statsig provides an "uber" JAR that contains both the core library and native libraries for popular supported platforms in a single package. This is the recommended approach for most users. #### Gradle ```groovy repositories { mavenCentral() } dependencies { implementation 'com.statsig:javacore:X.X.X:uber' // Uber JAR with all native libraries } ``` #### Maven ```xml <dependencies> <dependency> <groupId>com.statsig</groupId> <artifactId>javacore</artifactId> <version>X.X.X</version> <classifier>uber</classifier> </dependency> </dependencies> ``` You can find the latest version on [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore). The uber JAR includes native libraries for: - Linux (x86\_64, arm64) - macOS (x86\_64, arm64) - Windows (x86\_64) This approach eliminates the need to specify the exact platform and simplifies deployment across different environments. ### Advanced: Platform-specific installation If you need more control over dependencies or want to minimize the JAR size for a specific platform, you can use the platform-specific installation approach. 1. **Install Core Library** #### Gradle ```groovy repositories { mavenCentral() } dependencies { implementation 'com.statsig:javacore:X.X.X' // Replace X.X.X with the latest version } ``` #### Maven ```xml <dependencies> <dependency> <groupId>com.statsig</groupId> <artifactId>javacore</artifactId> <version>X.X.X</version> <!-- Replace X.X.X with the latest version --> </dependency> </dependencies> ``` You can find the latest version on [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore). 2. **Install Platform-Specific Library** You need to add the appropriate OS/architecture-specific dependency. Choose one of the following methods: **Method 1: Automatic Detection** Run the following code to detect your system and get the appropriate dependency: ```java import com.statsig.*; // All StatsigOptions are optional, feel free to adjust them as needed StatsigOptions options = new StatsigOptions.Builder().build(); Statsig statsig = new Statsig("your-secret-key", options); ``` You receive output similar to: ```plaintext For Linux with arm64 architecture, add the following to build.gradle: implementation 'com.statsig:javacore:<version>:aarch64-unknown-linux-gnu' For Linux with x86_64 architecture, add the following to build.gradle: implementation 'com.statsig:javacore:<version>:x86_64-unknown-linux-gnu' ``` **Method 2: Manual Configuration** #### Gradle ```groovy dependencies { implementation 'com.statsig:javacore:X.X.X' // Core SDK (from Step 1) implementation 'com.statsig:javacore:X.X.X:YOUR-OS-ARCHITECTURE' // OS/architecture-specific dependency } ``` #### Maven ```xml <dependencies> <dependency> <groupId>com.statsig</groupId> <artifactId>javacore</artifactId> <version>X.X.X</version> </dependency> <dependency> <groupId>com.statsig</groupId> <artifactId>javacore</artifactId> <version>X.X.X</version> <classifier>YOUR-OS-ARCHITECTURE</classifier> </dependency> </dependencies> ``` Replace `YOUR-OS-ARCHITECTURE` with one of the supported combinations from the Supported OS and Architecture Combinations section. > **Warning:** > > **Docker Considerations for Alpine Linux** > > When using Alpine Linux or other musl-based Docker containers, you need to install additional compatibility packages for the native libraries to work properly. Add the following to your Dockerfile: > > ```dockerfile > RUN apk add --no-cache libgcc gcompat > ``` > > The Statsig Java Core SDK automatically detects musl-based systems and uses the appropriate musl-compatible native libraries (e.g., `x86_64-unknown-linux-musl`, `aarch64-unknown-linux-musl`). 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. #### Java ```java import com.statsig.*; // All StatsigOptions are optional, feel free to adjust them as needed StatsigOptions options = new StatsigOptions.Builder() .setSpecsSyncIntervalMs(10000) .setEventLoggingFlushIntervalMs(10000) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build(); Statsig myStatsigServer = new Statsig(SECRET_KEY, options); myStatsigServer.initialize().get(); ``` #### Kotlin ```kotlin import com.statsig.* // All StatsigOptions are optional, feel free to adjust them as needed val options = StatsigOptions.Builder() .setSpecsSyncIntervalMs(10000) .setEventLoggingFlushIntervalMs(10000) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build() val myStatsigServer = Statsig(SECRET_KEY, options) myStatsigServer.initialize().get() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls. ## Getting started ### Quick start example 1. **Create a new Java project** Create a new Gradle or Maven project with the following structure: ```plaintext my-statsig-app/ ├── build.gradle (or pom.xml) └── src/main/java/ExampleApp.java ``` 2. **Add Statsig dependency** #### build.gradle ```groovy plugins { id 'java' id 'application' } repositories { mavenCentral() } dependencies { implementation 'com.statsig:javacore:X.X.X:uber' } application { mainClass = 'ExampleApp' } ``` #### pom.xml ```xml <project> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>my-statsig-app</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>com.statsig</groupId> <artifactId>javacore</artifactId> <version>X.X.X</version> <classifier>uber</classifier> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.0.0</version> <configuration> <mainClass>ExampleApp</mainClass> </configuration> </plugin> </plugins> </build> </project> ``` Replace `X.X.X` with the latest version from [Maven Central](https://central.sonatype.com/artifact/com.statsig/javacore). 3. **Write your application code** #### ExampleApp.java ```java import com.statsig.*; public class ExampleApp { public static void main(String[] args) throws Exception { // Initialize Statsig StatsigOptions options = new StatsigOptions.Builder().build(); Statsig statsig = new Statsig("YOUR_SERVER_SECRET_KEY", options); statsig.initialize().get(); try { // Check a feature gate boolean isEnabled = statsig.checkGate("user123", "my_feature_gate"); System.out.println("Feature gate is " + (isEnabled ? "enabled" : "disabled")); // Get a config DynamicConfig config = statsig.getConfig("user123", "my_config"); System.out.println("Config value: " + config.getString("some_parameter", "default_value")); } finally { // Always shutdown Statsig when done statsig.shutdown(); } } } ``` #### ExampleApp.kt ```kotlin import com.statsig.* fun main() { // Initialize Statsig val options = StatsigOptions.Builder().build() val statsig = Statsig("YOUR_SERVER_SECRET_KEY", options) statsig.initialize().get() try { // Check a feature gate val isEnabled = statsig.checkGate("user123", "my_feature_gate") println("Feature gate is ${if (isEnabled) "enabled" else "disabled"}") // Get a config val config = statsig.getConfig("user123", "my_config") println("Config value: ${config.getString("some_parameter", "default_value")}") } finally { // Always shutdown Statsig when done statsig.shutdown().get() } } ``` Replace `YOUR_SERVER_SECRET_KEY` with your actual server secret key from the [Statsig Console](https://console.statsig.com/). 4. **Run the application** #### Gradle ```bash ./gradlew run ``` #### Maven ```bash mvn compile exec:java ``` If everything is set up correctly, you should see output related to your feature gate and configuration. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). To check a gate for a user: #### Java ```java String userID = "user_id"; boolean result = statsig.checkGate(userID, "my_feature_gate"); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); boolean gateResult = statsig.checkGate(user, "my_feature_gate"); ``` #### Kotlin ```kotlin val userID = "user_id" val result = statsig.checkGate(userID, "my_feature_gate") // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() val gateResult = statsig.checkGate(user, "my_feature_gate") ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example: #### Java ```java String userID = "user_id"; DynamicConfig config = statsig.getConfig(userID, "my_config"); String name = config.getString("name", ""); int size = config.getInt("size", 10); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); DynamicConfig dynamicConfig = statsig.getConfig(user, "my_config"); ``` #### Kotlin ```kotlin val userID = "user_id" val config = statsig.getConfig(userID, "my_config") val name = config.getString("name", "") val size = config.getInt("size", 10) // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() val dynamicConfig = statsig.getConfig(user, "my_config") ``` ### Getting a layer/experiment **Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) because layers make parameters reusable and support mutually exclusive experiments. #### Java ```java String userID = "user_id"; // Getting an Experiment Experiment experiment = statsig.getExperiment(userID, "my_experiment"); String expName = experiment.getString("experiment_param", ""); // Getting a Layer Layer layer = statsig.getLayer(userID, "my_layer"); String layerValue = layer.getString("layer_param", "default"); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); Experiment experimentWithUser = statsig.getExperiment(user, "my_experiment"); Layer layerWithUser = statsig.getLayer(user, "my_layer"); ``` #### Kotlin ```kotlin val userID = "user_id" // Getting an Experiment val experiment = statsig.getExperiment(userID, "my_experiment") val expName = experiment.getString("experiment_param", "") // Getting a Layer val layer = statsig.getLayer(userID, "my_layer") val layerValue = layer.getString("layer_param", "default") // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() val experimentWithUser = statsig.getExperiment(user, "my_experiment") val layerWithUser = statsig.getLayer(user, "my_layer") ``` ### Retrieving feature gate metadata To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object: #### Java ```java String userID = "user_id"; FeatureGate gate = statsig.getFeatureGate(userID, "my_feature_gate"); System.out.println("Gate name: " + gate.name); System.out.println("Gate value: " + gate.value); System.out.println("Rule ID: " + gate.ruleID); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); FeatureGate gateWithUser = statsig.getFeatureGate(user, "my_feature_gate"); ``` #### Kotlin ```kotlin val userID = "user_id" val gate = statsig.getFeatureGate(userID, "my_feature_gate") println("Gate name: ${gate.name}") println("Gate value: ${gate.value}") println("Rule ID: ${gate.ruleID}") // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() val gateWithUser = statsig.getFeatureGate(user, "my_feature_gate") ``` ### Parameter stores If you want dynamic control over whether a value comes from a Feature Gate, Experiment, or Dynamic Config outside your deployment cycle, use Parameter Stores. A Parameter Store lets you define a parameter that you can change at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application supports future flexibility and allows non-technical Statsig users to turn parameters into experiments. #### Java ```java String userID = "user_id"; ParameterStore store = statsig.getParameterStore(userID, "my_param_store"); String stringValue = store.getString("string_param", "default"); int intValue = store.getInt("int_param", 0); boolean boolValue = store.getBoolean("bool_param", false); double doubleValue = store.getDouble("double_param", 0.0); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); ParameterStore storeWithUser = statsig.getParameterStore(user, "my_param_store"); ``` #### Kotlin ```kotlin val userID = "user_id" val store = statsig.getParameterStore(userID, "my_param_store") val stringValue = store.getString("string_param", "default") val intValue = store.getInt("int_param", 0) val boolValue = store.getBoolean("bool_param", false) val doubleValue = store.getDouble("double_param", 0.0) // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() val storeWithUser = statsig.getParameterStore(user, "my_param_store") ``` ### Logging an event After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata: #### Java ```java import java.util.HashMap; import java.util.Map; String userID = "user_id"; String eventName = "my_custom_event"; // Simple event statsig.logEvent(userID, eventName); // Event with value statsig.logEvent(userID, eventName, 10.5); // Event with metadata Map<String, String> metadata = new HashMap<>(); metadata.put("key1", "value1"); metadata.put("key2", "value2"); statsig.logEvent(userID, eventName, metadata); // Event with value and metadata statsig.logEvent(userID, eventName, 10.5, metadata); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); statsig.logEvent(user, eventName, 10.5, metadata); ``` #### Kotlin ```kotlin val userID = "user_id" val eventName = "my_custom_event" // Simple event statsig.logEvent(userID, eventName) // Event with value statsig.logEvent(userID, eventName, 10.5) // Event with metadata val metadata = mapOf( "key1" to "value1", "key2" to "value2" ) statsig.logEvent(userID, eventName, metadata) // Event with value and metadata statsig.logEvent(userID, eventName, 10.5, metadata) // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() statsig.logEvent(user, eventName, 10.5, metadata) ``` ### Sending events to Log Explorer You can forward logs to Logs Explorer for analysis using the Forward Log Line Event API. The API lets you include custom metadata and event values with each log. #### Java ```java import java.util.HashMap; import java.util.Map; String userID = "user_id"; Map<String, Object> payload = new HashMap<>(); payload.put("log_level", "error"); payload.put("message", "Something went wrong"); payload.put("timestamp", System.currentTimeMillis()); statsig.forwardLogLineEvent(userID, payload); // with StatsigUser StatsigUser user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build(); statsig.forwardLogLineEvent(user, payload); ``` #### Kotlin ```kotlin val userID = "user_id" val payload = mapOf( "log_level" to "error", "message" to "Something went wrong", "timestamp" to System.currentTimeMillis() ) statsig.forwardLogLineEvent(userID, payload) // with StatsigUser val user = StatsigUser.builder() .userID("user_id") .email("my_user@example.com") .build() statsig.forwardLogLineEvent(user, payload) ``` ## Using shared instance To access a single Statsig instance globally throughout your codebase, use the shared instance singleton pattern: #### Java ```java import com.statsig.*; // Create a shared instance that can be accessed globally StatsigServer statsig = Statsig.newShared("secret-key"); statsig.initialize().get(); // Access the shared instance from anywhere in your code StatsigServer sharedStatsig = Statsig.shared(); boolean isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name"); // Check if a shared instance exists if (Statsig.hasSharedInstance()) { // Use the shared instance } // Remove the shared instance when no longer needed Statsig.removeShared(); ``` #### Kotlin ```kotlin import com.statsig.* // Create a shared instance that can be accessed globally val statsig = Statsig.newShared("secret-key") statsig.initialize().get() // Access the shared instance from anywhere in your code val sharedStatsig = Statsig.shared() val isFeatureEnabled = sharedStatsig.checkGate(user, "feature_name") // Check if a shared instance exists if (Statsig.hasSharedInstance()) { // Use the shared instance } // Remove the shared instance when no longer needed Statsig.removeShared() ``` - `Statsig.newShared(sdkKey, options)`: Creates a new shared instance of Statsig that you can access globally - `Statsig.shared()`: Returns the shared instance - `Statsig.hasSharedInstance()`: Checks if a shared instance exists (useful when you aren't sure if the shared instance is ready yet) - `Statsig.removeShared()`: Removes the shared instance (useful when you want to switch to a new shared instance) > **Note:** > > `hasSharedInstance()` and `removeShared()` are helpful in specific scenarios but aren't required in most use cases where the shared instance is set up near the top of your application. > > Also note that only one shared instance can exist at a time. Attempting to create a second shared instance results in an error. ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call `get()` on a layer parameter. To delay exposure logging until the user actually uses the feature, use manual exposures. #### Java ```java String userID = "user_id"; // Check gate without logging exposure boolean result = statsig.checkGateWithExposureLoggingDisabled(userID, "my_feature_gate"); // Manually log the exposure when ready statsig.manuallyLogGateExposure(userID, "my_feature_gate"); // Works with configs too DynamicConfig config = statsig.getConfigWithExposureLoggingDisabled(userID, "my_config"); statsig.manuallyLogConfigExposure(userID, "my_config"); // And with experiments/layers Experiment experiment = statsig.getExperimentWithExposureLoggingDisabled(userID, "my_experiment"); statsig.manuallyLogExperimentExposure(userID, "my_experiment"); Layer layer = statsig.getLayerWithExposureLoggingDisabled(userID, "my_layer"); statsig.manuallyLogLayerParameterExposure(userID, "my_layer", "parameter_name"); ``` #### Kotlin ```kotlin val userID = "user_id" // Check gate without logging exposure val result = statsig.checkGateWithExposureLoggingDisabled(userID, "my_feature_gate") // Manually log the exposure when ready statsig.manuallyLogGateExposure(userID, "my_feature_gate") // Works with configs too val config = statsig.getConfigWithExposureLoggingDisabled(userID, "my_config") statsig.manuallyLogConfigExposure(userID, "my_config") // And with experiments/layers val experiment = statsig.getExperimentWithExposureLoggingDisabled(userID, "my_experiment") statsig.manuallyLogExperimentExposure(userID, "my_experiment") val layer = statsig.getLayerWithExposureLoggingDisabled(userID, "my_layer") statsig.manuallyLogLayerParameterExposure(userID, "my_layer", "parameter_name") ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks). In addition to `userID`, the top-level fields on `StatsigUser` are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass key-value pairs in the `custom` field for targeting. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services. #### Java ```java import com.statsig.*; import java.util.HashMap; import java.util.Map; // Build a user with various fields Map<String, Object> customFields = new HashMap<>(); customFields.put("plan", "premium"); customFields.put("age", 25); Map<String, String> privateAttributes = new HashMap<>(); privateAttributes.put("internal_id", "123456"); StatsigUser user = StatsigUser.builder() .userID("user_123") .email("user@example.com") .ip("192.168.1.1") .userAgent("Mozilla/5.0...") .country("US") .locale("en_US") .appVersion("1.2.3") .custom(customFields) .privateAttributes(privateAttributes) .build(); // Use the user for evaluation boolean result = statsig.checkGate(user, "my_feature_gate"); ``` #### Kotlin ```kotlin import com.statsig.* // Build a user with various fields val customFields = mapOf( "plan" to "premium", "age" to 25 ) val privateAttributes = mapOf( "internal_id" to "123456" ) val user = StatsigUser.builder() .userID("user_123") .email("user@example.com") .ip("192.168.1.1") .userAgent("Mozilla/5.0...") .country("US") .locale("en_US") .appVersion("1.2.3") .custom(customFields) .privateAttributes(privateAttributes) .build() // Use the user for evaluation val result = statsig.checkGate(user, "my_feature_gate") ``` ## Private attributes Statsig evaluates private attributes normally but doesn't log them in events sent to Statsig servers. Use them for PII or other sensitive data. #### Java ```java Map<String, String> privateAttributes = new HashMap<>(); privateAttributes.put("sensitive_field", "sensitive_value"); StatsigUser user = StatsigUser.builder() .userID("user_123") .privateAttributes(privateAttributes) .build(); ``` #### Kotlin ```kotlin val privateAttributes = mapOf( "sensitive_field" to "sensitive_value" ) val user = StatsigUser.builder() .userID("user_123") .privateAttributes(privateAttributes) .build() ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | string | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specsUrl | string | No | — | Custom URL for fetching feature specifications. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specsSyncIntervalMs | long | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallbackToStatsig | boolean | No | — | Turn this on if you're proxying `download_config_specs` / `get_id_lists` and want to fall back to the default Statsig endpoint to increase reliability. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logEventUrl | string | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableAllLogging | boolean | No | — | If true, the SDK doesn't collect any logging within the session, including custom events and config check exposure events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enableIDLists | boolean | No | — | Required to be `true` when using segments with more than 1000 IDs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableUserAgentParsing | boolean | No | — | If true, the SDK doesn't parse User-Agent strings into `browserName`, `browserVersion`, `systemName`, `systemVersion`, and `appVersion` when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableUserCountryLookup | boolean | No | — | If true, the SDK doesn't parse IP addresses (from `user.ip`) into country codes when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingFlushIntervalMs | long | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventLoggingMaxQueueSize | int | No | — | Maximum number of events to queue before forcing a flush. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataStore | DataStore | No | — | An adapter with custom storage behavior for config specs. Can also continuously fetch updates in place of the Statsig network. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyConfig | ProxyConfig | No | — | Configuration for connecting through an outbound HTTP proxy. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specAdapterConfigs | List<SpecAdapterConfig> | No | — | Advanced configuration for fetching specs from multiple sources or protocols, including [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) over gRPC websocket streaming.Each `SpecAdapterConfig` can set:- `adapterType`: one of `SpecAdapterType.DATA_STORE`, `SpecAdapterType.NETWORK_HTTP`, or `SpecAdapterType.NETWORK_GRPC_WEBSOCKET` - `specsUrl`: optional endpoint override for the adapter - `initTimeoutMs`: optional initialization timeout in milliseconds - `authenticationMode`: optional transport auth mode using `AuthenticationMode.NONE`, `AuthenticationMode.TLS`, or `AuthenticationMode.MTLS` - `caCertPath`, `clientCertPath`, `clientKeyPath`, `domainName`: optional TLS and mTLS fields for gRPC websocket connections | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | persistentStorage | PersistentStorage | No | — | Interface to use persistent storage within the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | outputLoggerLevel | OutputLogger.LogLevel | No | — | Set the logging level for the SDK. Options: `NONE`, `ERROR`, `WARN`, `INFO`, `DEBUG`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | observabilityClient | ObservabilityClient | No | — | Interface to integrate observability metrics exposed by the SDK. | --- #### Java ```java // Example usage StatsigOptions options = new StatsigOptions.Builder() .setEnvironment("staging") .setSpecsSyncIntervalMs(10000) .setEventLoggingFlushIntervalMs(5000) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` #### Kotlin ```kotlin // Example usage val options = StatsigOptions.Builder() .setEnvironment("staging") .setSpecsSyncIntervalMs(10000) .setEventLoggingFlushIntervalMs(5000) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build() val statsig = Statsig("secret-key", options) statsig.initialize().get() ``` ### Proxy and custom network routing Use `setProxyConfig(ProxyConfig)` if your service needs a standard outbound HTTP proxy for Statsig network calls. Use `setSpecAdapterConfigs(...)` if you're routing spec downloads through [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction). ```java ProxyConfig proxyConfig = new ProxyConfig(); proxyConfig.setProxyHost("proxy.example.com"); proxyConfig.setProxyPort(8080); proxyConfig.setProxyProtocol("https"); proxyConfig.setCaCertPath("/etc/ssl/certs/corporate-ca.pem"); // Optional StatsigOptions options = new StatsigOptions.Builder() .setProxyConfig(proxyConfig) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` `ProxyConfig` supports `proxyHost`, `proxyPort`, `proxyAuth`, `proxyProtocol`, and `caCertPath`. Set `caCertPath` when your environment requires a custom PEM CA bundle for outbound TLS. ### Statsig Forward Proxy example ```java import java.util.Collections; SpecAdapterConfig forwardProxyConfig = new SpecAdapterConfig() .setAdapterType(SpecAdapterType.NETWORK_GRPC_WEBSOCKET) .setSpecsUrl("http://forward-proxy.internal:50051") .setAuthenticationMode(AuthenticationMode.NONE); StatsigOptions options = new StatsigOptions.Builder() .setSpecAdapterConfigs(Collections.singletonList(forwardProxyConfig)) .setFallbackToStatsigApi(true) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` ## Client initialize response Use `getClientInitializeResponse` to generate bootstrap values for a client SDK from the Java Core SDK's cached specs. Bootstrapping supports server-side rendering (SSR) and avoids the client's initial evaluation request. Initialize the server SDK before generating a response. For an initialized server SDK and user, generate a response with the default options: ```java String bootstrapJson = statsig.getClientInitializeResponse(user); ``` #### Full code example and client bootstrapping `getClientInitializeResponse` returns a JSON string, not a Java object. This example uses an initialized `statsig` instance: ```java import com.statsig.ClientInitResponseOptions; import com.statsig.HashAlgo; import com.statsig.StatsigUser; StatsigUser user = new StatsigUser.Builder() .setUserID("a-user") .build(); // Use the default options. String bootstrapJson = statsig.getClientInitializeResponse(user); // Or scope the response to the client SDK key's target app. ClientInitResponseOptions options = new ClientInitResponseOptions(); options.setClientSDKKey("client-sdk-key"); options.setHashAlgo(HashAlgo.DJB2); options.setIncludeLocalOverrides(false); String filteredBootstrapJson = statsig.getClientInitializeResponse(user, options); ``` Return the JSON string as the body of your bootstrap endpoint with `Content-Type: application/json`. If your framework serializes objects to JSON, parse the string first. Serializing the string again produces a quoted JSON string instead of the bootstrap object. Pass the response to your client SDK's bootstrap API. For the JavaScript client, follow [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter). #### Initialize response options `ClientInitResponseOptions` supports these bootstrapping options: | Setter | Type | Behavior | | --- | --- | --- | | `setHashAlgo` | `HashAlgo` | Controls config-name hashing: `DJB2` (default), `SHA256`, or `NONE` (unhashed). Name hashing isn't encryption or an integrity check. | | `setClientSDKKey` | `String` | Restricts the response to the client key's [target app](https://docs.statsig.com/sdks/target-apps). Use the key that initializes the client SDK. | | `setIncludeLocalOverrides` | `boolean` | Includes local overrides in evaluations when `true`. Defaults to `false`. | Use the setters rather than assigning the public fields directly. The setters also update the values that Java Core passes to the native SDK. Unlike Node Core, Java Core doesn't expose individual config-name filters in this options class. #### Hash algorithm Choose how the response hashes config names. The default is `djb2`; choose no hashing only when your client integration requires unhashed names. ```java ClientInitResponseOptions options = new ClientInitResponseOptions(); options.setHashAlgo(HashAlgo.DJB2); String bootstrapJson = statsig.getClientInitializeResponse(user, options); ``` #### Client SDK key Use the client SDK key to apply its [target-app restrictions](https://docs.statsig.com/sdks/target-apps) to the response. ```java ClientInitResponseOptions options = new ClientInitResponseOptions(); options.setClientSDKKey("client-sdk-key"); String bootstrapJson = statsig.getClientInitializeResponse(user, options); ``` #### Include local overrides Set this option to include local overrides when generating bootstrap values for development or testing. ```java ClientInitResponseOptions options = new ClientInitResponseOptions(); options.setIncludeLocalOverrides(true); String bootstrapJson = statsig.getClientInitializeResponse(user, options); ``` #### Match the client user Generate the response for the same user ID, custom IDs, and evaluation attributes that the client SDK uses. When targeting depends on IP address or user agent, pass those request attributes to the server-side user. If you use Stable ID, share the same `stableID` custom ID between server and client. Keep the server secret key on the server. Send each user only their own bootstrap response, and don't share a cached response across users. Config-name filters and name hashing aren't substitutes for authorization. ## Shutting Statsig down Because the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before shutting down your app or server: #### Java ```java // Shutdown flushes all pending events and stops background tasks statsig.shutdown(); // Or with a timeout (blocks until shutdown completes or timeout) statsig.shutdown().get(5, TimeUnit.SECONDS); ``` #### Kotlin ```kotlin // Shutdown flushes all pending events and stops background tasks statsig.shutdown() // Or with a timeout (blocks until shutdown completes or timeout) statsig.shutdown().get(5, TimeUnit.SECONDS) ``` ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing purposes, without changing the configuration in the Statsig console. #### Java ```java import java.util.HashMap; import java.util.Map; // Override a gate statsig.overrideGate("my_feature_gate", true); // Override a config Map<String, Object> configOverride = new HashMap<>(); configOverride.put("key", "value"); configOverride.put("number", 42); statsig.overrideConfig("my_config", configOverride); // Override an experiment Map<String, Object> experimentOverride = new HashMap<>(); experimentOverride.put("variant", "test"); statsig.overrideExperiment("my_experiment", experimentOverride); // Override an experiment to a particular groupname statsig.overrideExperimentByGroupName("my_experiment", "a_group_name"); statsig.overrideExperimentByGroupName("my_experiment", "a_group_name", "user_123"); // Override a layer Map<String, Object> layerOverride = new HashMap<>(); layerOverride.put("layer_param", "override_value"); statsig.overrideLayer("my_layer", layerOverride); // Clear all overrides statsig.clearAllOverrides(); // Clear specific override statsig.clearGateOverride("my_feature_gate"); statsig.clearConfigOverride("my_config"); ``` #### Kotlin ```kotlin // Override a gate statsig.overrideGate("my_feature_gate", true) // Override a config val configOverride = mapOf( "key" to "value", "number" to 42 ) statsig.overrideConfig("my_config", configOverride) // Override an experiment val experimentOverride = mapOf( "variant" to "test" ) statsig.overrideExperiment("my_experiment", experimentOverride) // Override an experiment to a particular groupname statsig.overrideExperimentByGroupName("my_experiment", "a_group_name") statsig.overrideExperimentByGroupName("my_experiment", "a_group_name", "user_123") // Override a layer val layerOverride = mapOf( "layer_param" to "override_value" ) statsig.overrideLayer("my_layer", layerOverride) // Clear all overrides statsig.clearAllOverrides() // Clear specific override statsig.clearGateOverride("my_feature_gate") statsig.clearConfigOverride("my_config") ``` ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. Use it to persist user assignments across sessions, ensuring consistent experiment groups when users return. Persistent storage is useful for client-side A/B testing where you need users to always see the same variant. #### Java ```java import com.statsig.*; import java.util.HashMap; import java.util.Map; class MyPersistentStorage implements PersistentStorage { private Map<String, Map<String, StickyValues>> storage = new HashMap<>(); @Override public Map<String, StickyValues> load(String key) { // Load persisted sticky values for the given key // Key format is "{userId}:userID" or "{customId}:{idType}" return storage.get(key); } @Override public void save(String key, String configName, StickyValues data) { // Save sticky values for a specific experiment/config storage.computeIfAbsent(key, k -> new HashMap<>()).put(configName, data); } @Override public void delete(String key, String configName) { // Delete sticky values for a specific experiment/config Map<String, StickyValues> values = storage.get(key); if (values != null) { values.remove(configName); } } } // Use persistent storage StatsigOptions options = new StatsigOptions.Builder() .setPersistentStorage(new MyPersistentStorage()) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` #### Kotlin ```kotlin import com.statsig.* class MyPersistentStorage : PersistentStorage { private val storage = mutableMapOf<String, MutableMap<String, StickyValues>>() override fun load(key: String): Map<String, StickyValues>? { // Load persisted sticky values for the given key // Key format is "{userId}:userID" or "{customId}:{idType}" return storage[key] } override fun save(key: String, configName: String, data: StickyValues) { // Save sticky values for a specific experiment/config storage.getOrPut(key) { mutableMapOf() }[configName] = data } override fun delete(key: String, configName: String) { // Delete sticky values for a specific experiment/config storage[key]?.remove(configName) } } // Use persistent storage val options = StatsigOptions.Builder() .setPersistentStorage(MyPersistentStorage()) .build() val statsig = Statsig("secret-key", options) statsig.initialize().get() ``` ### Helper methods The `PersistentStorage` interface provides helper methods for working with user-based storage keys: ```java // Get persisted values for a user using the helper method Map<String, StickyValues> values = persistentStorage.getValuesForUser(user, "userID"); // Generate a storage key from a user and ID type String key = PersistentStorage.getStorageKey(user, "userID"); // Returns "{userId}:userID" String customKey = PersistentStorage.getStorageKey(user, "companyID"); // Returns "{companyId}:companyID" ``` ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems such as Redis. #### Java ```java import com.statsig.*; class MyDataStore implements DataStore { @Override public String getDataSync(String key) { // Synchronously fetch data for the given key // This is called during SDK evaluation return null; } @Override public CompletableFuture<Void> setData(String key, String data) { // Store data for the given key // Called when SDK receives updates from Statsig return CompletableFuture.completedFuture(null); } @Override public CompletableFuture<Void> initialize() { // Perform any initialization needed for your data store return CompletableFuture.completedFuture(null); } @Override public void shutdown() { // Clean up resources } } // Use data store StatsigOptions options = new StatsigOptions.Builder() .setDataStore(new MyDataStore()) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` #### Kotlin ```kotlin import com.statsig.* import java.util.concurrent.CompletableFuture class MyDataStore : DataStore { override fun getDataSync(key: String): String? { // Synchronously fetch data for the given key // This is called during SDK evaluation return null } override fun setData(key: String, data: String): CompletableFuture<Void> { // Store data for the given key // Called when SDK receives updates from Statsig return CompletableFuture.completedFuture(null) } override fun initialize(): CompletableFuture<Void> { // Perform any initialization needed for your data store return CompletableFuture.completedFuture(null) } override fun shutdown() { // Clean up resources } } // Use data store val options = StatsigOptions.Builder() .setDataStore(MyDataStore()) .build() val statsig = Statsig("secret-key", options) statsig.initialize().get() ``` ## Custom output logger The Output Logger interface lets you customize how the SDK logs messages and enables integration with your own logging system and control over log verbosity. #### Java ```java import com.statsig.*; class MyOutputLogger implements OutputLogger { @Override public void log(LogLevel level, String message) { // Route SDK logs to your logging system switch (level) { case ERROR: System.err.println("[ERROR] " + message); break; case WARN: System.out.println("[WARN] " + message); break; case INFO: System.out.println("[INFO] " + message); break; case DEBUG: System.out.println("[DEBUG] " + message); break; } } } // Use custom output logger StatsigOptions options = new StatsigOptions.Builder() .setOutputLogger(new MyOutputLogger()) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` #### Kotlin ```kotlin import com.statsig.* class MyOutputLogger : OutputLogger { override fun log(level: OutputLogger.LogLevel, message: String) { // Route SDK logs to your logging system when (level) { OutputLogger.LogLevel.ERROR -> println("[ERROR] $message") OutputLogger.LogLevel.WARN -> println("[WARN] $message") OutputLogger.LogLevel.INFO -> println("[INFO] $message") OutputLogger.LogLevel.DEBUG -> println("[DEBUG] $message") else -> {} } } } // Use custom output logger val options = StatsigOptions.Builder() .setOutputLogger(MyOutputLogger()) .setOutputLoggerLevel(OutputLogger.LogLevel.INFO) .build() val statsig = Statsig("secret-key", options) statsig.initialize().get() ``` ## Observability client The Observability Client interface lets you monitor SDK health by integrating with your own observability systems. For more information on the metrics emitted by Statsig SDKs, go to the [Monitoring documentation](https://docs.statsig.com/infrastructure/sdk-monitoring). #### Java ```java import com.statsig.*; class MyObservabilityClient implements ObservabilityClient { @Override public void emitMetric(String metricName, double value, Map<String, String> tags) { // Send metric to your monitoring system System.out.println("Metric: " + metricName + " = " + value + ", tags: " + tags); } @Override public void startTimer(String operationName) { // Start timing an operation } @Override public void endTimer(String operationName, Map<String, String> tags) { // End timing and emit duration metric } } // Use observability client StatsigOptions options = new StatsigOptions.Builder() .setObservabilityClient(new MyObservabilityClient()) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); ``` #### Kotlin ```kotlin import com.statsig.* class MyObservabilityClient : ObservabilityClient { override fun emitMetric(metricName: String, value: Double, tags: Map<String, String>) { // Send metric to your monitoring system println("Metric: $metricName = $value, tags: $tags") } override fun startTimer(operationName: String) { // Start timing an operation } override fun endTimer(operationName: String, tags: Map<String, String>) { // End timing and emit duration metric } } // Use observability client val options = StatsigOptions.Builder() .setObservabilityClient(MyObservabilityClient()) .build() val statsig = Statsig("secret-key", options) statsig.initialize().get() ``` ## FAQ #### What Java versions are supported? The Java Core SDK supports Java 8 and higher. Statsig added Java 8 support in version 0.4.3. #### Which platforms are supported? The SDK supports: - Linux (x86\_64, arm64, musl variants) - macOS (x86\_64, arm64) - Windows (x86\_64) Refer to the Tested Platforms section for verified Docker images. #### Should I use the uber JAR or platform-specific JARs? Statsig recommends the uber JAR for most use cases, as it includes native libraries for all popular platforms and simplifies deployment. Use platform-specific JARs only if you need to minimize JAR size or have specific dependency requirements. #### How do I use this with Alpine Linux? For Alpine Linux (musl-based systems), install compatibility packages: ```dockerfile RUN apk add --no-cache libgcc gcompat ``` The SDK automatically uses musl-compatible native libraries. #### How do I handle initialization in production? The SDK initialization is asynchronous. Use `.get()` on the CompletableFuture to wait for initialization: ```java Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); // Blocks until initialized ``` Always call `shutdown()` when your application stops to flush pending events. #### Can I use multiple Statsig instances? Yes, you can create multiple Statsig instances with different configurations. You can also use the global singleton with `Statsig.getGlobalSingleton()` for convenience. #### How do I debug SDK issues? Set the output logger level to DEBUG to see detailed logs: ```java StatsigOptions options = new StatsigOptions.Builder() .setOutputLoggerLevel(OutputLogger.LogLevel.DEBUG) .build(); ``` ## Reference ### FeatureGate class ```java class FeatureGate { String name; // Gate name boolean value; // Evaluation boolean result String ruleID; // Rule ID for this gate EvaluationDetails evaluationDetails; // Evaluation details String rawJson; // Raw JSON string representation } ``` ### Experiment class ```java class Experiment { String name; // Name of the experiment String ruleID; // ID of the rule used in the experiment Map<String, JsonElement> value; // Configuration values specific to the experiment String groupName; // The group name the user falls into EvaluationDetails evaluationDetails; // Details about how the experiment was evaluated String rawJson; // Raw JSON representation of the experiment } ``` **Methods for Experiment:** ```java public String getString(String key, String fallbackValue) public boolean getBoolean(String key, Boolean fallbackValue) public double getDouble(String key, double fallbackValue) public int getInt(String key, int fallbackValue) public long getLong(String key, long fallbackValue) public Object[] getArray(String key, Object[] fallbackValue) public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue) ``` ### DynamicConfig class ```java class DynamicConfig { String name; // Name of the config String ruleID; // ID of the rule used Map<String, JsonElement> value; // Configuration values EvaluationDetails evaluationDetails; // Details about how the config was evaluated String rawJson; // Raw JSON representation } ``` **Methods for DynamicConfig:** ```java public String getString(String key, String fallbackValue) public boolean getBoolean(String key, Boolean fallbackValue) public double getDouble(String key, double fallbackValue) public int getInt(String key, int fallbackValue) public long getLong(String key, long fallbackValue) public Object[] getArray(String key, Object[] fallbackValue) public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue) ``` ### Layer class ```java class Layer { String name; // Layer name String ruleID; // Rule ID for this layer String groupName; // Group name Map<String, JsonElement> value; // Layer values String allocatedExperimentName; // Allocated experiment name EvaluationDetails evaluationDetails; // Evaluation details String rawJson; // Raw JSON string representation } ``` **Methods for Layer:** ```java public String getString(String key, String fallbackValue) public boolean getBoolean(String key, Boolean fallbackValue) public double getDouble(String key, double fallbackValue) public int getInt(String key, int fallbackValue) public long getLong(String key, long fallbackValue) public Object[] getArray(String key, Object[] fallbackValue) public Map<String, Object> getMap(String key, Map<String, Object> fallbackValue) ``` ### Fields needed methods (Enterprise only) > **Info:** > > This is available for Enterprise contracts. Reach out to the Statsig support team, your sales contact, or through the [Slack community](https://statsig.com/slack) to enable it. These methods let you retrieve a list of user fields used in the targeting rules for gates, configs, experiments, and layers. ```java // Get user fields needed for a gate evaluation List<String> getFieldsNeededForGate(String gateName) // Get user fields needed for a dynamic config evaluation List<String> getFieldsNeededForDynamicConfig(String configName) // Get user fields needed for an experiment evaluation List<String> getFieldsNeededForExperiment(String experimentName) // Get user fields needed for a layer evaluation List<String> getFieldsNeededForLayer(String layerName) ``` **Field Mapping** The fields returned by these methods correspond to the following user properties: ```java // Field mapping between user properties and internal field names userID -> "u" email -> "e" ip -> "i" userAgent -> "ua" country -> "c" locale -> "l" appVersion -> "a" time -> "t" stableID -> "s" environment -> "en" targetApp -> "ta" // Custom fields are prefixed with "cf:" // Example: "cf:plan", "cf:age" ``` ================================================================================ # Go Server Core SDK URL: https://docs.statsig.com/server-core/go-core ================================================================================ # Go Server Core SDK - **Package:** `github.com/statsig-io/statsig-go-core` ([gomod](https://pkg.go.dev/github.com/statsig-io/statsig-go-core)) - **Latest version:** v0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-go) ## Setup the SDK 1. **Install the SDK** Using the `go get` CLI, install the latest version of the SDK: ```plaintext go get github.com/statsig-io/statsig-go-core@latest ``` Or add a dependency on the most recent version in go.mod: ```plaintext require ( github.com/statsig-io/statsig-go-core v0.23.2 ) ``` Go to the [Releases tab in GitHub](https://github.com/statsig-io/statsig-server-core/releases) for the latest versions. :::note `go get` requires a Go module project with a go.mod file. ::: 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. ```go import ( "log" statsig "github.com/statsig-io/statsig-go-core" ) options, err := statsig.NewOptionsBuilder(). WithOutputLogLevel("DEBUG"). Build() if err != nil { log.Fatalf("failed to build options: %v", err) } s, err := statsig.NewStatsigWithOptions("secret-key", options) if err != nil { log.Fatalf("failed to create Statsig client: %v", err) } s.Initialize() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). To check a gate for a user: ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() // Basic check if s.CheckGate(user, "a_gate") { // Gate is on, enable new feature } else { // Gate is off } // With options (e.g., disable automatic exposure logging) options := &statsig.FeatureGateEvaluationOptions{DisableExposureLogging: true} s.CheckGateWithOptions(user, "a_gate", options) ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example: ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() // You can disable exposure logging for this specific check dynamicConfigOptions := &statsig.DynamicConfigEvaluationOptions{DisableExposureLogging: false} dynamic_config := "a_config" config := s.GetDynamicConfigWithOptions(user, dynamic_config, dynamicConfigOptions) // Access the config values str_val := config.GetString("str_val", "default_str_val") // returns String int_val := config.GetNumber("number_val", 100) // returns float64 bool_val := config.GetBool("bool_val", false) // returns bool interface_val := config.GetSlice("interface_val", []any{"default_interface_val"}) // returns []any map_val := config.GetMap("map_val", map[string]any{"default": "value"}) // returns map[string]interface{} // The config object also provides metadata about the evaluation fmt.Println(config.RuleID) // The ID of the rule that served this config fmt.Println(config.IDType) // The type of the evaluation (experiment, config, etc) ``` ### Getting a layer/experiment **Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) because layers make parameters reusable and support mutually exclusive experiments. ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() // Getting values with GetExperiment experimentOptions := &statsig.ExperimentEvaluationOptions{DisableExposureLogging: false} experiment := s.GetExperimentWithOptions(user, "a_test_experiment", experimentOptions) str_val := experiment.GetString("str_val", "default_str_val") // returns String int_val := experiment.GetNumber("number_val", 100) // returns float64 // Getting values with GetLayer layerOptions := &statsig.LayerEvaluationOptions{DisableExposureLogging: false} layer := s.GetLayerWithOptions(user, "a_test_experiment", layerOptions) str_val := layer.GetString("str_val", "default_str_val") // returns String int_val := layer.GetNumber("number_val", 100) // returns float64 ``` ### Retrieving feature gate metadata To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object: ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() options := &statsig.FeatureGateEvaluationOptions{DisableExposureLogging: false} featureGate := s.GetFeatureGateWithOptions(user, "a_gate", options) ``` ### Logging an event After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata: ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() event := statsig.EventPayload{ EventName: "sample_event", Value: "event", Metadata: map[string]string{ "val_1": "log val 1", }, } s.LogEvent(user, event) ``` ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call `get()` on a layer parameter. To delay exposure logging until the user actually uses the feature, use manual exposures. All main SDK functions (`CheckGate`, `GetDynamicConfig`, `GetExperiment`, `GetLayer`) accept an optional options parameter with a `DisableExposureLogging` field. When set to `true`, the SDK doesn't automatically log an exposure event. You can then manually log the exposure using the corresponding manual exposure logging method: #### Feature Gates ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() options := &statsig.FeatureGateEvaluationOptions{DisableExposureLogging: true} result := s.CheckGateWithOptions(user, "a_gate_name", options) ``` ```go s.ManuallyLogFeatureGateExposure(user, "gate_name") ``` #### Dynamic Configs ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() options := &statsig.DynamicConfigEvaluationOptions{DisableExposureLogging: true} config := s.GetDynamicConfigWithOptions(user, "config_name", options) ``` ```go s.ManuallyLogDynamicConfigExposure(user, "config_name") ``` #### Experiments ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() options := &statsig.ExperimentEvaluationOptions{DisableExposureLogging: true} experiment := s.GetExperimentWithOptions(user, "experiment_name", options) ``` ```go s.ManuallyLogExperimentExposure(user, "experiment_name") ``` #### Layers ```go user, _ := statsig.NewUserBuilderWithUserID("a-user").Build() options := &statsig.LayerEvaluationOptions{DisableExposureLogging: true} layer := s.GetLayerWithOptions(user, "layer_name", options) paramValue := layer.GetString("param_name", "fallback") ``` ```go s.ManuallyLogLayerParamExposure(user, "layer_name", "param_name") ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks). In addition to `userID`, the top-level fields on `StatsigUser` are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass key-value pairs in the `custom` field for targeting. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services. ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. ### Parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | SpecsUrl | string | No | — | Custom URL for fetching feature specifications. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | LogEventUrl | string | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | Environment | string | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | EventLoggingFlushIntervalMs | number | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | EventLoggingMaxQueueSize | number | No | — | Maximum number of events to queue before forcing a flush. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | SpecsSyncIntervalMs | number | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | OutputLogLevel | string | No | — | Controls the verbosity of SDK logs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | DisableCountryLookup | boolean | No | — | Disables country lookup based on IP address. Set to `true` to improve performance if country-based targeting isn't needed. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | DisableUserAgentParsing | boolean | No | — | Disables user agent parsing. Set to `true` to improve performance if device/browser-based targeting isn't needed. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | WaitForCountryLookupInit | boolean | No | — | When set to `true`, the SDK waits for country lookup data (such as GeoIP or YAML files) to fully load during initialization. This may add approximately 1 second to startup time, but ensures that IP-to-country parsing is ready at evaluation time. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | WaitForUserAgentInit | boolean | No | — | When set to `true`, the SDK waits until user agent parsing data is fully loaded during initialization. This may add approximately 1 second to startup time, but ensures that parsing of the user's `userAgent` string into fields such as `browserName`, `browserVersion`, `systemName`, `systemVersion`, and `appVersion` is ready before any evaluations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | EnableIdLists | boolean | No | — | Enables downloading ID lists; set to false to skip ID list syncing. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | IdListsUrl | string | No | — | Custom URL for fetching ID lists. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | IdListsSyncIntervalMs | number | No | — | How often the SDK syncs ID lists (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | DisableAllLogging | boolean | No | — | When set to true, the SDK doesn't log any events or exposures. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | DisableNetwork | boolean | No | — | When set to true, the SDK doesn't make any network requests. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | GlobalCustomFields | string | No | — | JSON string of custom fields that should be appended to every evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | ObservabilityClientRef | number | No | — | Internal reference for a custom observability client created through the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | DataStoreRef | number | No | — | Internal reference for a custom data store adapter created through the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | PersistentStorageRef | number | No | — | Internal reference for a persistent storage adapter created through the SDK. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | InitTimeoutMs | number | No | — | Maximum time in milliseconds to wait for SDK initialization to complete. If initialization takes longer than this timeout, the SDK continues to operate but may return default values until initialization completes. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | FallbackToStatsigApi | boolean | No | — | When set to true, the SDK falls back to using the Statsig API directly if custom adapters (like local file adapters) fail to load configurations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | SpecAdapterConfig | SpecAdapterConfig | No | — | Configures the source used to retrieve feature specifications. Use `SpecAdapterTypeNetworkGrpcWebsocket` to stream specifications from the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy). The Go SDK accepts one spec adapter. If the configured source is unavailable during initialization, initialization fails after the adapter initialization timeout. | ### Proxy and custom network routing Use `WithSpecAdapterConfig` to stream feature specifications from the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy) over gRPC websocket. ```go options, err := statsig.NewOptionsBuilder(). WithSpecAdapterConfig(statsig.SpecAdapterConfig{ AdapterType: statsig.SpecAdapterTypeNetworkGrpcWebsocket, SpecsUrl: "http://forward-proxy.internal:50051", AuthenticationMode: statsig.AuthenticationModeNone, }). Build() if err != nil { // Handle options build error. } statsigClient, err := statsig.NewStatsigWithOptions("server-secret-key", options) if err != nil { // Handle client creation error. } statsigClient.Initialize() ``` `InitTimeoutMs` controls the initial specification sync timeout and defaults to 3000 milliseconds when set to `0`. For TLS, set `AuthenticationMode` to `statsig.AuthenticationModeTls` and provide `CaCertPath`. For mTLS, use `statsig.AuthenticationModeMtls` and also provide `ClientCertPath` and `ClientKeyPath`. Use `DomainName` to override the TLS server name used for certificate verification. This adapter controls specification downloads only. Continue to use `WithLogEventUrl` and `WithIdListsUrl` when you need custom endpoints for event logging and ID lists. --- ### Example options usage ```go import ( statsig "github.com/statsig-io/statsig-go-core" ) // Initialize StatsigOptions with custom parameters options, err := statsig.NewOptionsBuilder(). WithSpecsUrl("https://example.com/specsUrl"). WithLogEventUrl("https://example.com/logUrl"). WithEnvironment("production"). WithEventLoggingFlushIntervalMs(2000). WithEventLoggingMaxQueueSize(5000). WithSpecsSyncIntervalMs(1000). WithOutputLogLevel("DEBUG"). WithDisableCountryLookup(true). WithDisableUserAgentParsing(true). WithWaitForCountryLookupInit(false). WithEnableIdLists(true). WithIdListsSyncIntervalMs(60000). WithInitTimeoutMs(3000). WithFallbackToStatsigApi(false). Build() if err != nil { // handle options build error } // Pass the options object when initializing the Statsig client s, err := statsig.NewStatsigWithOptions("secret-key", options) if err != nil { // handle init error } s.Initialize() ``` ## Client initialize response Use `GetClientInitResponse` to generate bootstrap values for a client SDK from the Go Core SDK's cached feature specifications. Bootstrapping supports server-side rendering (SSR) and avoids the client's initial evaluation request. Initialize the server SDK before generating a response. For an initialized server SDK and user, generate a response with the default options: ```go bootstrapJSON := s.GetClientInitResponse(user) if bootstrapJSON == nil { panic("client initialize response is unavailable") } ``` #### Full code example and client bootstrapping `GetClientInitResponse` and `GetClientInitResponseWithOptions` return a `*string` containing JSON, or `nil` if the response isn't available. This example uses an initialized `s` instance: ```go import ( "fmt" statsig "github.com/statsig-io/statsig-go-core" ) user, err := statsig.NewUserBuilderWithUserID("a-user").Build() if err != nil { panic(err) } // Use the default options. bootstrapJSON := s.GetClientInitResponse(user) if bootstrapJSON == nil { panic("client initialize response is unavailable") } fmt.Println(*bootstrapJSON) // Or restrict the response to a client key and selected configs. clientKey := "client-sdk-key" hashAlgorithm := "djb2" gates := []string{"onboarding_v2", "new_checkout"} experiments := []string{"pricing_experiment"} options := &statsig.ClientInitResponseOptions{ ClientSDKKey: &clientKey, HashAlgorithm: &hashAlgorithm, FeatureGateFilter: &gates, ExperimentFilter: &experiments, } filteredBootstrapJSON := s.GetClientInitResponseWithOptions(user, options) if filteredBootstrapJSON == nil { panic("client initialize response is unavailable") } fmt.Println(*filteredBootstrapJSON) ``` Return the dereferenced string as your HTTP response body with `Content-Type: application/json`. Don't pass the string directly to a JSON encoder, which encodes it as a quoted string. If you wrap the response in another JSON object, use `json.RawMessage` or parse the JSON first. Pass the response to your client SDK's bootstrap API. For the JavaScript client, follow [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter). #### Initialize response options All `ClientInitResponseOptions` fields are optional. Leave a field `nil` to use its default behavior. | Field | Type | Behavior | | --- | --- | --- | | `HashAlgorithm` | `*string` | Controls config-name hashing: `"djb2"` (default), `"sha256"`, or `"none"` (unhashed). Name hashing isn't encryption or an integrity check. | | `ClientSDKKey` | `*string` | Restricts the response to the client key's [target app](https://docs.statsig.com/sdks/target-apps). Use the key that initializes the client SDK. | | `IncludeLocalOverrides` | `*bool` | Includes local overrides in evaluations when `true`. Defaults to `false`. | | `FeatureGateFilter` | `*[]string` | Includes only the named feature gates. | | `ExperimentFilter` | `*[]string` | Includes only the named experiments. | | `DynamicConfigFilter` | `*[]string` | Includes only the named dynamic configs. | | `LayerFilter` | `*[]string` | Includes only the named layers. | | `ParamStoreFilter` | `*[]string` | Includes only the named parameter stores. | Filters take original config names, even when the response hashes those names. An unset filter doesn't restrict that config type. Use `ClientSDKKey` to apply target-app restrictions rather than relying on name filters alone. #### Hash algorithm Choose how the response hashes config names. The default is `djb2`; choose no hashing only when your client integration requires unhashed names. ```go hashAlgorithm := "djb2" options := &statsig.ClientInitResponseOptions{HashAlgorithm: &hashAlgorithm} bootstrapJSON := s.GetClientInitResponseWithOptions(user, options) ``` #### Client SDK key Use the client SDK key to apply its [target-app restrictions](https://docs.statsig.com/sdks/target-apps) to the response. ```go clientKey := "client-sdk-key" options := &statsig.ClientInitResponseOptions{ClientSDKKey: &clientKey} bootstrapJSON := s.GetClientInitResponseWithOptions(user, options) ``` #### Filtering Select specific config names to reduce the response size. Filters for other config types remain unset in this example. ```go gates := []string{"onboarding_v2", "new_checkout"} experiments := []string{"pricing_experiment"} options := &statsig.ClientInitResponseOptions{ FeatureGateFilter: &gates, ExperimentFilter: &experiments, } bootstrapJSON := s.GetClientInitResponseWithOptions(user, options) ``` #### Include local overrides Set this option to include local overrides when generating bootstrap values for development or testing. ```go includeOverrides := true options := &statsig.ClientInitResponseOptions{IncludeLocalOverrides: &includeOverrides} bootstrapJSON := s.GetClientInitResponseWithOptions(user, options) ``` #### Match the client user Generate the response for the same user ID, custom IDs, and evaluation attributes that the client SDK uses. When targeting depends on IP address or user agent, pass those request attributes to the server-side user. If you use Stable ID, share the same `stableID` custom ID between server and client. Keep the server secret key on the server. Send each user only their own bootstrap response, and don't share a cached response across users. Config-name filters and name hashing aren't substitutes for authorization. ## Shutting Statsig down Because the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before shutting down your app or server: ```go // Method signature func (s *Statsig) Shutdown() {} // example usage s, err := statsig.NewStatsig("secret-key") s.Initialize() s.Shutdown() ``` ### Flush events ```go // Method signature func (s *Statsig) FlushEvents() {} // example usage s, err := statsig.NewStatsig("secret-key") s.Initialize() s.FlushEvents() ``` ## FAQ ##### Installation FAQs #### How do I fix undefined symbol errors/linker errors You may need to reset your environment variables to those found in the `statsig.env` or `statsig.env.ps1` file generated during the post-install script. Running the command sets the environment variables for the current terminal session. Add the variables to your `.bashrc`, `.zshrc`, or `.ps1` file to load them automatically. ================================================================================ # Ruby Server SDK URL: https://docs.statsig.com/server/ruby ================================================================================ # Ruby Server SDK - **Package:** `statsig` ([rubygems](https://rubygems.org/gems/statsig)) - **Latest version:** 2.9.6 - **Repository:** [ruby-sdk](https://github.com/statsig-io/ruby-sdk) ## Setup the SDK 1. **Install the SDK** If you're using Bundler, add the [gem](https://rubygems.org/gems/statsig) to your Gemfile from command line: ```shell bundle add statsig ``` or directly include it in your Gemfile and run `bundle install`: ```shell gem "statsig", ">= X.Y.Z" ``` Check out the latest versions on [https://rubygems.org/gems/statsig](https://rubygems.org/gems/statsig) 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. ```ruby require 'statsig' Statsig.initialize('server-secret-key') ``` ```ruby # Or, if you want to initialize with certain options options = StatsigOptions.new({'tier' => 'staging'}, network_timeout: 5) # And a callback when the initialization network request fails def error_callback(e) puts e end ... Statsig.initialize('server-secret-key', options, method(:error_callback)) ``` ### Initializing Statsig in a Rails application If your application is using Rails, you should initialize Statsig in `config/initializers/statsig.rb`: ```ruby Statsig.initialize('server-secret-key', options) ``` ### Initializing Statsig when using Unicorn, Puma, Passenger, or Sidekiq For **Unicorn**, you should initialize Statsig within an `after_fork` hook in your `unicorn.rb` config file: ```ruby after_fork do |server,worker| Statsig.initialize('server-secret-key', options) end ``` For **Puma**, you should initialize Statsig within an `on_worker_boot` hook in your `puma.rb` config file: ```ruby on_worker_boot do Statsig.initialize('server-secret-key', options) end ``` For **Passenger**, you should initialize Statsig in your `config.ru` config file: ```ruby if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| Statsig.initialize('server-secret-key', options) end end ``` For **Sidekiq**, you should initialize Statsig in your `sidekiq.rb`/server configuration file: ```ruby Sidekiq.configure_server do |config| config.on(:startup) do Statsig.initialize end config.on(:shutdown) do Statsig.shutdown end end ``` If you're using Rails in combination with any of the above, initialize using the specific process lifecycle hooks exposed by the respective tool. You can initialize in multiple places to ensure the SDK is fully usable, including all background processing. `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```ruby user = StatsigUser.new({'userID' => 'some_user_id'}) if Statsig.check_gate(user, 'use_new_feature') # Gate is on, enable new feature else # Gate is off end ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```ruby config = Statsig.get_config(user, 'awesome_product_details') # The 2nd parameter is the default value to be used in case the given parameter name does not exist on # the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the # value has not been cached on the client. item_name = config.get('product_name', 'Awesome Product v1'); price = config.get('price', 10.0); shouldDiscount = config.get('discount', false); # Or just get the whole json object backing this config if you prefer json = config.value ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```ruby # Values via getLayer layer = Statsig.get_layer(user, "user_promo_experiments") title = layer.get("title", "Welcome to Statsig!") discount = layer.get("discount", 0.1) # or, via getExperiment title_exp = Statsig.get_experiment(user, "new_user_promo_title") price_exp = Statsig.get_experiment(user, "new_user_promo_price") title = title_exp.get("title", "Welcome to Statsig!") discount = price_exp.get("discount", 0.1) ... price = msrp * (1 - discount) ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```ruby Statsig.log_event( user, 'add_to_cart', 'SKU_12345', { 'price' => '9.99', 'item_name' => 'diet_coke_48_pack' } ) ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options `initialize()` takes an optional `options` parameter in addition to the secret key to customize the Statsig client. Available options: - **environment**: Hash, default `nil` - a Hash you can use to set environment variables that apply to all your users in the same session, for targeting purposes. - The most common usage is to set the "tier" (string), and have feature gates pass/fail for specific environments. The accepted values are "production", "staging" and "development", e.g. `StatsigOptions.New({ 'tier' => 'staging' })`. - **download\_config\_specs\_url**: String, default `"https://api.statsigcdn.com/v2/download_config_specs/"` - The url used specifically to call download\_config\_specs - **log\_event\_url**: String, default `"https://statsigapi.net/v1/log_event"` - The url used specifically to call log\_event - **get\_id\_lists\_url**: String, default `"https://statsigapi.net/v1/get_id_lists"` - The url used specifically to call get\_id\_lists - **rulesets\_sync\_interval**: Number, default `10` - The interval (in seconds) to poll for changes to your Statsig configuration - **idlists\_sync\_interval**: Number, default `60` - The interval (in seconds) to poll for changes to id lists - **disable\_rulesets\_sync**: Boolean, default `false` - Disable background syncing for rulesets - **disable\_idlists\_sync**: Boolean, default `false` - Disable background syncing for id lists - **logging\_interval\_seconds**: Number, default `60` - How often to flush logs to Statsig - **logging\_max\_buffer\_size**: Number, default `1000`, you can set it lower but the server drops anything over 1000 - The maximum number of events to batch before flushing logs to the server - **local\_mode**: Boolean, default `false` - Restricts the SDK to not issue any network requests and only respond with default values (or local overrides) - **bootstrap\_values**: String, default `nil` - A string that represents all rules for all feature gates, dynamic configs and experiments. Provide it to bootstrap the Statsig server SDK at initialization in case your server runs into network issue or Statsig server is down temporarily. - **rules\_updated\_callback**: function, default `nil` - A callback function called whenever the rulesets update - **data\_store**: IDataStore, default `nil` - A class that extends IDataStore. Use it to provide values from a common data store (like Redis) to initialize the Statsig SDK. - **idlist\_threadpool\_size**: Number, default `3` - The number of threads allocated to syncing IDLists - **logger\_threadpool\_size**: Number, default `3` - The number of threads allocated to posting event logs - **disable\_diagnostics\_logging**: Boolean, default `false` - Should diagnostics be logged. These include performance metrics for initialize - **disable\_sorbet\_logging\_handlers**: Boolean, default `false` - Statsig utilizes Sorbet (https://sorbet.org) to ensure type safety of the SDK. This includes logging to console when it detects errors. You can disable this logging by setting this flag to true. - **network\_timeout**: Number, default `nil` - Maximum number of seconds to wait for a network call before timing out - **post\_logs\_retry\_limit**: Number, default `3` - Number of times to retry sending a batch of failed log events - **post\_logs\_retry\_backoff**: Number/Function, default `nil` - The number of seconds, or a function that returns the number of seconds based on the number of retries remaining which overrides the default backoff time between retries - **user\_persistent\_storage**: IUserPersistentStorage, default `nil` - A storage adapter for persisted values. Use it for sticky bucketing users in experiments. Implements Statsig::Interfaces::IUserPersistentStorage. ## Shutdown To gracefully shutdown the SDK and flush all events: ```ruby Statsig.shutdown ``` ## Client SDK bootstrapping The Statsig server SDK can generate the initialization values for a client SDK. This is useful for server-side rendering (SSR) or when you want to pre-fetch values for a client. ```ruby values = Statsig.get_client_initialize_response(user); # Hash[String, Any] | Nil ``` ## Local Overrides You can override the values the SDK returns for testing purposes, which is useful for local development when testing specific scenarios. ```ruby # Adding gate overrides Statsig.override_gate("a_gate_name", true) # Adding config overrides Statsig.override_config("a_config_name", {"key" => "value"}) ``` > **Note:** > > 1. These only apply locally - they don't update definitions in the Statsig console or elsewhere. > 2. The local override API isn't designed to be a full mock. It's only a convenient way to override the value of the gate/config/etc. ## Manual Exposures Statsig SDKs automatically log an exposure event every time you check a gate/experiment/config. In some scenarios, you may want to control when to log an exposure. **Gates** ```ruby result = Statsig.check_gate(user, 'a_gate_name', CheckGateOptions.new(disable_log_exposure: true)) ``` ```ruby Statsig.manually_log_gate_exposure(user, 'a_gate_name') ``` **Configs** ```ruby config = Statsig.get_config(user, 'a_dynamic_config_name', GetConfigOptions.new(disable_log_exposure: true)) ``` ```ruby Statsig.manually_log_config_exposure(user, 'a_dynamic_config_name') ``` **Experiments** ```ruby experiment = Statsig.get_experiment(user, 'an_experiment_name', GetExperimentOptions.new(disable_log_exposure: true)) ``` ```ruby Statsig.manually_log_experiment_exposure(user, 'an_experiment_name') ``` **Layers** ```ruby layer = Statsig.get_layer(user, 'a_layer_name', GetLayerOptions.new(disable_log_exposure: true)) paramValue = layer.get('a_param_name', 'fallback_value') ``` ```ruby Statsig.manually_log_layer_parameter_exposure(user, 'a_layer_name', 'a_param_name') ``` ## User persistent storage User Persistent Storage is a storage adapter for running sticky experiments that persists user assignments across sessions. ### Interface ```ruby class IUserPersistentStorage def load(key) nil end def save(key, data) end end ``` ### Example Implementation ```ruby class DummyPersistentStorageAdapter < Statsig::Interfaces::IUserPersistentStorage attr_accessor :store def initialize @store = {} end def load(key) return nil unless @store&.key?(key) @store[key] end def save(key, data) @store[key] = data end end ``` ## Multi-instance usage To create multiple independent instances of the Statsig SDK (for example, to use different API keys or configurations), use the instance-based approach: ```ruby sdk_instance = StatsigDriver.new(secret_key, options, error_callback) ``` ## FAQ #### How do I run experiments for logged out users Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). #### How can I mock or override the SDK for testing Starting in `v1.12.0+`, the Ruby SDK supports `localMode` and `overrides`. Refer to [Local Overrides](#local-overrides). - `localMode` is a boolean parameter in `StatsigOptions` when initializing the SDK. It restricts all network traffic, so the SDK operates offline and only returns default or override values. #### Can I generate the initialize response for a client SDK using the Ruby server SDK Yes. Refer to [Client SDK Bootstrapping](#client-sdk-bootstrapping). ## Reference ### Type StatsigUser ```ruby export type StatsigUser = { class StatsigUser attr_accessor :user_id attr_accessor :email attr_accessor :ip attr_accessor :user_agent attr_accessor :country attr_accessor :locale attr_accessor :app_version attr_accessor :statsig_environment attr_accessor :custom_ids # Hash of key:string value:string attr_accessor :private_attributes # Hash of key:string value:string @custom # Hash of key:string value:string def initialize(user_hash) @statsig_environment = Hash.new if user_hash.is_a?(Hash) @user_id = user_hash['userID'] || user_hash['user_id'] @user_id = @user_id.to_s unless @user_id.nil? @email = user_hash['email'] @ip = user_hash['ip'] @user_agent = user_hash['userAgent'] || user_hash['user_agent'] @country = user_hash['country'] @locale = user_hash['locale'] @app_version = user_hash['appVersion'] || user_hash['app_version'] @custom = user_hash['custom'] if user_hash['custom'].is_a? Hash @statsig_environment = user_hash['statsigEnvironment'] @private_attributes = user_hash['privateAttributes'] if user_hash['privateAttributes'].is_a? Hash custom_ids = user_hash['customIDs'] || user_hash['custom_ids'] @custom_ids = custom_ids if custom_ids.is_a? Hash end end end ``` ### Type StatsigOptions ```ruby class StatsigOptions attr_accessor :environment attr_accessor :download_config_specs_url attr_accessor :log_event_url attr_accessor :get_id_lists_url attr_accessor :rulesets_sync_interval attr_accessor :idlists_sync_interval attr_accessor :disable_rulesets_sync attr_accessor :disable_idlists_sync attr_accessor :logging_interval_seconds attr_accessor :logging_max_buffer_size attr_accessor :local_mode attr_accessor :bootstrap_values attr_accessor :rules_updated_callback attr_accessor :data_store attr_accessor :idlist_threadpool_size attr_accessor :logger_threadpool_size attr_accessor :disable_diagnostics_logging attr_accessor :disable_sorbet_logging_handlers attr_accessor :network_timeout attr_accessor :post_logs_retry_limit attr_accessor :post_logs_retry_backoff attr_accessor :user_persistent_storage def initialize( environment = nil, download_config_specs_url: nil, log_event_url: nil, get_id_lists_url: nil, rulesets_sync_interval: 10, idlists_sync_interval: 60, disable_rulesets_sync: false, disable_idlists_sync: false, logging_interval_seconds: 60, logging_max_buffer_size: 1000, local_mode: false, bootstrap_values: nil, rules_updated_callback: nil, data_store: nil, idlist_threadpool_size: 3, logger_threadpool_size: 3, disable_diagnostics_logging: false, disable_sorbet_logging_handlers: false, network_timeout: nil, post_logs_retry_limit: 3, post_logs_retry_backoff: nil, user_persistent_storage: nil ) end end ``` ### DataStore ```ruby module Statsig module Interfaces class IDataStore def init end def get(key) nil end def set(key, value) end def shutdown end end end end ``` ================================================================================ # .NET Server SDK URL: https://docs.statsig.com/server-core/dotnet-core ================================================================================ # .NET Server SDK - **Package:** `Statsig.Dotnet` ([nuget](https://www.nuget.org/packages/Statsig.Dotnet)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-dotnet) ## Setup the SDK 1. **Install the SDK** ## Installation ```bash dotnet add package Statsig.Dotnet ``` Or add the package reference to your `.csproj` file: ```xml <PackageReference Include="Statsig.Dotnet" Version="X.X.X" /> ``` ### Requirements - **.NET 8.0** or later - **Windows, macOS, or Linux** (x64 and ARM64 supported) 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. ```csharp using Statsig; var statsig = new Statsig.Statsig("server-secret-key"); await statsig.Initialize(); ``` You can also provide custom options: ```csharp var options = new StatsigOptionsBuilder() .SetSpecsSyncIntervalMs(10000) .SetDisableAllLogging(false) .Build(); var statsig = new Statsig("server-secret-key", options); await statsig.Initialize(); ``` For shared instance usage: ```csharp var sharedStatsig = Statsig.NewShared("server-secret-key", options); await sharedStatsig.Initialize(); var statsig = Statsig.Shared(); ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). To check a gate for a user: ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .SetEmail("user@example.com") .Build(); var gateValue = statsig.CheckGate(user, "new_feature_gate"); if (gateValue) { // Gate is on, enable new feature } else { // Gate is off } ``` You can also disable exposure logging for this evaluation: ```csharp var options = new EvaluationOptions(disableExposureLogging: true); var gateValue = statsig.CheckGate(user, "new_feature_gate", options); ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example: ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); var config = statsig.GetDynamicConfig(user, "product_config"); var productName = config.Get<string>("product_name", "Default Product"); var price = config.Get<double>("price", 9.99); var isEnabled = config.Get<bool>("enabled", false); var features = config.Get<List<string>>("features", new List<string>()); Console.WriteLine($"Config Name: {config.Name}"); Console.WriteLine($"Group Name: {config.GroupName}"); Console.WriteLine($"Rule ID: {config.RuleID}"); ``` ### Getting a layer/experiment **Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) because layers make parameters reusable and support mutually exclusive experiments. ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); var experiment = statsig.GetExperiment(user, "button_color_test"); var buttonColor = experiment.Get<string>("color", "blue"); var fontSize = experiment.Get<int>("font_size", 14); var showBorder = experiment.Get<bool>("show_border", true); Console.WriteLine($"Experiment Name: {experiment.Name}"); Console.WriteLine($"Group Name: {experiment.GroupName}"); Console.WriteLine($"Rule ID: {experiment.RuleID}"); Console.WriteLine($"Button Color: {buttonColor}"); ``` ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); var layer = statsig.GetLayer(user, "user_prefs_layer"); var theme = layer.Get<string>("theme", "light"); var language = layer.Get<string>("language", "en"); var notifications = layer.Get<bool>("notifications_enabled", true); Console.WriteLine($"Layer Name: {layer.Name}"); Console.WriteLine($"Allocated Experiment: {layer.AllocatedExperimentName}"); Console.WriteLine($"Group Name: {layer.GroupName}"); Console.WriteLine($"Rule ID: {layer.RuleID}"); ``` The SDK automatically logs layer parameter access as exposure events unless you disable this behavior with `EvaluationOptions`. ### Logging an event After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata: ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); statsig.LogEvent(user, "button_clicked"); statsig.LogEvent(user, "purchase_completed", 29.99); statsig.LogEvent(user, "page_view", "homepage", new Dictionary<string, string> { ["referrer"] = "google", ["campaign"] = "summer_sale" }); statsig.LogEvent(user, "video_watched", 120, new Dictionary<string, string> { ["video_id"] = "abc123", ["quality"] = "1080p" }); ``` The `LogEvent` method supports multiple overloads: - `LogEvent(user, eventName)` - `LogEvent(user, eventName, stringValue, metadata)` - `LogEvent(user, eventName, intValue, metadata)` - `LogEvent(user, eventName, doubleValue, metadata)` ### Retrieving feature gate metadata To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object: ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); var gate = statsig.GetFeatureGate(user, "new_feature_gate"); Console.WriteLine($"Gate Name: {gate.Name}"); Console.WriteLine($"Gate Value: {gate.Value}"); Console.WriteLine($"Rule ID: {gate.RuleID}"); Console.WriteLine($"ID Type: {gate.IDType}"); if (gate.EvaluationDetails != null) { Console.WriteLine($"Config Sync Time: {gate.EvaluationDetails.ConfigSyncTime}"); Console.WriteLine($"Init Time: {gate.EvaluationDetails.InitTime}"); Console.WriteLine($"Reason: {gate.EvaluationDetails.Reason}"); } ``` ### Parameter stores If you want dynamic control over whether a value comes from a Feature Gate, Experiment, or Dynamic Config outside your deployment cycle, use Parameter Stores. A Parameter Store lets you define a parameter that you can change at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application supports future flexibility and allows non-technical Statsig users to turn parameters into experiments. ```csharp # Get a Parameter Store by name param_store = statsig.getParameterStore(user, "my_parameter_store") ``` ### Retrieving parameter values Parameter Store provides methods for retrieving values of different types with fallback defaults. #### Param Store Methods - **GetBool(string, default(bool))**: Pulls key value of type boolean - **GetString(string, "")**: Pulls key value of type string - **GetLong(string, default(long))**: Pulls key value of type long - **GetDouble(string, default(double))**: Pulls key value of type double - **GetList(string, new List<>())**: Pulls key value of type list - **GetDictionary(string, new Dictionary<string, object>())**: Pulls key value of type Dictionary ### Evaluation options You can disable exposure logging when retrieving a parameter store: ```csharp var store = statsig.GetParameterStore(user, name!, options); if (store == null) { throw new Exception($"Parameter store {name} not found"); } var x = store.GetBool(paramName, default(bool)); var y = store.GetString(paramName, ""); var z = store.GetDictionary(paramName, new Dictionary<string, object>()); ``` ## Using shared instance To access a single Statsig instance globally throughout your codebase, use the shared instance singleton pattern: ```csharp var sharedStatsig = Statsig.NewShared("server-secret-key"); await sharedStatsig.Initialize(); // Later, anywhere in your codebase var statsig = Statsig.Shared(); // Use the shared instance var result = statsig.CheckGate(user, "my_gate"); ``` The shared instance is useful for: - Singleton pattern usage across your application - Dependency injection scenarios - Avoiding multiple SDK instances Clean up the shared instance on shutdown: ```csharp var statsig = Statsig.Shared(); await statsig.FlushEvents(); await statsig.Shutdown(); Statsig.RemoveSharedInstance(); ``` ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call `get()` on a layer parameter. To delay exposure logging until the user actually uses the feature, use manual exposures. All main SDK functions (`CheckGate`, `GetDynamicConfig`, `GetExperiment`, `GetLayer`) accept an optional `EvaluationOptions` parameter. When you set `disableExposureLogging` to `true`, the SDK doesn't automatically log an exposure event. You can then manually log the exposure using the corresponding manual exposure logging method: #### Feature Gates ```csharp var result = statsig.CheckGate(user, "a_gate_name", new EvaluationOptions(disableExposureLogging: true)); ``` ```csharp statsig.ManuallyLogGateExposure(user, "a_gate_name"); ``` #### Dynamic Configs ```csharp var config = statsig.GetDynamicConfig(user, "a_dynamic_config_name", new EvaluationOptions(disableExposureLogging: true)); ``` ```csharp statsig.ManuallyLogDynamicConfigExposure(user, "a_dynamic_config_name"); ``` #### Experiments ```csharp var experiment = statsig.GetExperiment(user, "an_experiment_name", new EvaluationOptions(disableExposureLogging: true)); ``` ```csharp statsig.ManuallyLogExperimentExposure(user, "an_experiment_name"); ``` #### Layers ```csharp var layer = statsig.GetLayer(user, "a_layer_name", new EvaluationOptions(disableExposureLogging: true)); var paramValue = layer.Get("a_param_name", "fallback_value"); ``` ```csharp statsig.ManuallyLogLayerParameterExposure(user, "a_layer_name", "a_param_name"); ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for each user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks). In addition to `userID`, the top-level fields on `StatsigUser` are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass key-value pairs in the `custom` field for targeting. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services. `StatsigUser` represents the user context for feature flag evaluation. Use `StatsigUserBuilder` to create user instances: ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .SetEmail("user@example.com") .SetIP("192.168.1.1") .SetUserAgent("Mozilla/5.0...") .SetCountry("US") .SetLocale("en-US") .SetAppVersion("1.2.3") .SetCustomIDs(new Dictionary<string, string> { ["employee_id"] = "emp_456", ["team_id"] = "team_789" }) .AddCustomID("department_id", "dept_123") .SetCustomProperties(new Dictionary<string, object> { ["subscription_tier"] = "premium", ["account_age_days"] = 365, ["is_beta_user"] = true }) .AddCustomProperty("last_login", DateTime.UtcNow) .SetPrivateAttributes(new Dictionary<string, object> { ["internal_user_score"] = 0.85, ["risk_level"] = "low" }) .AddPrivateAttribute("pii_hash", "abc123def456") .Build(); ``` ## Builder methods #### Builder Methods - **SetUserID(string)**: Set the primary user ID - **SetEmail(string)**: Set user email - **SetIP(string)**: Set user IP address - **SetUserAgent(string)**: Set browser user agent - **SetCountry(string)**: Set user country - **SetLocale(string)**: Set user locale - **SetAppVersion(string)**: Set app version - **SetCustomIDs(Dictionary<string, string>)**: Set all custom IDs - **AddCustomID(string, string)**: Add a single custom ID - **SetCustomProperties(Dictionary<string, object>)**: Set all custom properties - **AddCustomProperty(string, object)**: Add a single custom property - **SetPrivateAttributes(Dictionary<string, object>)**: Set all private attributes - **AddPrivateAttribute(string, object)**: Add a single private attribute - **Build()**: Create the StatsigUser instance Dispose of StatsigUser instances when done: ```csharp using var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions Configure `StatsigOptions` using the `StatsigOptionsBuilder` pattern: ```csharp var options = new StatsigOptionsBuilder() .SetSpecsURL("https://custom-api.statsig.com/v1/download_config_specs") .SetLogEventURL("https://custom-api.statsig.com/v1/rgstr") .SetEnvironment("production") .SetSpecsSyncIntervalMs(30000) .SetEventLoggingMaxQueueSize(1000) .SetWaitForCountryLookupInit(true) .SetWaitForUserAgentInit(true) .SetDisableCountryLookup(false) .SetDisableUserAgentParsing(false) .SetDisableAllLogging(false) .SetInitTimeoutMs(3000) .SetFallbackToStatsigApi(false) .SetEnableIDLists(true) .SetIDListsURL("https://custom-api.statsig.com/v1/get_id_lists") .SetIDListsSyncIntervalMs(60000) .SetGlobalCustomFields(new Dictionary<string, object> { ["app_version"] = "1.2.3", ["build_number"] = "456" }) .Build(); var statsig = new Statsig("server-secret-key", options); ``` ## Available options - **SetSpecsURL(string)**: Override the default specs download endpoint - **SetLogEventURL(string)**: Override the default event logging endpoint - **SetEnvironment(string)**: Set the environment tier (e.g., "production", "staging") - **SetSpecsSyncIntervalMs(int)**: How often to sync configuration specs (default: 10000ms) - **SetEventLoggingMaxQueueSize(int)**: Maximum events to queue before flushing - **SetWaitForCountryLookupInit(bool)**: Wait for country lookup initialization - **SetWaitForUserAgentInit(bool)**: Wait for user agent parsing initialization - **SetDisableCountryLookup(bool)**: Disable automatic country detection - **SetDisableUserAgentParsing(bool)**: Disable user agent parsing - **SetDisableAllLogging(bool)**: Disable all event logging - **SetInitTimeoutMs(int)**: Maximum time in milliseconds to wait for SDK initialization (default: 3000ms) - **SetFallbackToStatsigApi(bool)**: Fallback to Statsig API when custom adapters fail (default: false) - **SetEnableIDLists(bool)**: Enable ID list targeting - **SetIDListsURL(string)**: Override the default ID lists endpoint - **SetIDListsSyncIntervalMs(int)**: How often to sync ID lists (default: 60000ms) - **SetGlobalCustomFields(Dictionary<string, object>)**: Global custom fields for all events - **SetSpecAdapterConfig(SpecAdapterConfig)**: Configure a custom spec source such as [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) - **SetProxyConfig(ProxyConfig)**: Configuration for connecting through a proxy server ### Proxy and custom network routing The `.NET` Server Core SDK uses `SetProxyConfig(ProxyConfig)` for a standard outbound HTTP proxy. If you are routing config sync through [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) or another custom spec source, use `SetSpecAdapterConfig(SpecAdapterConfig)`. If you only need custom Statsig endpoints, use `SetSpecsURL`, `SetLogEventURL`, and `SetIDListsURL`. ```csharp var proxyConfig = new ProxyConfig { ProxyHost = "proxy.example.com", ProxyPort = 8080, ProxyAuth = "username:password", // Optional ProxyProtocol = "http", // Optional: "http" or "https" CaCertPath = "/etc/ssl/certs/corporate-ca.pem" // Optional }; var options = new StatsigOptionsBuilder() .SetProxyConfig(proxyConfig) .Build(); var statsig = new Statsig("server-secret-key", options); ``` ### ProxyConfig properties - **ProxyHost** (string): The hostname or IP address of the proxy server - **ProxyPort** (int): The port number of the proxy server - **ProxyAuth** (string, optional): Authentication credentials in the format "username:password" - **ProxyProtocol** (string, optional): The protocol to use for the proxy connection ("http" or "https") - **CaCertPath** (string, optional): Path to a PEM CA bundle for outbound TLS ### Statsig Forward Proxy example ```csharp var specAdapterConfig = new SpecAdapterConfig( adapterType: "network_grpc_websocket", specsUrl: "http://forward-proxy.internal:50051" ); var options = new StatsigOptionsBuilder() .SetSpecAdapterConfig(specAdapterConfig) .SetFallbackToStatsigApi(true) .Build(); ``` #### EvaluationOptions `EvaluationOptions` allows you to customize the behavior of feature flag evaluations: ```csharp var options = new EvaluationOptions(disableExposureLogging: true); var gateValue = statsig.CheckGate(user, "feature_gate", options); var config = statsig.GetDynamicConfig(user, "product_config", options); var experiment = statsig.GetExperiment(user, "button_test", options); var layer = statsig.GetLayer(user, "user_prefs_layer", options); ``` ## Options - **DisableExposureLogging**: When `true`, prevents automatic exposure event logging for this evaluation. Useful when you want to evaluate a feature flag without affecting analytics or experiment results. ## Use cases - **Internal Tools**: Check flag values for debugging without affecting user metrics - **Conditional Logic**: Evaluate flags as part of complex logic where exposure should be logged manually later When you disable exposure logging, you can manually log exposures later using the manual exposure methods: ```csharp var options = new EvaluationOptions(disableExposureLogging: true); var gateValue = statsig.CheckGate(user, "feature_gate", options); if (shouldLogExposure) { statsig.ManuallyLogGateExposure(user, "feature_gate"); } ``` ## Shutting Statsig down Because the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before shutting down your app or server. ```csharp await statsig.FlushEvents(); await statsig.Shutdown(); statsig.Dispose(); ``` For shared instances: ```csharp var statsig = Statsig.Shared(); await statsig.FlushEvents(); await statsig.Shutdown(); Statsig.RemoveSharedInstance(); ``` ## Methods - **FlushEvents()**: Immediately flush any pending events to Statsig servers - **Shutdown()**: Gracefully shutdown the SDK, flushing events and cleaning up resources - **Dispose()**: Release native resources (implements IDisposable) Call `FlushEvents()` before `Shutdown()` to send all pending events. Always call `Dispose()` or use `using` statements to clean up resources. ## Client SDK bootstrapping | SSR If you use the Statsig client SDK in a browser or mobile app, you can bootstrap the client SDK with values from the server SDK to avoid a network request on the client. Bootstrapping is useful for server-side rendering (SSR) or to reduce the number of network requests on the client. ```csharp var user = new StatsigUserBuilder() .SetUserID("user_123") .Build(); var initResponse = statsig.GetClientInitializeResponse(user); var options = new ClientInitResponseOptions { HashAlgorithm = "sha256", ClientSDKKey = "client-sdk-key", IncludeLocalOverrides = false }; var customInitResponse = statsig.GetClientInitializeResponse(user, options); ``` The `GetClientInitializeResponse` method returns a JSON string containing the initialization data that client-side SDKs need. The initialization data enables server-side rendering and reduces client initialization time. ## ClientInitResponseOptions - **HashAlgorithm**: Hash algorithm for response integrity (default: "djb2") - **ClientSDKKey**: Client SDK key to include in response - **IncludeLocalOverrides**: Whether to include local overrides in the response (default: false) ### Working with IP or UserAgent values The server SDK doesn't automatically use `ip` or `userAgent` for gate evaluation because it doesn't have access to request headers. To use derived attributes such as Browser Name/Version, OS Name/Version, and Country, manually set the `ip` and `userAgent` fields on the user object when calling `GetClientInitializeResponse`. ### Working with IDs To ensure accurate config evaluation, the server SDK needs access to all user attributes that the client SDK uses. Pass all of these attributes to the server SDK, using cookies if needed to attach them on first requests. If the user objects on the client and server aren't identical, modern SDKs throw an `InvalidBootstrap` warning. Client SDKs also auto-generate a `StableID`. Manage the lifecycle of this ID to keep it consistent between client and server. Managing this with a cookie is often the simplest approach; refer to [Keeping StableID Consistent](https://docs.statsig.com/client/javascript-sdk-stable-id#keeping-stableid-consistent). If `StableID` differs between client and server, a `BootstrapStableIDMismatch` warning appears, and checks with that warning don't contribute to experiment analyses. ### getClientInitializeResponse and the legacy JS SDK If you are migrating from the legacy JS Client, you need to make some updates to how your server SDK generates values. Statsig changed the default hashing algorithm from `sha256` to `djb2` for performance and size reasons. ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing purposes without changing the configuration in the Statsig console. ```csharp statsig.OverrideGate("test_gate", true); statsig.OverrideDynamicConfig("test_config", new Dictionary<string, object> { ["color"] = "red", ["size"] = 42, ["enabled"] = true }); statsig.OverrideExperiment("test_experiment", new Dictionary<string, object> { ["variant"] = "treatment", ["multiplier"] = 1.5 }); statsig.OverrideExperimentByGroupName("test_experiment", "treatment_group"); statsig.OverrideLayer("test_layer", new Dictionary<string, object> { ["theme"] = "dark", ["font_size"] = 16 }); statsig.OverrideParameterStore("testing123", new Dictionary<string, object>() { ["brush_color"] = "blue", ["monochromatic"] = true, ["weight"] = 42, ["gradient"] = 3.14, ["pen_sizes"] = [1, 2, 3, 4, 5], ["artwork"] = new Dictionary<string, object>() { ["nesting"] = "treatment" } }); ``` You can also specify a user ID for targeted overrides: ```csharp statsig.OverrideGate("test_gate", true, "user_123"); statsig.OverrideDynamicConfig("test_config", new Dictionary<string, object> { ["special_feature"] = true }, "user_123"); ``` Local overrides are useful for: - Testing specific configurations during development - QA testing with known values - Debugging feature flag behavior - Integration testing with predictable results Overrides persist for the lifetime of the Statsig instance and affect all evaluations unless you provide a specific user ID. ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. Use it to persist user assignments across sessions, ensuring consistent experiment groups when users return. Persistent storage is useful for client-side A/B testing where users must always see the same variant. ```csharp using System.Collections.Generic; using Statsig; // Implement PersistentStorage to control how user stickiness is stored. public class MyPersistentStorage : PersistentStorage { private readonly Dictionary<string, Dictionary<string, StickyValues>> _store = new(); public override IDictionary<string, StickyValues> Load(string key) { // Load persisted values for this user from your backing store. return _store.TryGetValue(key, out var configs) ? new Dictionary<string, StickyValues>(configs) : new Dictionary<string, StickyValues>(); } public override void Save(string key, string configName, StickyValues data) { // Persist the sticky assignment (database, Redis, etc.). if (!_store.TryGetValue(key, out var configs)) { configs = new Dictionary<string, StickyValues>(); _store[key] = configs; } configs[configName] = data; } public override void Delete(string key, string configName) { // Remove the persisted value for this config/user. if (_store.TryGetValue(key, out var configs)) { configs.Remove(configName); } } } ``` ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems such as Redis. #### Csharp ```csharp using System.Threading.Tasks; using Statsig; public class MyDataStore : DataStore { public Task Initialize() { // Perform any initialization needed for your data store. return Task.CompletedTask; } public Task Shutdown() { // Clean up resources. return Task.CompletedTask; } public DataStoreResponse Get(string key) { // Retrieve data for the given key. // This is called during SDK evaluation. return Task.FromResult<DataStoreResponse?>(null); } public void Set(string key, string value, long? time = null) { // Store data for the given key. // Called when SDK receives updates from Statsig. return Task.CompletedTask; } public bool SupportsPollingUpdatesFor(string key) { // Return true if your store supports polling updates for this key, false otherwise. return Task.FromResult(false).CompletedTask; } } // Use data store var options = new StatsigOptionsBuilder() .SetDataStore(new MyDataStore()) .Build(); var statsig = new Statsig("server-secret-key", options); await statsig.Initialize(); ``` ## Performance benefits The .NET Core SDK uses Statsig's high-performance Rust evaluation engine through FFI bindings: - Native Rust evaluation engine handles all rule processing - .NET wrapper provides familiar C# APIs and type safety - Automatic memory management between .NET and Rust boundaries - Thread-safe operations across the FFI boundary ## Async/await support All network operations are fully async: ```csharp await statsig.Initialize(); await statsig.FlushEvents(); await statsig.Shutdown(); ``` Evaluation methods are synchronous for optimal performance: ```csharp var result = statsig.CheckGate(user, "gate_name"); ``` ## Thread safety The Statsig instance is thread-safe, and you can use it concurrently across multiple threads. Use the shared instance singleton pattern for application-wide usage: ```csharp var sharedStatsig = Statsig.NewShared("server-secret-key"); await sharedStatsig.Initialize(); var statsig = Statsig.Shared(); ``` ================================================================================ # C++ Server SDK URL: https://docs.statsig.com/server-core/cpp-core ================================================================================ # C++ Server SDK - **Repository:** [statsig-cpp-core](https://github.com/statsig-io/statsig-cpp-core) ## Setup the SDK 1. **Install the SDK** ## Installation Statsig implements all core logic in Rust. Statsig attaches prebuilt binaries as assets with each release, so a Rust environment isn't required. The CMakeLists.txt file handles the build configuration. If you encounter any installation or build issues, contact Statsig. ```CMake FetchContent_Declare( Statsig GIT_REPOSITORY https://github.com/statsig-io/statsig-cpp-core.git GIT_TAG 0.12.2-rc.1 ) FetchContent_MakeAvailable(Statsig) target_include_directories(CppApp PRIVATE ${statsig_SOURCE_DIR}/include) target_include_directories(CppApp PRIVATE ${statsig_SOURCE_DIR}/src) target_link_libraries(CppApp PRIVATE Statsig) ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. ```cpp #include <statsig/statsig.h> statsig_cpp_core::StatsigOptionsBuilder optionsBuilder; optionsBuilder.environment = "development"; optionsBuilder.specs_url = api_v2 + "/download_config_specs"; optionsBuilder.log_event_url = api + "/log_event"; optionsBuilder.id_lists_url = api + "/get_id_lists"; statsig_cpp_core::StatsigOptions options = optionsBuilder.build(); Statsig statsig("server-secret-key", options); statsig.initializeBlocking().wait(); ``` `initialize` performs a network request. After `initializeBlocking` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls. ## Tested platforms > **Note:** > > The upstream Statsig docs source doesn't yet include a `testedPlatforms` snippet for C++ Core. Use the [statsig-cpp-core](https://github.com/statsig-io/statsig-cpp-core) release assets and your target Linux distribution when validating Docker images. Add a tested-platforms table here when the snippet is published upstream. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). To check a gate for a user: ```cpp if (statsig.checkGate(user, "a_gate")) { // Gate is on, enable new feature } else { // Gate is off } ``` You can also disable exposure logging for this evaluation: ```cpp FeatureGateEvaluationOptions options; options.disable_exposure_logging = true; bool gateValue = statsig.check_gate(user, "a_gate", options); ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example: ```cpp // Get a dynamic config for a specific user DynamicConfig config = statsig.getDynamicConfig(user, "a_config"); // Access config values (We will provide accessors) std::string product_name = config.value.get("product_name", "Awesome Product v1"); double price = config.value.get("price", 10.0); // Access evaluation details such as rule id statsig_cpp_core::EvaluationDetails detail = config.details; std::cout << config.rule_id << std::endl; // The ID of the rule that served this config std::cout << config.id_type << std::endl; // The type of the evaluation (experiment, config, etc) // Advanced Usage: // You can disable exposure logging for this specific check DynamicConfigEvaluationOptions options; options.disable_exposure_logging = true; config = statsig.getDynamicConfig(user, "a_config", options); ``` ### Getting a layer/experiment **Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) because layers make parameters reusable and support mutually exclusive experiments. ```cpp // Get a experiment for a specific user statsig_cpp_core::Experiment exp = statsig.getExpriment(user, "an_experiment"); // Access config values (We will provide accessors) auto product_name = exp.value.get("product_name", "Awesome Product v1"); auto price = exp.value.get("price", 10.0); // Access evaluation details such as rule id statsig_cpp_core::EvaluationDetails detail = exp.details; std::cout << exp.rule_id << std::endl; // The ID of the rule that served this config std::cout << exp.id_type << std::endl; // The type of the evaluation (experiment, config, etc) // Advanced Usage: // You can disable exposure logging for this specific check ExperimentEvaluationOptions options; options.disable_exposure_logging = true; config = statsig.getExperiment(user, "an_experiment", options); ``` ### Retrieving feature gate metadata To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object: ```cpp FeatureGate gate = statsig.getFeatureGate(user, "example_gate"); std::cout << gate.rule_id << std::endl; std::cout << gate.value << std::endl; ``` The `get_feature_gate()` method returns a `FeatureGate` object with: - `value`: The boolean gate value - `rule_id`: The ID of the rule that served this gate - `id_type`: The type of the evaluation - `evaluation_details`: Additional metadata about the evaluation ### Logging an event After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata: ```cpp statsig.log_event( user, "add_to_cart", { {"price", "9.99"}, {"item_name", "diet_coke_48_pack"} } ); ``` The `log_event` method supports multiple overloads: - `log_event(user, event_name)` - `log_event(user, event_name, string_value)` - `log_event(user, event_name, string_value, metadata)` Statsig is adding support for numerical value and metadata. ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for each user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks). In addition to `userID`, the top-level fields on `StatsigUser` are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass key-value pairs in the `custom` field to use for targeting. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services. ```cpp statsig_cpp_core::UserBuilder builder; builder.setUserID(j["userID"]); builder.setCustomIDs(j["customIDs"]); builder.setCountry(j["customIDs"]); statsig_cpp_core::User user = builder.build(); // UserBuilder also supports deserialize from json ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. ### Available options ```cpp std::optional<std::string> specs_url; std::optional<std::string> id_lists_url; std::optional<std::string> log_event_url; std::optional<std::string> output_log_level; std::optional<std::string> environment; bool enable_id_lists = false; bool disable_all_logging = false; bool disable_country_lookup = false; bool disable_network = false; ``` Use `set_spec_adapter_config(const SpecAdapterConfig&)` to configure a custom source for feature specifications. ### Proxy and custom network routing Use `set_spec_adapter_config` to stream feature specifications from the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy) over gRPC websocket. ```cpp statsig_cpp_core::SpecAdapterConfig specAdapterConfig( statsig_cpp_core::SpecAdapterConfig::TYPE_NETWORK_GRPC_WEBSOCKET ); specAdapterConfig.specs_url = "http://forward-proxy.internal:50051"; specAdapterConfig.authentication_mode = statsig_cpp_core::SpecAdapterConfig::AUTH_NONE; statsig_cpp_core::StatsigOptionsBuilder optionsBuilder; optionsBuilder.set_spec_adapter_config(specAdapterConfig); statsig_cpp_core::StatsigOptions options = optionsBuilder.build(); ``` `init_timeout_ms` defaults to 3000 milliseconds. For TLS, set `authentication_mode` to `SpecAdapterConfig::AUTH_TLS` and provide `ca_cert_path`. For mTLS, use `SpecAdapterConfig::AUTH_MTLS` and also provide `client_cert_path` and `client_key_path`. Use `domain_name` to override the TLS server name used for certificate verification. The C++ SDK accepts one spec adapter. If the configured source is unavailable during initialization, initialization fails after the adapter initialization timeout. The adapter controls specification downloads only; event logging and ID lists use their separately configured endpoints. ### Example usage ```cpp statsig_cpp_core::StatsigOptionsBuilder optionsBuilder; optionsBuilder.environment = "development"; optionsBuilder.specs_url = api_v2 + "/download_config_specs"; optionsBuilder.log_event_url = api + "/log_event"; optionsBuilder.id_lists_url = api + "/get_id_lists"; statsig_cpp_core::StatsigOptions options = optionsBuilder.build(); ``` ## Shutting Statsig down Because the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before your application exits. ```cpp statsig.shutdownBlocking(); ``` The `shutdown()` method: - Flushes any pending events to Statsig servers - Cleans up resources - Waits for all operations to complete ## Reference ### API methods - `check_gate(user: StatsigUser, gate_name: str, options: Optional[FeatureGateEvaluationOptions] = None) -> bool` - `get_dynamic_config(user: StatsigUser, config_name: str, options: Optional[DynamicConfigEvaluationOptions] = None) -> DynamicConfig` - `get_experiment(user: StatsigUser, experiment_name: str, options: Optional[ExperimentEvaluationOptions] = None) -> DynamicConfig` - `get_layer(user: StatsigUser, layer_name: str, options: Optional[LayerEvaluationOptions] = None) -> Layer` - `get_feature_gate(user: StatsigUser, gate_name: str, options: Optional[FeatureGateEvaluationOptions] = None) -> FeatureGate` - `log_event(user: StatsigUser, event_name: str, value: Optional[Union[str, float]] = None, metadata: Optional[Dict[str, str]] = None) -> None` - `shutdown() -> AsyncResult[None]` ### Fields needed methods The following methods return information about which user fields evaluation requires. - `get_gate_fields_needed(gate_name: str) -> List[str]` - `get_dynamic_config_fields_needed(config_name: str) -> List[str]` - `get_experiment_fields_needed(experiment_name: str) -> List[str]` - `get_layer_fields_needed(layer_name: str) -> List[str]` These methods return a list of strings representing the user fields required to evaluate the specified gate, config, experiment, or layer. ================================================================================ # Rust Server SDK URL: https://docs.statsig.com/server-core/rust-core ================================================================================ # Rust Server SDK - **Package:** `statsig-rust` ([crates](https://crates.io/crates/statsig-rust)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-rust) ## Set up the SDK 1. **Install the SDK** To use the SDK, add the Statsig Rust package to your Cargo.toml file: ```toml [dependencies] statsig-rust = "X.Y.Z" # Replace with the latest version ``` Or, you can use the cargo command: ```shell cargo add statsig-rust ``` You can find the latest version and documentation at [crates.io/crates/statsig-rust](https://crates.io/crates/statsig-rust). 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a StatsigOptions object to customize the SDK. ```rust use statsig_rust::{Statsig, StatsigOptions}; use std::sync::Arc; // Simple initialization let statsig = Statsig::new("server-secret-key", None); statsig.initialize().await?; // Or with StatsigOptions let mut options = StatsigOptions::default(); options.environment = Some("development".to_string()); let statsig = Statsig::new("server-secret-key", Some(Arc::new(options))); statsig.initialize().await?; // Don't forget to shutdown when done statsig.shutdown().await?; ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example: ```rust use statsig_rust::{Statsig, StatsigUserBuilder}; let user = StatsigUserBuilder::new_with_user_id("a-user".to_string()).build(); if statsig.check_gate(&user, "a_gate") { // Gate is on, enable new feature } else { // Gate is off } ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and similar types) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a full JSON object configurable on the server from which you can fetch typed parameters. ```rust use statsig_rust::{Statsig, StatsigUserBuilder, DynamicConfigEvaluationOptions}; use std::sync::Arc; // Get a dynamic config for a specific user let user = StatsigUserBuilder::new_with_user_id("my_user".to_string()).build(); let config = statsig.get_dynamic_config(&user, "a_config"); // Access config values with type-safe getters and fallback values let product_name = config.get_string("product_name", "Awesome Product v1"); // returns String let price = config.get_double("price", 10.0); // returns f64 let should_discount = config.get_bool("discount", false); // returns bool let quantity = config.get_int("quantity", 1); // returns i64 // Advanced Usage: // You can disable exposure logging for this specific check let mut options = DynamicConfigEvaluationOptions::default(); options.disable_exposure_logging = Some(true); let config = statsig.get_dynamic_config_with_options(&user, "a_config", &options); // The config object also provides metadata about the evaluation println!("{}", config.rule_id); // The ID of the rule that served this config println!("{}", config.id_type); // The type of the evaluation (experiment, config, etc) ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available. Statsig recommends [Layers](https://docs.statsig.com/experiments/layers-overview) because they make parameters reusable and support mutually exclusive experiments. ```rust use statsig_rust::{Statsig, StatsigUserBuilder}; // Values via get_layer let user = StatsigUserBuilder::new_with_user_id("my_user".to_string()).build(); let layer = statsig.get_layer(&user, "user_promo_experiments"); let title = layer.get_string("title", "Welcome to Statsig!"); let discount = layer.get_double("discount", 0.1); // Via get_experiment let title_exp = statsig.get_experiment(&user, "new_user_promo_title"); let price_exp = statsig.get_experiment(&user, "new_user_promo_price"); let title = title_exp.get_string("title", "Welcome to Statsig!"); let discount = price_exp.get_double("discount", 0.1); ``` ### Parameter stores Use Parameter Stores when you want to define a parameter without deciding whether it should be a Feature Gate, Experiment, or Dynamic Config. Parameter Stores let you change the parameter type at any point in the Statsig console without a new deployment. Parameter Stores are optional, but parameterizing your application provides future flexibility and allows non-technical Statsig users to turn parameters into experiments. ```jsx let param_store = statsig.get_parameter_store("my_parameters"); let param_store_value = param_store.get(&user, "my_parameter_value", false); //false is fallback value println!("param_store_value: {}", param_store_value); ``` ### Logging an event To track custom events, call the Log Event API. Specify the user, event name, and an optional value or metadata object: ```rust use statsig_rust::{Statsig, StatsigUserBuilder}; use std::collections::HashMap; use crate::evaluation::dynamic_value::DynamicValue; // Create a user let user = StatsigUserBuilder::new_with_user_id("user_id".to_string()).build(); // Create metadata hashmap let mut metadata = HashMap::new(); metadata.insert("price".to_string(), "9.99".into()); metadata.insert("item_name".to_string(), "diet_coke_48_pack".into()); // Log the event statsig.log_event( &user, "add_to_cart", Some("SKU_12345".into()), // value as DynamicValue Some(metadata) ); ``` Learn more about identifying users, group analytics, and best practices for logging events in the [logging events guide](https://docs.statsig.com/guides/logging-events). ### Retrieving feature gate metadata In certain scenarios, you may need more information about a gate evaluation than a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object: ```rust use statsig_rust::{Statsig, StatsigUserBuilder}; // Create a user let user = StatsigUserBuilder::new_with_user_id("user_id".to_string()).build(); // Get a feature gate let gate = statsig.get_feature_gate(&user, "example_gate"); // Access gate properties println!("{}", gate.rule_id); println!("{}", gate.value); // Boolean value of the gate ``` ## Using shared instance To create a single Statsig instance accessible globally throughout your codebase, use the shared instance functionality, which provides a singleton pattern: ```rust // Create a shared instance that can be accessed globally let statsig = Statsig::new_shared("server-secret-key", None).unwrap(); statsig.initialize().await?; // Access the shared instance from anywhere in your code let shared_statsig = Statsig::shared(); let is_feature_enabled = shared_statsig.check_gate(&user, "feature_name"); // Check if a shared instance exists if Statsig::has_shared_instance() { // Use the shared instance } // Remove the shared instance when no longer needed Statsig::remove_shared(); ``` The shared instance helps when multiple parts of your codebase need Statsig without passing an instance between them. - `Statsig::new_shared(sdk_key, options)`: Creates a new shared instance of Statsig that you can access globally - `Statsig::shared()`: Returns the shared instance - `Statsig::has_shared_instance()`: Checks if a shared instance exists (useful when the shared instance may not be ready yet) - `Statsig::remove_shared()`: Removes the shared instance (useful when you want to switch to a new shared instance) > **Note:** > > `has_shared_instance()` and `remove_shared()` are helpful in specific scenarios but aren't required in most use cases where the shared instance is set up near the top of your application. > > Also note that only one shared instance can exist at a time. Attempting to create a second shared instance results in an error. ## Manual exposures By default, the SDK automatically logs an exposure event when you check a gate, get a config, get an experiment, or call get() on a parameter in a layer. To delay exposure logging (for example, to log only after the user actually uses the feature), use manual exposures. All main SDK functions (`check_gate`, `get_dynamic_config`, `get_experiment`, `get_layer`) accept an options parameter with a `disable_exposure_logging` field. When set to `true`, the SDK doesn't automatically log an exposure. You can then log the exposure manually at a later time: #### Feature Gates ```rust result = statsig.check_gate_with_options(&user, 'a_gate_name', FeatureGateEvaluationOptions {disable_exposure_logging: true}); ``` ```rust statsig.manually_log_gate_exposure(&user, 'a_gate_name') ``` #### Dynamic Configs ```rust config = statsig.get_dynamic_config_with_options(&user, 'a_dynamic_config_name', DynamicConfigEvaluationOptions {disable_exposure_logging: true}); ``` ```rust statsig.manually_log_dynamic_config_exposure(&user, 'a_dynamic_config_name') ``` #### Experiments ```rust experiment = statsig.get_experiment_with_options(&user, 'an_experiment_name', ExperimentEvaluationOptions {disable_exposure_logging: true}); ``` ```rust statsig.manually_log_experiment_exposure(&user, 'an_experiment_name') ``` #### Layers ```rust layer = statsig.get_layer_with_options(&user, 'a_layer_name', LayerEvaluationOptions {disable_exposure_logging: true}); paramValue = layer.get('a_param_name', 'fallback_value') ``` ```rust statsig.manually_log_layer_parameter_exposure(&user, 'a_layer_name', 'a_param_name') ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. Complete user information lets you take advantage of advanced gate and config conditions (like country or OS/browser-level checks) and correctly measure the impact of experiments on metrics and events. As explained in [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks), you must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. In addition to userID, the top-level fields on StatsigUser are: email, ip, userAgent, country, locale, and appVersion. You can also pass any key-value pairs in an object or dictionary to the custom field and create targeting based on them. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. They are useful for PII or sensitive data that you don't want to send to third-party services. ```rust use statsig_rust::StatsigUserBuilder; use std::collections::HashMap; // Create a user with just a user ID let user = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .build(); // Or create a user with custom IDs let mut custom_ids = HashMap::new(); custom_ids.insert("employee_id".to_string(), "emp-456".to_string()); let user_with_custom_ids = StatsigUserBuilder::new_with_custom_ids(custom_ids) .build(); // Create a user with several properties let mut custom_fields = HashMap::new(); custom_fields.insert("plan".to_string(), "premium".into()); custom_fields.insert("age".to_string(), 25.into()); let user = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .email(Some("user@example.com".to_string())) .ip(Some("192.168.1.1".to_string())) .user_agent(Some("Mozilla/5.0...".to_string())) .country(Some("US".to_string())) .locale(Some("en-US".to_string())) .app_version(Some("1.0.0".to_string())) .custom(Some(custom_fields)) .build(); // Private Attributes (not forwarded to integrations) let mut private_attrs = HashMap::new(); private_attrs.insert("internal_id".to_string(), "emp-123".into()); let user_with_private = StatsigUserBuilder::new_with_user_id("user-123".to_string()) .email(Some("user@example.com".to_string())) .private_attributes(Some(private_attrs)) .build(); ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | data_store | Option<Arc<dyn DataStoreTrait>> | No | — | External data store for Statsig values. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_all_logging | Option<bool> | No | — | When true, disables all event logging. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_network | Option<bool> | No | — | When `true`, disables all network functions: event & exposure logging, spec downloads, and ID List downloads. Formerly called "localMode". | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enable_id_lists | Option<bool> | No | — | Enable/disable ID list functionality. **Required to be `true` when using segments with more than 1000 IDs.** Refer to [ID List segments](https://docs.statsig.com/segments/add-id-list) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_user_agent_parsing | Option<bool> | No | — | If set to true, the SDK doesn't attempt to parse UserAgents (attached to the user object) into browserName, browserVersion, systemName, systemVersion, and appVersion at evaluation time, when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_user_agent_init | Option<bool> | No | — | When set to true, the SDK waits until user agent parsing data is fully loaded during initialization. This may slow down startup by ~1 second but ensures that parsing of the user's userAgent string into fields like browserName, browserVersion, systemName, systemVersion, and appVersion is ready before any evaluations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_user_country_lookup | Option<bool> | No | — | If set to true, the SDK doesn't attempt to parse IP addresses (attached to the user object at user.ip) into Country codes at evaluation time, when needed for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_country_lookup_init | Option<bool> | No | — | When set to true, the SDK waits for country lookup data (e.g., GeoIP or YAML files) to fully load during initialization. This may slow down startup by ~1 second but ensures that IP-to-country parsing is ready at evaluation time. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | Option<String> | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_adapter | Option<Arc<dyn EventLoggingAdapter>> | No | — | Custom adapter for event logging. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_flush_interval_ms | Option<u32> | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_queue_size | Option<u32> | No | — | Maximum number of events to queue before forcing a flush.- Default is `2000` - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - Refer to `event_logging_max_pending_batch_queue_size` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_pending_batch_queue_size | Option<u32> | No | — | Maximum number of event batches to hold in buffer to retry.- Default is `100`. - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - eg: 2000 \* 100 means the SDK can process 200k event per second before events start getting dropped - Refer to `event_logging_max_queue_size`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallback_to_statsig_api | Option<bool> | No | — | Whether to fall back to the Statsig API if custom endpoints fail. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_adapter | Option<Arc<dyn IdListsAdapter>> | No | — | Custom adapter for ID lists. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_sync_interval_ms | Option<u32> | No | — | How often the SDK updates ID lists from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_url | Option<String> | No | — | Custom URL for fetching ID lists. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | init_timeout_ms | Option<u64> | No | — | Sets the maximum timeout for initialization requests (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | log_event_url | Option<String> | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | observability_client | Option<Weak<dyn ObservabilityClient>> | No | — | Client for collecting observability data. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | output_log_level | Option<LogLevel> | No | — | Controls the verbosity of SDK logs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | override_adapter | Option<Arc<dyn OverrideAdapter>> | No | — | Custom adapter for overrides. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | spec_adapters_config | Option<Vec<SpecAdapterConfig>> | No | — | Configuration for specification adapters. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_adapter | Option<Arc<dyn SpecsAdapter>> | No | — | Custom adapter for specifications. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_sync_interval_ms | Option<u32> | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_url | Option<String> | No | — | Custom URL for fetching feature specifications. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | global_custom_fields | Option<HashMap<String, DynamicValue>> | No | — | Global custom fields to include with all evaluations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxy_config | Option<ProxyConfig> | No | — | Configuration for connecting through a proxy server. The `ProxyConfig` struct has the following properties:- `proxy_host`: Option<String> - Specifies the proxy server host - `proxy_port`: Option<u16> - Specifies the proxy server port - `proxy_auth`: Option<String> - For proxy authentication (format: `"username:password"`) - `proxy_protocol`: Option<String> - Specifies the protocol (e.g., `"http"`, `"https"`) - `ca_cert_path`: Option<String> - Optional path to a PEM CA bundle for outbound TLS | ### Example usage ```rust use statsig_rust::{Statsig, StatsigOptions}; use std::sync::Arc; // Initialize StatsigOptions with custom parameters let mut options = StatsigOptions::default(); options.environment = Some("development".to_string()); options.init_timeout_ms = Some(3000); options.disable_all_logging = Some(false); options.enable_id_lists = Some(true); options.output_log_level = Some(LogLevel::Info); // LogLevel enum, not a string // Pass the options object into Statsig::new() let statsig = Statsig::new("server-secret-key", Some(Arc::new(options))); statsig.initialize().await?; // Or, use the builder pattern for a more fluent interface let options = StatsigOptions::builder() .environment(Some("development".to_string())) .init_timeout_ms(Some(3000)) .disable_all_logging(Some(false)) .enable_id_lists(Some(true)) .specs_sync_interval_ms(Some(30000)) // Configure proxy settings .proxy_config(Some(ProxyConfig { proxy_host: Some("proxy.example.com".to_string()), proxy_port: Some(8080), proxy_protocol: Some("https".to_string()), proxy_auth: None, // Use Some("username:password".to_string()) if authentication is required ca_cert_path: Some("/etc/ssl/certs/corporate-ca.pem".to_string()), })) .build(); // Pass the options object into Statsig::new() let statsig = Statsig::new("server-secret-key", Some(Arc::new(options))); statsig.initialize().await?; ``` ### Proxy and custom network routing Use `proxy_config` if your service needs a standard outbound HTTP proxy. If you need to route config sync through [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) or another custom source, use `spec_adapters_config` or `specs_url` instead. Set `ca_cert_path` when your environment requires a custom PEM CA bundle for outbound TLS. ## Client initialize response Use `get_client_init_response_as_string` to generate bootstrap values for a client SDK from the Rust SDK's cached specs. Bootstrapping supports server-side rendering (SSR) and avoids the client's initial evaluation request. Initialize the server SDK before generating a response. For an initialized server SDK and user, generate a response with the default options: ```rust let bootstrap_json = statsig.get_client_init_response_as_string(&user); ``` #### Full code example and client bootstrapping This example uses an initialized `statsig` instance and returns JSON as a `String`: ```rust use statsig_rust::{ClientInitResponseOptions, HashAlgorithm, StatsigUserBuilder}; use std::collections::HashSet; let user = StatsigUserBuilder::new_with_user_id("a-user".to_string()).build(); // Use the default options. let bootstrap_json = statsig.get_client_init_response_as_string(&user); // Or restrict the response to a client key and selected configs. let options = ClientInitResponseOptions { client_sdk_key: Some("client-sdk-key".to_string()), hash_algorithm: Some(HashAlgorithm::Djb2), feature_gate_filter: Some(HashSet::from([ "onboarding_v2".to_string(), "new_checkout".to_string(), ])), experiment_filter: Some(HashSet::from(["pricing_experiment".to_string()])), ..Default::default() }; let filtered_bootstrap_json = statsig.get_client_init_response_with_options_as_string(&user, &options); ``` Return the string as your HTTP response body with `Content-Type: application/json`. Don't serialize the string as JSON again, which produces a quoted string instead of the bootstrap object. If you need a typed Rust value instead, use `get_client_init_response(&user)` or `get_client_init_response_with_options(&user, &options)`. These methods return `InitializeResponse`. Use the string-returning methods when sending the response to a client SDK. Pass the response to your client SDK's bootstrap API. For the JavaScript client, follow [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter). #### Initialize response options Start with `ClientInitResponseOptions::default()` and set the fields you need: | Field | Type | Behavior | | --- | --- | --- | | `hash_algorithm` | `Option<HashAlgorithm>` | Controls config-name hashing: `HashAlgorithm::Djb2` (default), `HashAlgorithm::Sha256`, or `HashAlgorithm::None` (unhashed). Name hashing isn't encryption or an integrity check. | | `client_sdk_key` | `Option<String>` | Restricts the response to the client key's [target app](https://docs.statsig.com/sdks/target-apps). Use the key that initializes the client SDK. | | `include_local_overrides` | `Option<bool>` | Includes local overrides in evaluations when `Some(true)`. Defaults to `Some(false)`. | | `feature_gate_filter` | `Option<HashSet<String>>` | Includes only the named feature gates. | | `experiment_filter` | `Option<HashSet<String>>` | Includes only the named experiments. | | `dynamic_config_filter` | `Option<HashSet<String>>` | Includes only the named dynamic configs. | | `layer_filter` | `Option<HashSet<String>>` | Includes only the named layers. | | `param_store_filter` | `Option<HashSet<String>>` | Includes only the named parameter stores. | Filters take original config names, even when the response hashes those names. An unset filter doesn't restrict that config type. Use `client_sdk_key` to apply target-app restrictions rather than relying on name filters alone. #### Hash algorithm Choose how the response hashes config names. The default is `djb2`; choose no hashing only when your client integration requires unhashed names. ```rust let options = ClientInitResponseOptions { hash_algorithm: Some(HashAlgorithm::Djb2), ..Default::default() }; let bootstrap_json = statsig.get_client_init_response_with_options_as_string(&user, &options); ``` #### Client SDK key Use the client SDK key to apply its [target-app restrictions](https://docs.statsig.com/sdks/target-apps) to the response. ```rust let options = ClientInitResponseOptions { client_sdk_key: Some("client-sdk-key".to_string()), ..Default::default() }; let bootstrap_json = statsig.get_client_init_response_with_options_as_string(&user, &options); ``` #### Filtering Select specific config names to reduce the response size. Filters for other config types remain unset in this example. ```rust let options = ClientInitResponseOptions { feature_gate_filter: Some(HashSet::from(["onboarding_v2".to_string()])), experiment_filter: Some(HashSet::from(["pricing_experiment".to_string()])), ..Default::default() }; let bootstrap_json = statsig.get_client_init_response_with_options_as_string(&user, &options); ``` #### Include local overrides Set this option to include local overrides when generating bootstrap values for development or testing. ```rust let options = ClientInitResponseOptions { include_local_overrides: Some(true), ..Default::default() }; let bootstrap_json = statsig.get_client_init_response_with_options_as_string(&user, &options); ``` #### Match the client user Generate the response for the same user ID, custom IDs, and evaluation attributes that the client SDK uses. When targeting depends on IP address or user agent, pass those request attributes to the server-side user. If you use Stable ID, share the same `stableID` custom ID between server and client. Keep the server secret key on the server. Send each user only their own bootstrap response, and don't share a cached response across users. Config-name filters and name hashing aren't substitutes for authorization. ## Shutting Statsig down Statsig batches and periodically flushes events. To flush all logged events before shutdown, call `shutdown()` before your app or server shuts down: ```rust statsig.shutdown().await?; ``` Alternatively, you can manually flush events without shutting down: ```rust // Manually flush events to the server statsig.flush_events().await; ``` ## SDK event subscriptions The Statsig SDK provides an event subscription system that lets you listen for evaluation events and lifecycle events in real time. This is useful for debugging, analytics, custom logging, and integration with external systems. ### Supported events The SDK supports subscribing to the following evaluation events: - **`gate_evaluated`** - Fired when a feature gate is evaluated for a user - **`dynamic_config_evaluated`** - Fired when a dynamic config is retrieved for a user - **`experiment_evaluated`** - Fired when an experiment is evaluated for a user - **`layer_evaluated`** - Fired when a layer is evaluated for a user - **`specs_updated`** - Fired when the SDK updates its cached specs, including where the specs were loaded from - **`"*"`** - Subscribe to all evaluation events ### SDK event data Each event includes relevant context about the evaluation: - **Gate Evaluated Events** include: `gate_name`, `value` (boolean), `rule_id`, `reason` - **Dynamic Config Events** include: the full `dynamic_config` object with values and metadata - **Experiment Events** include: the full `experiment` object with variant assignment and parameters - **Layer Events** include: the full `layer` object with allocated experiment and parameters - **Specs Updated Events** include `source`, `source_api`, and `values` metadata, where `values.time` is the timestamp of the last update to the project in the Statsig console ### Use cases Event subscriptions are particularly useful for: - **Debugging**: Monitor which features are being evaluated and their results - **Analytics**: Track feature usage patterns and user segments - **Custom Logging**: Send evaluation data to your own logging systems - **Integration**: Forward events to external analytics or monitoring tools - **Testing**: Verify that features are being evaluated as expected ### Best practices - **Clean up subscriptions**: Always unsubscribe when you no longer need to listen for events to prevent memory leaks - **Handle event data carefully**: Event objects may contain sensitive user information depending on your configuration - **Use specific event types**: Subscribe to specific events rather than "\*" when possible for better performance - **Avoid heavy processing**: Keep event handlers lightweight to avoid impacting SDK performance ```rust use statsig_rust::{Statsig, StatsigUserBuilder, sdk_event_emitter::SdkEvent}; let statsig = Statsig::new("server-secret-key", None)?; statsig.initialize().await?; // Subscribe to gate evaluation events let gate_sub_id = statsig.subscribe(SdkEvent::GATE_EVALUATED, |event| { if let SdkEvent::GateEvaluated { gate_name, value, rule_id, reason } = event { println!("Gate evaluated: {} = {}, rule: {}, reason: {}", gate_name, value, rule_id, reason); } }); // Subscribe to dynamic config evaluation events let config_sub_id = statsig.subscribe(SdkEvent::DYNAMIC_CONFIG_EVALUATED, |event| { if let SdkEvent::DynamicConfigEvaluated { dynamic_config } = event { println!("Config evaluated: {}", dynamic_config.name); } }); // Subscribe to experiment evaluation events let experiment_sub_id = statsig.subscribe(SdkEvent::EXPERIMENT_EVALUATED, |event| { if let SdkEvent::ExperimentEvaluated { experiment } = event { println!("Experiment evaluated: {} -> {}", experiment.name, experiment.group_name); } }); // Subscribe to layer evaluation events let layer_sub_id = statsig.subscribe(SdkEvent::LAYER_EVALUATED, |event| { if let SdkEvent::LayerEvaluated { layer } = event { println!("Layer evaluated: {}", layer.name); } }); let specs_updated_sub_id = statsig.subscribe(SdkEvent::SPECS_UPDATED, |event| { if let SdkEvent::SpecsUpdated { source, source_api, values, } = event { println!( "Specs updated from {} via {} (project last edited at {})", source, source_api, values.time ); } }); // Subscribe to all events let all_events_sub_id = statsig.subscribe(SdkEvent::ALL, |event| { println!("Event received: {}", event.get_name()); }); // Unsubscribe from specific event types statsig.unsubscribe(SdkEvent::GATE_EVALUATED); statsig.unsubscribe(SdkEvent::SPECS_UPDATED); // Unsubscribe using subscription ID statsig.unsubscribe_by_id(&config_sub_id); // Unsubscribe from all events statsig.unsubscribe_all(); ``` ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing. This is useful for local development or testing when you want to force a specific value without changing the configuration in the Statsig console. ```Rust // Overrides the given gate to the specified value statsig.override_gate("test_gate", true, None); // Overrides the given dynamic config to the provided value statsig.override_dynamic_config("test_1", my_map.clone(), None); //my_map is HashMap<String, Value> // Overrides the given experiment to the provided value statsig.override_experiment("test_xp_1", my_map.clone(), None); //my_map is HashMap<String, Value> // Overrides the given experiment to a particular groupname, available for experiments only statsig.override_experiment_by_group_name("test_xp_1", "a_group_name", None); // Overrides the given layer to the provided value statsig.override_layer("user_promo_experiments", my_map.clone(), None); //my_map is HashMap<String, Value> //Alternatively, get the Experiment object for a given groupName let group_exp = statsig.get_experiment_by_group_name("pricing_experiment", "premium_group"); let premium_price = group_exp.get_double("price", 9.99); ``` ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. This enables you to persist user assignments across sessions, ensuring consistent experiment groups when a user returns. This is useful for client-side A/B testing where users must always receive the same variant. ```rust pub trait PersistentStorageTrait: Send + Sync { fn load(&self, key: &str) -> Result<Option<UserPersistedValues>, PersistentStorageErrorEnum>; fn save(&self, key: &str, config_name: &str, data: &StickyValues) -> Result<(), PersistentStorageErrorEnum>; fn delete(&self, key: &str, config_name: &str) -> Result<(), PersistentStorageErrorEnum>; } ``` ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems. ```rust pub trait DataStoreTrait: Send + Sync { fn initialize(&self) -> Result<(), DataStoreErrorEnum>; fn shutdown(&self) -> Result<(), DataStoreErrorEnum>; fn get(&self, key: &str) -> Result<Option<DataStoreResponse>, DataStoreErrorEnum>; fn set(&self, key: &str, value: &str, time: Option<u64>) -> Result<(), DataStoreErrorEnum>; fn support_polling_updates_for(&self, key: &str) -> Result<bool, DataStoreErrorEnum>; } pub struct DataStoreResponse { pub result: String, pub time: Option<u64>, } ``` ## Enrich users for Forward Proxy ID list evaluation The experimental `StatsigFPUserBuilder` fetches ID list memberships from Forward Proxy and returns a standard `StatsigUser`. For the request flow and membership freshness, refer to [Forward Proxy user enrichment](https://docs.statsig.com/server/concepts/async-user-enrichment). Use a compatible early-access Rust SDK build that exports these APIs under `statsig_rust::experimental`. Deploy [Forward Proxy with Redis](https://docs.statsig.com/server/concepts/forward-proxy-id-list-enrichment) first, then verify a known member with the same server secret key your SDK uses. ### Configure the SDK and enrichment provider Set `StatsigOptions.enable_id_lists` to `Some(false)` before initializing the SDK so the process doesn't also download every ID list. Create one initialized `Statsig` instance and one enrichment provider per application process. Reuse the provider across user builds. The example assumes an initialized `statsig` instance, a `server_key`, and a `proxy_url`. Add Tokio with the `macros` and `rt-multi-thread` features to run async application code. Run the example inside an async function returning `Result<(), Box<dyn std::error::Error>>`. ```rust use statsig_rust::experimental::{ ForwardProxyEnrichmentOptions, ForwardProxyUserEnrichmentProvider, StatsigFPUserBuilder, }; use std::sync::Arc; let provider = Arc::new( ForwardProxyUserEnrichmentProvider::new( &server_key, ForwardProxyEnrichmentOptions { url: proxy_url.to_string(), timeout_ms: Some(100), retries: Some(1), proxy_config: None, }, ) .map_err(|error| format!("{error:?}"))?, ); let user = StatsigFPUserBuilder::new_with_enricher(provider.clone()) .user_id(Some("user-123")) .custom_ids(Some([("accountID", "account-456")])) .build() .await?; let enabled = statsig.check_gate(&user, "a_gate_with_id_list_targeting"); ``` The example maps constructor errors to strings and propagates `build()` errors to the caller. ### Enrichment options | Option | Default | Purpose | | --- | --- | --- | | `url` | Required | Proxy base URL. The provider appends `/v1/user_enrichment`. | | `timeout_ms` | `100` | Timeout in milliseconds for each HTTP attempt. | | `retries` | `1` | Additional attempts for retryable failures. `0` disables retries. | | `proxy_config` | `None` | Optional egress proxy and custom CA, separate from the destination URL. | Retries and backoff can make a build take longer than `timeout_ms`. HTTP 4xx responses fail immediately except `408`; the provider doesn't retry `429`. Transport failures, body-read failures, `408`, and most HTTP 5xx responses can retry; `501` fails immediately. Invalid JSON or a missing `id_lists` response field fails decoding without a retry. Enrichment requests use gzip. Provider construction returns `Result` and rejects an empty base URL or an unreadable custom CA file. Use TLS for remote proxy connections. Configure `StatsigOptions.specs_url` as `<proxy-url>/v2/download_config_specs` if you also want config specs through the proxy. `fallback_to_statsig_api` applies to config specs only. ### Handle build results and verify targeting `build().await` returns `Result<StatsigUser, EnrichmentError>`. On success, pass the user to normal evaluation methods. The builder hashes and deduplicates the user ID and custom ID values before requesting memberships. Numeric IDs and string IDs such as `"00123"` retain their original representations before hashing. A valid response with an empty `id_lists` object succeeds with empty memberships. A missing `id_lists` field, malformed JSON, timeout, failed response-body read, or unsuccessful HTTP status returns an error. Don't replace a build error with empty memberships or an unenriched user; handle the failure explicitly. Replace the sample IDs with a known member's IDs and use a gate with an ID list rule. Confirm the expected gate result, then test a non-member. Build a new enriched user when memberships need refreshing; the provider doesn't cache memberships or update existing users automatically. ## Custom output logger The Output Logger interface lets you customize how the SDK logs messages, enabling integration with your own logging system and control over log verbosity. ```rust pub trait OutputLogProvider: Send + Sync { fn initialize(&self); fn debug(&self, tag: &str, msg: String); fn info(&self, tag: &str, msg: String); fn warn(&self, tag: &str, msg: String); fn error(&self, tag: &str, msg: String); fn shutdown(&self); } ``` ## Observability client The Observability Client interface lets you monitor the health of the SDK by integrating with your own observability systems. This enables you to track metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, refer to the [Monitoring documentation](https://docs.statsig.com/infrastructure/sdk-monitoring). ```rust pub trait ObservabilityClient: Send + Sync { fn init(&self); fn increment(&self, metric_name: &str, value: f64, tags: &HashMap<String, String>); fn gauge(&self, metric_name: &str, value: f64, tags: &HashMap<String, String>); fn dist(&self, metric_name: &str, value: f64, tags: &HashMap<String, String>); fn error(&self, tag: &str, error: &str); } ``` ## Fields needed methods (Enterprise only) > **Info:** > > This is available for Enterprise contracts. Reach out to the Statsig support team, your sales contact, or through the [Slack community](https://statsig.com/slack) if you want this enabled. These methods return an array of strings representing the user fields referenced in the targeting rules or conditions of the specified feature. Use them to understand which user properties influence a particular feature's behavior. ```rust // Get fields needed for a gate let fields_needed: Vec<String> = statsig.get_fields_needed_for_gate("gate_name"); // Get fields needed for a dynamic config let fields_needed: Vec<String> = statsig.get_fields_needed_for_dynamic_config("config_name"); // Get fields needed for an experiment let fields_needed: Vec<String> = statsig.get_fields_needed_for_experiment("experiment_name"); // Get fields needed for a layer let fields_needed: Vec<String> = statsig.get_fields_needed_for_layer("layer_name"); ``` ### Field mapping The fields returned by these methods correspond to the following user properties: ```rust // Field mapping between user properties and internal field names let field_mapping = std::collections::HashMap::from([ ("userID", "u"), ("email", "e"), ("ip", "i"), ("userAgent", "ua"), ("country", "c"), ("locale", "l"), ("appVersion", "a"), ("time", "t"), ("stableID", "s"), ("environment", "en"), ("targetApp", "ta"), ]); // Custom fields are prefixed with "cf:" // Example: fields.add("cf:" + field_name); ``` ## FAQ #### How do I run experiments for logged out users? Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment) ## Reference ### Fields needed methods (Enterprise only) ```rust // Get user fields needed for a gate evaluation pub fn get_fields_needed_for_gate(&self, gate_name: &str) -> Vec<String> // Get user fields needed for a dynamic config evaluation pub fn get_fields_needed_for_dynamic_config(&self, config_name: &str) -> Vec<String> // Get user fields needed for an experiment evaluation pub fn get_fields_needed_for_experiment(&self, experiment_name: &str) -> Vec<String> // Get user fields needed for a layer evaluation pub fn get_fields_needed_for_layer(&self, layer_name: &str) -> Vec<String> ``` > **Info:** > > This is available for Enterprise contracts. Reach out to the Statsig support team, your sales contact, or through the [Slack community](https://statsig.com/slack) if you want this enabled. #### Field mapping The fields returned by these methods correspond to the following user properties: ```plaintext // Field mapping between user properties and internal field names const fieldMapping = { userID: 'u', email: 'e', ip: 'i', userAgent: 'ua', country: 'c', locale: 'l', appVersion: 'a', time: 't', stableID: 's', environment: 'en', targetApp: 'ta', }; // Custom fields are prefixed with "cf:" // Example: fields.add('cf:' + field); ``` ================================================================================ # Elixir Server SDK URL: https://docs.statsig.com/server-core/elixir-core ================================================================================ # Elixir Server SDK - **Package:** `statsig_elixir` ([hex](https://hex.pm/packages/statsig_elixir)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-elixir) ## Setup the SDK 1. **Install the SDK** To use the SDK, add the following to your `mix.exs`: ```elixir {:statsig_elixir, "~> 0.8.0"}, ``` The SDK is written using `rustler_precompiled`, which downloads a precompiled binary by default. You can also build the Rust code within your project by cloning [statsig-server-core](https://github.com/statsig-io/statsig-server-core) ```bash cd statsig-server-core/statsig-elixir/ # set the environment variable FORCE_STATSIG_NATIVE_BUILD="true" mix compile ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a `StatsigOptions` object to customize the SDK. `Statsig.ex` uses GenServer to manage the Statsig instance (which is written in Rust). Add Statsig to your Supervision Tree: ```elixir # Initializing, with StatsigOptions sdk_key = "secret-key******" # your secret key statsig_options = %StatsigOptions{enable_id_lists: true} # Add to your supervision tree statsig_spec = %{id: Statsig, start: {Statsig, :start_link, [sdk_key, statsig_options]}} children = [ # Other Apps statsig_spec ] res = Supervisor.start_link(children, opts) # Or directly initialize the GenServer {:ok,_} = Statsig.start_link(sdk_key, statsig_options) Statsig.initialize() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independent of your API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require a user object (refer to [Statsig user](#statsig-user)). To check a gate for a user: ```elixir user = %StatsigUser{ user_id: "test_user_123" } {:ok, check_gate} = Statsig.check_gate("test_public", user) # check_gate will be a boolean ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send different values (strings, numbers, etc.) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a JSON object from which you can retrieve typed parameters. For example: ```elixir # Get a dynamic config for a specific user user = %StatsigUser{ user_id: "test_user_123" } {:ok, config} = Statsig.get_dynamic_config("a_config", user) # Access the values in the dynamic config: param_value = DynamicConfig.get_param_value(config, "header_text") # Disable exposure options = %Statsig.DynamicConfigEvaluationOptions{ disable_exposure_logging = true } {:ok, config} = Statsig.get_dynamic_config("a_config", user, options) ``` ### Getting a layer/experiment **Layers/Experiments** let you run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) because layers make parameters reusable and support mutually exclusive experiments. ```elixir # Values via get_layer user = %StatsigUser{ user_id: "test_user_123" } {:ok, layer} = Statsig.get_layer("user_promo_experiments", user) {:ok, title_string_value} = Layer.get(layer, "title", "Welcome to Statsig!") {:ok, discount_float_value} = Layer.get(layer, "discount", 0.1) # Via get_experiment {:ok, experiment} = Statsig.get_experiment("user_promo_experiment", user) title_exp = Experiment.get_param_value(experiment, "new_user_promo_title") # Disable exposure options = %Statsig.ExperimentEvaluationOptions{ disable_exposure_logging = true } {:ok, experiment} = Statsig.get_experiment("user_promo_experiment", user, options) ``` > **Note:** > > When you use a layer to get a value, use get param value. This method returns primitive types (boolean, string, and numbers). For more complex types, the SDK returns JSON-serialized values. ### Retrieving feature gate metadata To retrieve more information about a gate evaluation than a boolean value, use the Get Feature Gate API, which returns a `FeatureGate` object: ```elixir {:ok, feature_gate} = Statsig.get_feature_gate(user, "example_gate") # access the value, or the name off of the feature_gate object options = %Statsig.FeatureGateEvaluationOptions{ disable_exposure_logging = true } {:ok, feature_gate} = Statsig.get_feature_gate(user, "example_gate", options) ``` ### Parameter stores If you want dynamic control over whether a value comes from a Feature Gate, Experiment, or Dynamic Config outside your deployment cycle, use Parameter Stores. A Parameter Store lets you define a parameter that you can change at any point in the Statsig console. Parameter Stores are optional, but parameterizing your application supports future flexibility and allows non-technical Statsig users to turn parameters into experiments. > **Note:** > > _Parameter stores are not yet available for this sdk. Need it now? Reach out in Slack._ ### Logging an event After setting up a Feature Gate or Experiment, track custom events to measure how features or experiment groups affect user behavior. Call the Log Event API and specify the user and event name. You can also provide a value and metadata: ```elixir Statsig.log_event(user, "test_event", 1, %{"metadata_1" => "value"}) ``` ### Sending events to Log Explorer You can forward logs to Logs Explorer for analysis using the Forward Log Line Event API. The API lets you include custom metadata and event values with each log. > **Note:** > > Sending events to Log Explorer is not yet available for this sdk. Need it now? Reach out in Slack. ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. More user attributes enable advanced gate and config conditions (such as country or OS/browser checks) and more accurate experiment impact measurement. You must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. For details, refer to [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks). In addition to `userID`, the top-level fields on `StatsigUser` are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass key-value pairs in the `custom` field for targeting. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. Use them for PII or sensitive data that you don't want to send to third-party services. ```elixir user = %Statsig.User{ user_id: "a-user-id", email: "user@example.com", ip: "192.168.1.1", user_agent: "Mozilla/5.0...", country: "US", locale: "en_US", app_version: "1.0.0", custom: %{ # Custom fields "plan" => "premium", "age" => 25 }, custom_ids: %{ # Custom ID types "stable_id" => "stable-id-123" }, private_attributes: %{ # Private attributes not forwarded to integrations "email" => "private@example.com" } } ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | string | No | — | The environment you're operating in (e.g., Production) | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | output_log_level | string | No | — | The type of logs you'd like exposed. (e.g., Debug) | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | init_timeout_ms | number | No | — | How long it should take for initialization to time out. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_flush_interval_ms | number | No | — | How often events should flush to the Statsig servers. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_queue_size | Option<u32> | No | — | Maximum number of events to queue before forcing a flush.- Default is `2000` - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - See also `event_logging_max_pending_batch_queue_size` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_pending_batch_queue_size | Option<u32> | No | — | Maximum number of event batches to hold in buffer to retry.- Default is `100`. - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - eg: 2000 \* 100 means the SDK can process 200k event per second before events start getting dropped - See also `event_logging_max_queue_size`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | log_event_url | string | No | — | The URL events should be logged to | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_sync_interval_ms | number | No | — | How often specs should sync from the Statsig servers | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_url | string | No | — | The URL Statsig should download specs from | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | spec_adapter_configs | list | No | — | Advanced configuration for fetching specs from custom sources, including [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enable_id_lists | boolean | No | — | Enable ID list download. **Required to be `true` when using segments with more than 1000 IDs.** See [ID List segments](https://docs.statsig.com/segments/add-id-list) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_url | string | No | — | The URL ID lists should be downloaded from | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id_lists_sync_interval_ms | number | No | — | How often ID lists should be synced. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_country_lookup_init | boolean | No | — | Block initialization call until country lookup is initialized | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | wait_for_user_agent_init | boolean | No | — | Block initialization call until user\_agent is initialized | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_all_logging | boolean | No | — | When `true`, disables all event logging. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_country_lookup | boolean | No | — | To improve memory usage, disable using country lookup. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_network | boolean | No | — | Turn off all network requests including get\_dcs and log\_events | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_user_agent_parsing | boolean | No | — | To improve memory usage, disable using user agent parsing. | --- ```elixir # Initialize StatsigOptions with custom parameters statsig_options = %StatsigOptions{ enable_id_lists: true } # Pass the options object into statsig.initialize() {:ok, _} = Statsig.start_link(sdk_key, statsig_options) Statsig.initialize() ``` ### Proxy and custom network routing The Elixir Server Core SDK doesn't document a dedicated outbound HTTP proxy config. For custom network routing, use `spec_adapter_configs` for [Statsig Forward Proxy](https://docs.statsig.com/infrastructure/api_proxy/introduction) or set `specs_url`, `log_event_url`, and `id_lists_url` directly. ```elixir statsig_options = %StatsigOptions{ spec_adapter_configs: [ %Statsig.SpecAdapterConfig{ adapter_type: "network_grpc_websocket", specs_url: "http://forward-proxy.internal:50051", authentication_mode: "none" } ], fallback_to_statsig_api: true } ``` ## Shutting Statsig down Because the SDK batches events and periodically flushes them, some events might not send before your app or server shuts down. To flush all logged events, call `shutdown()` before your app or server shuts down: ```elixir Statsig.shutdown() ``` ## Client SDK Bootstrapping | SSR If you are using the Statsig client SDK in a browser or mobile app, you can bootstrap the client SDK with values from the server SDK to avoid a network request on the client. Bootstrapping is useful for server-side rendering (SSR) or when you want to reduce the number of network requests on the client. ```elixir # Get client initialize response for a user {:ok, response} = Statsig.get_client_init_response_as_string(user) # Pass values to a client SDK to initialize without a network request ``` ## Persistent storage The Persistent Storage interface lets you implement custom storage for user-specific configurations. Use it to persist user assignments across sessions, ensuring consistent experiment groups when users return. Persistent storage is useful for client-side A/B testing where users must always see the same variant. > **Note:** > > Not supported yet. ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems. > **Note:** > > Not supported yet. ## Custom output logger The Output Logger interface lets you customize how the SDK logs messages, enabling integration with your own logging system and control over log verbosity. > **Note:** > > Not supported yet. ## Observability client The Observability Client interface lets you monitor SDK health by integrating with your own observability systems, enabling tracking of metrics, errors, and performance data. For more information on the metrics emitted by Statsig SDKs, go to the [Monitoring documentation](https://docs.statsig.com/infrastructure/sdk-monitoring). > **Note:** > > Not supported yet. ## FAQ #### How do I run experiments for logged out users? Refer to the guide on [device level experiments](https://docs.statsig.com/guides/logging-events#device-level-events) ================================================================================ # PHP Server SDK URL: https://docs.statsig.com/server-core/php-core ================================================================================ # PHP Server SDK - **Package:** `statsig/statsig-php-core` ([composer](https://packagist.org/packages/statsig/statsig-php-core)) - **Latest version:** 0.24.0 - **Repository:** [statsig-server-core](https://github.com/statsig-io/statsig-server-core/tree/main/statsig-php) > **Tip:** > > Migrating from the legacy PHP SDK? Refer to the [Migration Guide](https://docs.statsig.com/server-core/migration-guides/php). ## Set up the SDK 1. **Install the SDK** ## Installation ### 1. Install and add as a dependency Install the PHP Core SDK using Composer: ```shell composer require statsig/statsig-php-core ``` ### 2. PHP configuration requirements The PHP Core SDK uses the FFI extension to interface with the Rust core. Enable FFI in your PHP configuration by setting `ffi.enable=true` in your php.ini file. For more information about this setting, go to the [PHP manual for ffi.enable](https://www.php.net/manual/en/ffi.configuration.php#ini.ffi.enable). ### 3. Add scripts & cron job Add post-install and post-update scripts in composer.json: ```json // composer.json { "name": "awesome-php-project", ... "scripts": { ... "post-install-cmd": [ "cd vendor/statsig/statsig-php-core && php post-install.php" ], "post-update-cmd": [ "cd vendor/statsig/statsig-php-core && php post-install.php" ] } } ``` Add a script to sync your Statsig configs and flush your events. For example files, go to [Statsig's GitHub](https://github.com/daniel-statsig/statsig-php-core-slim-example/tree/main/bin). Set up cron jobs to run these scripts periodically: ```shell */10 * * * * /usr/bin/php /var/www/example.com/bin/StatsigSyncConfig.php 1>> /dev/null 2>&1 */1 * * * * /usr/bin/php /var/www/example.com/bin/StatsigFlushEvents.php 1>> /dev/null 2>&1 ``` Run the StatsigSyncConfig.php cron job at least once before proceeding. 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. An optional `options` parameter accepts a StatsigOptions object to customize the SDK. Add your client secret key to the environment using a .env file or on the command line: ```shell export STATSIG_SECRET_KEY=secret-123456789 ``` ```php // At the top of your file use Statsig\Statsig; use Statsig\StatsigOptions; use Statsig\StatsigLocalFileEventLoggingAdapter; use Statsig\StatsigLocalFileSpecsAdapter; //In the case of slim framework, in container builder definitions: Statsig::class => function (ContainerInterface $c) { $sdk_key = getenv("STATSIG_SECRET_KEY"); $options = new StatsigOptions( null, null, new StatsigLocalFileSpecsAdapter($sdk_key, "/tmp"), new StatsigLocalFileEventLoggingAdapter($sdk_key, "/tmp") ); $statsig = new Statsig($sdk_key, $options); $statsig->initialize(); return $statsig; }, ``` > **Warning:** > > `StatsigLocalFile` Adapters rely on cron jobs and files. If you see errors around file access, ensure your cron job has run at least one time before using Statsig. Go to [Add Scripts & Cron Job](#2-add-scripts--cron-job) `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ## Working with the SDK ### Checking a feature flag/gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example: ```php use Statsig\Statsig; use Statsig\StatsigUserBuilder; $user = StatsigUserBuilder::withUserID('my_user')->build(); $passed = $statsig->checkGate($user, 'my_gate'); ``` ### Reading a dynamic config Feature Gates are useful for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and similar types) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a full JSON object configurable on the server from which you can fetch typed parameters. ```php $user = StatsigUserBuilder::withUserID('my_user')->build(); $config = $statsig->getDynamicConfig($user, 'my_config'); ``` ### Getting a layer/experiment Use **Layers/Experiments** to run A/B/n experiments. Statsig provides two APIs and recommends [Layers](https://docs.statsig.com/experiments/layers-overview) because they make parameters reusable and support mutually exclusive experiments. ```php $user = StatsigUserBuilder::withUserID('my_user')->build(); $xp = $statsig->getExperiment($user, 'an_experiment'); ``` ### Retrieving feature gate metadata In certain scenarios, you may need more information about a gate evaluation than a boolean value. For additional metadata about the evaluation, use the Get Feature Gate API, which returns a FeatureGate object: ```php $gate = $statsig->getFeatureGate($user, "example_gate"); ``` ### Parameter stores Use Parameter Stores when you want to define a parameter without deciding whether it should be a Feature Gate, Experiment, or Dynamic Config. Parameter Stores let you change the parameter type at any point in the Statsig console without a new deployment. Parameter Stores are optional, but parameterizing your application provides future flexibility and allows non-technical Statsig users to turn parameters into experiments. _Parameter stores aren't available for this SDK yet. Need it now? Reach out in [Slack](https://statsig.com/slack)._ ### Logging an event To track custom events, call the Log Event API. Specify the user, event name, and an optional value or metadata object: ```php $user = StatsigUserBuilder::withUserID('my_user')->build(); $statsig->logEvent($user, 'an_experiment'); ``` ### Sending events to Log Explorer You can forward logs to Logs Explorer for convenient analysis using the Forward Log Line Event API. This lets you include custom metadata and event values with each log. Log Explorer event forwarding isn't available for this SDK yet. Need it now? Reach out in [Slack](https://statsig.com/slack). ## Using shared instance To create a single Statsig instance accessible globally throughout your codebase, use the shared instance functionality, which provides a singleton pattern: ```php use Statsig\Statsig; // Initialize the shared instance Statsig::initializeShared('your-server-secret-key', $options); // Access the shared instance from anywhere in your code $user = StatsigUserBuilder::withUserID('my_user')->build(); $gate = Statsig::shared()->checkGate($user, 'my_gate'); // Shutdown the shared instance when your application closes Statsig::shared()->shutdown(); ``` ## Statsig user The `StatsigUser` object represents a user in Statsig. You must provide a `userID` or at least one of the `customIDs` to identify the user. When calling APIs that require a user, pass as much information as possible. Complete user information lets you take advantage of advanced gate and config conditions (like country or OS/browser-level checks) and correctly measure the impact of experiments on metrics and events. As explained in [why an ID is always required for server SDKs](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks), you must provide at least one identifier (userID or customID) to ensure a consistent experience for a given user. In addition to userID, the top-level fields on StatsigUser are: email, ip, userAgent, country, locale, and appVersion. You can also pass any key-value pairs in an object or dictionary to the custom field and create targeting based on them. ### Private attributes Private attributes are user attributes that Statsig uses for evaluation but doesn't forward to any integrations. They are useful for PII or sensitive data that you don't want to send to third-party services. ```php use Statsig\StatsigUser; $user = new StatsigUser([ 'userID' => 'a-user-id', 'email' => 'user@example.com', 'ip' => '192.168.1.1', 'userAgent' => 'Mozilla/5.0...', 'country' => 'US', 'locale' => 'en_US', 'appVersion' => '1.0.0', 'custom' => [ // Custom fields 'plan' => 'premium', 'age' => 25 ], 'customIDs' => [ // Custom ID types 'stableID' => 'stable-id-123' ], 'privateAttributes' => [ // Private attributes not forwarded to integrations 'email' => 'private@example.com' ] ]); ``` Set the `privateAttributes` parameter in the `StatsigUser` constructor to define which attributes are private so that Statsig doesn't forward them to any third-party integrations. The `privateAttributes` parameter is a key-value dictionary where keys are attribute names and values are the private values. In the example user object above, the key `"email"` appears both in the top-level `email` field and in `privateAttributes`. These are distinct: you can have a non-private value in the top-level `email` field and a private value in `private_attributes`, or vice versa. ```php $user = new StatsigUser([ 'userID' => 'a-user-id', 'email' => 'non_private@example.com', 'privateAttributes' => [ 'email' => 'private@example.com' ] ]); ``` ## Statsig options You can pass an optional `options` parameter in addition to `sdkKey` during initialization to customize the Statsig client. #### StatsigOptions | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_url | string | No | — | Custom URL for fetching feature specifications. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | log_event_url | string | No | — | Custom URL for logging events. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_adapter | StatsigSpecsAdapter | No | — | An adapter with custom storage behavior for config specs. For example, use `StatsigLocalFileSpecsAdapter` to store configs in the local filesystem. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_adapter | StatsigEventLoggingAdapter | No | — | An adapter with custom event logging behavior. For example, use `StatsigLocalFileEventLoggingAdapter` to store events in the local filesystem. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | string | No | — | Environment parameter for evaluation. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_flush_interval_ms | int | No | — | How often the SDK flushes events to Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_queue_size | Option<u32> | No | — | Maximum number of events to queue before forcing a flush.- Default is `2000` - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - Refer to `event_logging_max_pending_batch_queue_size` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_logging_max_pending_batch_queue_size | Option<u32> | No | — | Maximum number of event batches to hold in buffer to retry.- Default is `100`. - event\_logging\_max\_queue\_size \* event\_logging\_max\_pending\_batch\_queue\_size is the upper limit on how many events are queued - eg: 2000 \* 100 means the SDK can process 200k event per second before events start getting dropped - Refer to `event_logging_max_queue_size`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | specs_sync_interval_ms | int | No | — | How often the SDK updates specifications from Statsig servers (in milliseconds). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | output_log_level | string | No | — | Controls the verbosity of SDK logs. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_country_lookup | bool | No | — | Disables country lookup based on IP address. Set to `true` to improve performance if you don't need country-based targeting. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disable_user_agent_parsing | bool | No | — | Disables user agent parsing. Set to `true` to improve performance if you don't need device or browser-based targeting. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | init_timeout_ms | int | No | — | Maximum time in milliseconds to wait for SDK initialization to complete. If initialization takes longer than this timeout, the SDK continues to operate but may return default values until it completes. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallback_to_statsig_api | bool | No | — | When set to true, the SDK falls back to the Statsig API directly if custom adapters (like local file adapters) fail to load configurations. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | enable_id_lists | bool | No | — | Enable/disable ID list functionality. **Required to be `true` when using segments with more than 1000 IDs.** Refer to [ID List segments](https://docs.statsig.com/segments/add-id-list) for more details. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxy_config | ProxyConfig | No | — | Configuration for connecting through a proxy server. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | spec_adapter_config | SpecAdapterConfig | No | — | Configures the source used to retrieve feature specifications. Use `SpecAdapterConfig::TYPE_NETWORK_GRPC_WEBSOCKET` to stream specifications from the [Statsig Forward Proxy](https://docs.statsig.com/server/concepts/forward_proxy).The PHP SDK accepts one spec adapter. If the configured source is unavailable during initialization, initialization fails after the adapter initialization timeout. | #### ProxyConfig | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyHost | string | No | — | The hostname or IP address of the proxy server (e.g., `"proxy.example.com"` or `"192.168.1.100"`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyPort | int | No | — | The port number of the proxy server (e.g., `8080`, `3128`, `1080`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyAuth | string | No | — | Authentication credentials for the proxy server in the format `"username:password"`. Required only if the proxy requires authentication. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxyProtocol | string | No | — | The protocol to use for the proxy connection. Supported values: `"http"`, `"https"`, `"socks5"`. | ### Proxy and custom network routing The PHP Server Core SDK supports a dedicated `proxy_config` for a standard outbound HTTP proxy. If you only need to route Statsig traffic to different endpoints, use `specs_url`, `log_event_url`, and `id_lists_url`. ### Statsig Forward Proxy Use `spec_adapter_config` to stream feature specifications from the Statsig Forward Proxy over gRPC websocket: ```php use Statsig\SpecAdapterConfig; use Statsig\Statsig; use Statsig\StatsigOptions; $specAdapterConfig = new SpecAdapterConfig( adapterType: SpecAdapterConfig::TYPE_NETWORK_GRPC_WEBSOCKET, specsUrl: "http://forward-proxy.internal:50051", authenticationMode: SpecAdapterConfig::AUTH_NONE ); $options = new StatsigOptions( spec_adapter_config: $specAdapterConfig ); $statsig = new Statsig($sdk_key, $options); $statsig->initialize(); ``` `initTimeoutMs` defaults to 3000 milliseconds. For TLS, use `SpecAdapterConfig::AUTH_TLS` and provide `caCertPath`. For mTLS, use `SpecAdapterConfig::AUTH_MTLS` and also provide `clientCertPath` and `clientKeyPath`. Use `domainName` to override the TLS server name used for certificate verification. The spec adapter controls specification downloads only. Continue to configure `log_event_url` and `id_lists_url` separately when required. --- ### Performance recommendations If you experience performance issues, particularly with long initialization times, disable user agent parsing and country lookup to improve performance: - Set `disable_user_agent_parsing: true` if you don't need device or browser-based targeting. - Set `disable_country_lookup: true` if you don't need country-based targeting. Statsig added these optimizations in response to performance issues identified in [PR #1119](https://github.com/statsig-io/private-statsig-server-core/pull/1119). --- ### Example usage ```php use Statsig\Statsig; use Statsig\StatsigOptions; use Statsig\ProxyConfig; use Statsig\StatsigLocalFileSpecsAdapter; use Statsig\StatsigLocalFileEventLoggingAdapter; // Create proxy configuration $proxyConfig = new ProxyConfig( proxyHost: "proxy.example.com", proxyPort: 8080, proxyAuth: "username:password", // Optional, only if the proxy requires authentication proxyProtocol: "http" ); // Initialize StatsigOptions with custom parameters $options = new StatsigOptions( specs_url: null, log_event_url: null, specs_adapter: new StatsigLocalFileSpecsAdapter($sdk_key, "/tmp"), event_logging_adapter: new StatsigLocalFileEventLoggingAdapter($sdk_key, "/tmp"), environment: "development", event_logging_flush_interval_ms: 60000, event_logging_max_queue_size: 1000, specs_sync_interval_ms: 600000, output_log_level: "INFO", disable_country_lookup: true, // For better performance wait_for_country_lookup_init: false, wait_for_user_agent_init: false, enable_id_lists: false, disable_network: false, id_lists_url: null, id_lists_sync_interval_ms: null, disable_all_logging: false, init_timeout_ms: 3000, fallback_to_statsig_api: false, use_third_party_ua_parser: null, persistent_storage: null, proxy_config: $proxyConfig // Add proxy configuration ); // Pass the options object into Statsig constructor $statsig = new Statsig($sdk_key, $options); $statsig->initialize(); ``` > **Warning:** > > When using `StatsigLocalFile` Adapters, ensure your cron job has run at least one time before using Statsig. Go to [Add Scripts & Cron Job](#2-add-scripts--cron-job) ## Custom adapters ### SpecsAdapterBase - custom configuration sources The `SpecsAdapterBase` lets you fetch Statsig configurations from custom sources instead of (or in addition to) Statsig's servers. This is useful when you want to: - Store configurations in your own database or cache (e.g., Redis, Memcached) - Implement custom caching strategies - Use Statsig in environments with restricted network access - Reduce latency by serving configs from a local source #### Implementation To create a custom specs adapter, extend the `SpecsAdapterBase` class and implement the required methods. ```php <?php use Statsig\SpecsAdapterBase; use Statsig\SpecsUpdateListener; class RedisSpecsAdapter extends SpecsAdapterBase { private $redis; private $listener; public function __construct($redis) { parent::__construct(); $this->redis = $redis; } public function setup(SpecsUpdateListener $listener): void { $this->listener = $listener; } public function start(): void { // Fetch initial specs when SDK starts $this->refreshSpecsFromRedis(); // Optionally, trigger a background job or set up a timer $this->refreshSpecsFromRedis(); } private function fetchSpecsFromRedis() { try { $specs = $this->redis->get('statsig_config_specs'); return $specs ?: null; } catch (Exception $e) { error_log("Failed to fetch specs from Redis: " . $e->getMessage()); return null; } } private function refreshSpecsFromRedis() { $specs = $this->fetchSpecsFromRedis(); if ($specs && $this->listener) { $timestamp = intval(microtime(true) * 1000); $this->listener->didReceiveSpecsUpdate($specs, "Redis", $timestamp); } } } ``` #### Usage ```php use Statsig\Statsig; use Statsig\StatsigOptions; $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $specsAdapter = new RedisSpecsAdapter($redis); $options = new StatsigOptions( specs_adapter: $specsAdapter ); $statsig = new Statsig('your-server-secret-key', $options); $statsig->initialize(); ``` #### Key methods - **`setup(SpecsUpdateListener $listener)`**: Called during initialization to provide the listener for spec updates - **`start()`**: Called when the SDK starts. Fetch and provide initial configuration specs - **`shutdown()`**: Called when the SDK shuts down. Clean up resources - **`scheduleBackgroundSync()`**: Called to schedule periodic updates of configuration specs The `SpecsUpdateListener` provides: - **`didReceiveSpecsUpdate(string $specs, string $source, int $timestamp)`**: Notify the SDK of new specs - **`getCurrentSpecsInfo()`**: Get information about current specs --- ### EventLoggingAdapterBase - custom event destinations The `EventLoggingAdapterBase` lets you send events to custom destinations instead of or in addition to Statsig's servers. This is useful when you want to: - Send events to your existing analytics platform - Store events in a database for custom analysis - Forward events to multiple destinations - Implement custom batching or retry logic #### Implementation To create a custom event logging adapter, extend the `EventLoggingAdapterBase` class and implement the required methods. ```php <?php use Statsig\EventLoggingAdapterBase; use Statsig\LogEventRequest; class AnalyticsEventAdapter extends EventLoggingAdapterBase { private $analyticsClient; private $isStarted = false; public function __construct($analyticsClient) { parent::__construct(); $this->analyticsClient = $analyticsClient; } public function start(): void { $this->isStarted = true; // Initialize analytics client connection if needed $this->analyticsClient->connect(); } public function logEvents(LogEventRequest $request): bool { if (!$this->isStarted) { return false; } try { $events = $request->payload->events; $metadata = $request->payload->statsig_metadata; foreach ($events as $event) { // Transform Statsig event to analytics platform format $analyticsEvent = [ 'event_name' => $event['eventName'], 'user_id' => $event['user']['userID'] ?? null, 'timestamp' => $event['time'], 'properties' => array_merge( $event['metadata'] ?? [], ['statsig_metadata' => $metadata] ) ]; // Send to analytics platform $this->analyticsClient->track($analyticsEvent); } return true; } catch (Exception $e) { error_log("Failed to log events to analytics platform: " . $e->getMessage()); return false; } } public function shutdown(): void { $this->isStarted = false; // Clean up analytics client connection $this->analyticsClient->disconnect(); } } ``` #### Usage ```php use Statsig\Statsig; use Statsig\StatsigOptions; $analyticsClient = new MyAnalyticsClient('api-key'); $eventAdapter = new AnalyticsEventAdapter($analyticsClient); $options = new StatsigOptions( event_logging_adapter: $eventAdapter ); $statsig = new Statsig('your-server-secret-key', $options); $statsig->initialize(); // Events now go to your custom analytics platform $statsig->logEvent($user, 'button_clicked', ['button_id' => 'signup']); ``` #### Key methods - **`start()`**: Called when the SDK starts. Initialize connections or resources - **`logEvents(LogEventRequest $request): bool`**: Process and send events. Return true on success, false on failure - **`shutdown()`**: Called when the SDK shuts down. Clean up resources The `LogEventRequest` contains: - **`event_count`**: Number of events in the request - **`retries`**: Number of retry attempts for this request - **`payload`**: `LogEventPayload` with events and metadata The `LogEventPayload` contains: - **`events`**: Array of event objects with user data, event names, and metadata - **`statsig_metadata`**: SDK metadata including version and environment information ## Client initialize response Use `getClientInitializeResponse` to generate bootstrap values for a client SDK from the PHP Core SDK's cached specs. Bootstrapping supports server-side rendering (SSR) and avoids the client's initial evaluation request. Initialize the server SDK before generating a response. For an initialized server SDK and user, generate a response with the default options: ```php $bootstrapJson = $statsig->getClientInitializeResponse($user); ``` #### Full code example and client bootstrapping `getClientInitializeResponse` returns a JSON string, not a PHP array. This example uses an initialized `$statsig` instance: ```php use Statsig\StatsigUserBuilder; $user = StatsigUserBuilder::withUserID('a-user')->build(); // Use the default options. $bootstrapJson = $statsig->getClientInitializeResponse($user); // Or restrict the response to a client key and selected configs. $filteredBootstrapJson = $statsig->getClientInitializeResponse($user, [ 'client_sdk_key' => 'client-sdk-key', 'hash_algorithm' => 'djb2', 'feature_gate_filter' => ['onboarding_v2', 'new_checkout'], 'experiment_filter' => ['pricing_experiment'], 'include_local_overrides' => false, ]); ``` Options use `snake_case` keys, not the Node SDK's `camelCase` names. To return the response from a PHP endpoint, send the JSON string directly: ```php header('Content-Type: application/json'); echo $filteredBootstrapJson; ``` Don't call `json_encode` on the response string: encoding it again produces a quoted JSON string. If your framework serializes response objects, decode the string first with `json_decode($filteredBootstrapJson, true, 512, JSON_THROW_ON_ERROR)`. Pass the response to your client SDK's bootstrap API. For the JavaScript client, follow [Using EvaluationsDataAdapter](https://docs.statsig.com/client/javascript-mono/UsingEvaluationsDataAdapter). #### Initialize response options Pass an optional associative array as the second argument to `getClientInitializeResponse`: | Key | Type | Behavior | | --- | --- | --- | | `hash_algorithm` | `string` | Controls config-name hashing: `'djb2'` (default), `'sha256'`, or `'none'` (unhashed). Name hashing isn't encryption or an integrity check. | | `client_sdk_key` | `string` | Restricts the response to the client key's [target app](https://docs.statsig.com/sdks/target-apps). Use the key that initializes the client SDK. | | `include_local_overrides` | `bool` | Includes local overrides in evaluations when `true`. Defaults to `false`. | | `feature_gate_filter` | `string[]` | Includes only the named feature gates. | | `experiment_filter` | `string[]` | Includes only the named experiments. | | `dynamic_config_filter` | `string[]` | Includes only the named dynamic configs. | | `layer_filter` | `string[]` | Includes only the named layers. | | `param_store_filter` | `string[]` | Includes only the named parameter stores. | Filters take original config names, even when the response hashes those names. Omit a filter to leave that config type unrestricted. Use `client_sdk_key` to apply target-app restrictions rather than relying on name filters alone. #### Hash algorithm Choose how the response hashes config names. The default is `djb2`; choose no hashing only when your client integration requires unhashed names. ```php $bootstrapJson = $statsig->getClientInitializeResponse($user, [ 'hash_algorithm' => 'djb2', ]); ``` #### Client SDK key Use the client SDK key to apply its [target-app restrictions](https://docs.statsig.com/sdks/target-apps) to the response. ```php $bootstrapJson = $statsig->getClientInitializeResponse($user, [ 'client_sdk_key' => 'client-sdk-key', ]); ``` #### Filtering Select specific config names to reduce the response size. Filters for other config types remain unset in this example. ```php $bootstrapJson = $statsig->getClientInitializeResponse($user, [ 'feature_gate_filter' => ['onboarding_v2', 'new_checkout'], 'experiment_filter' => ['pricing_experiment'], ]); ``` #### Include local overrides Set this option to include local overrides when generating bootstrap values for development or testing. ```php $bootstrapJson = $statsig->getClientInitializeResponse($user, [ 'include_local_overrides' => true, ]); ``` #### Match the client user Generate the response for the same user ID, custom IDs, and evaluation attributes that the client SDK uses. When targeting depends on IP address or user agent, pass those request attributes to the server-side user. If you use Stable ID, share the same `stableID` custom ID between server and client. Keep the server secret key on the server. Send each user only their own bootstrap response, and don't share a cached response across users. Config-name filters and name hashing aren't substitutes for authorization. ## Shutting Statsig down Statsig batches and periodically flushes events. To flush all logged events before shutdown, call `shutdown()` before your app or server shuts down: ```php // Method signature public function shutdown(): void // example usage try { $statsig->shutdown(); echo "Statsig instance has been successfully shutdown.\n"; } catch (Exception $e) { error_log($e->getMessage()); } ``` Alternatively, if you operate in a serverless environment or cloud function and want to keep Statsig running in case the function is recycled, flush the logs to Statsig servers. To wait for logs to post before resolving, use: ```php // Method signature public function flushEvents(): void // example usage try { $statsig->flushEvents(); echo "All events have been successfully flushed.\n"; } catch (Exception $e) { echo "Failed to flush events: " . $e->getMessage() . "\n"; } ``` ## Local overrides Local Overrides let you override the values of gates, configs, experiments, and layers for testing. This is useful for local development or testing when you want to force a specific value without changing the configuration in the Statsig console. ```php $statsig->overrideGate("a_gate_name", true); $statsig->overrideDynamicConfig("a_config_name", [ "key" => "value", ]); $statsig->overrideExperiment("an_experiment_name", [ "key" => "value", ]); $statsig->overrideExperimentByGroupName("an_experiment_name", "a_group_name"); $statsig->overrideLayer("a_layer_name", [ "key" => "value", ]); ``` You can also pass a third argument to scope an override to a specific ID: ```php $statsig->overrideExperimentByGroupName("an_experiment_name", "a_group_name", "user_123"); ``` ## Persistent storage The Persistent Storage interface lets you implement custom storage for experiment assignments. This ensures consistent user experiences across sessions by persisting experiment assignments. For more information, go to the [Persistent Assignment](https://docs.statsig.com/server/concepts/persistent_assignment) documentation. ```php use Statsig\PersistentStorage; use Statsig\StickyValues; class MyPersistentStorage extends PersistentStorage { private array $storage = []; public function load(string $key): ?array { return $this->storage[$key] ?? null; } public function save(string $key, string $config_name, StickyValues $data): void { $this->storage[$key] ??= []; $this->storage[$key][$config_name] = $data->toArray(); } public function delete(string $key, string $config_name): void { unset($this->storage[$key][$config_name]); } } ``` ```php $persistent_storage = new MyPersistentStorage(); $options = new StatsigOptions( persistent_storage: $persistent_storage ); $statsig = new Statsig("secret-key", $options); $statsig->initialize(); $persisted_user = new StatsigUser("test-123"); $values = $persistent_storage->getValuesForUser($persisted_user, "userID") ?? []; $experiment = $statsig->getExperiment( $persisted_user, "active_experiment", ["user_persisted_values" => $values], ); ``` ## Data store The Data Store interface lets you implement custom storage for Statsig configurations, enabling advanced caching strategies and integration with your preferred storage systems. > **Note:** > > Not supported yet. ## Custom output logger The Output Logger interface lets you customize how the SDK logs messages, enabling integration with your own logging system and control over log verbosity. > **Note:** > > Not supported yet. ## Observability client The Observability Client interface lets you monitor the health of the SDK by integrating with your own observability systems. This enables you to track metrics, errors, and performance data. For more information on the metrics Statsig SDKs emit, refer to the [Monitoring](https://docs.statsig.com/infrastructure/sdk-monitoring) documentation. > **Note:** > > Not supported yet. ## Notes on beta version The PHP SDK requires an adapter for both logging and saving config specs, given the stateless nature of PHP. [The example repository](https://github.com/daniel-statsig/statsig-php-core-slim-example) provides simple file-based adapters. More mature implementations may use a different, more performant caching approach. For help with setup, reach out on [Slack](https://statsig.com/slack). ## FAQ #### How do I run experiments for logged out users? Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ================================================================================ # Legacy Server SDKs URL: https://docs.statsig.com/server-core/legacy-sdks ================================================================================ # Legacy Server SDKs Statsig is transitioning to the Statsig Server Core architecture, which unifies all Server SDKs around a performance-optimized core package. Server Core delivers improved performance and greater feature consistency. Most customers continue to use legacy SDKs, which remain supported except for major feature additions. ## Timelines Statsig has announced end-of-life dates for some Legacy Server SDKs. [Server Core SDKs](https://docs.statsig.com/server-core) often evaluate 5-10x faster than legacy SDKs and are more feature complete. Go to the docs for existing SDKs below: - [Node](https://docs.statsig.com/server/nodejsServerSDK) - [Python](https://docs.statsig.com/server/pythonSDK) - [Elixir/Erlang](https://docs.statsig.com/server/erlang) (End of Life April 30th, 2026) - [Java](https://docs.statsig.com/server/java) - [Rust](https://docs.statsig.com/server/rust) (End of Life April 30th, 2026) - [Go](https://docs.statsig.com/server/go) - [PHP](https://docs.statsig.com/server/php) - [.NET](https://docs.statsig.com/server/dotnet) ================================================================================ # C++ Server SDK URL: https://docs.statsig.com/server/cpp ================================================================================ # C++ Server SDK - **Repository:** [cpp-server-sdk](https://github.com/statsig-io/cpp-server-sdk) ## Set up the SDK 1. **Install the SDK** If you're using CMake, add the following to a `.cmake` file: ```cmake FetchContent_Declare(statsig GIT_REPOSITORY https://github.com/statsig-io/cpp-server-sdk.git GIT_TAG v0.1.0 ) FetchContent_MakeAvailable(statsig) ``` And include the following in your `CMakeLists.txt` file: ```cmake cmake_minimum_required(VERSION 3.11) include(FetchContent) include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/statsig.cmake) ``` Check out the latest versions on [https://github.com/statsig-io/cpp-server-sdk/releases/latest](https://github.com/statsig-io/cpp-server-sdk/releases/latest) 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console. ```cpp #include <statsig.h> statsig::initialize('server-secret-key'); // Or, if you want to initialize with certain options statsig::Options options; options.localMode = true statsig::initialize('server-secret-key', options) ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can fetch a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (equivalent to `return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example: ```cpp statsig::User user; user.userID = "some_user_id" if (statsig::checkGate(user, 'use_new_feature')) { // Gate is on, enable new feature } else { // Gate is off } ``` ## Reading a Dynamic Config Feature Gates are useful for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and similar types) to clients based on user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The API is similar to Feature Gates, but returns a full JSON object configurable on the server from which you can fetch typed parameters. ```cpp statsig::DynamicConfig config = statsig::get_config(user, 'awesome_product_details') auto item_name = config.value['product_name']; auto price = config.value['price']; auto shouldDiscount = config.value['discount']; ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available. Statsig recommends [Layers](https://docs.statsig.com/experiments/layers-overview) because they enable quicker iterations with parameter reuse. ```cpp // Values via getLayer statsig::Layer layer = statsig::getLayer(user, "user_promo_experiments") auto title = layer.get("title", "Welcome to Statsig!") auto discount = layer.get("discount") // or, via getExperiment statsig::DynamicConfig title_exp = statsig::getExperiment(user, "new_user_promo_title") statsig::DynamicConfig price_exp = statsig::getExperiment(user, "new_user_promo_price") title = title_exp.value["title"] discount = price_exp.value["discount"] ... price = msrp * (1 - discount) ``` ## Logging an Event To track custom events, call the Log Event API. Specify the user, event name, and an optional value or metadata object: ```cpp statsig::logEvent(user, 'add_to_cart') ``` Learn more about identifying users, group analytics, and best practices for logging events in the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible to take advantage of advanced gate and config conditions (like country or OS/browser level checks) and to correctly measure the impact of experiments on metrics and events. As explained in [the server SDK user ID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks), Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. In addition to `userID`, the top-level fields on StatsigUser are: `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object or dictionary to the `custom` field and create targeting based on them. > **Note:** > > While typing is lenient on the `StatsigUser` object, evaluation operators only work on primitive types (mostly strings and numbers). The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for non-primitive types. For example, the SDK compares an array set as a custom field only as a string. ### Private Attributes The `StatsigUser` object also has a `privateAttributes` field, which is a dictionary for setting private user attributes. The SDK uses attributes in `privateAttributes` only for evaluation and targeting, and removes them from logs before sending them to the Statsig server. For example, if a feature gate should pass only for users with emails ending in "@statsig.com" but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes`. ## Statsig Options `initialize()` takes an optional `options` parameter in addition to the secret key to customize the Statsig client. Available options include: | Option | Type | Default | Description | | --- | --- | --- | --- | | `api` | String | `"https://statsigapi.net/v1"` | Base URL for network requests from the SDK. | | `rulesetsSyncIntervalMs` | Integer | `10000` | Interval to poll for changes to your gate and config definitions. | | `loggingIntervalMs` | Integer | `60000` | Interval to flush logs to Statsig servers. | | `loggingMaxBufferSize` | Integer | `1000` | Maximum number of events to batch before flushing logs to the server. You can set a lower value, but the server drops anything over 1000. | | `localMode` | Boolean | `false` | Restricts the SDK from issuing network requests; the SDK responds only with default values or local overrides. | > **Info:** > > The C++ server SDK doesn't support ID Lists ## Shutdown To gracefully shut down the SDK and flush all events: ```cpp statsig::shutdown() ``` ## Local overrides You can override the values the SDK returns for testing. This is useful for local development when you want to test specific scenarios. ```cpp // Adding gate overrides statsig::overrideGate("a_gate_name", true) // Adding config overrides std::unordered_map<std::string, JSON::any> overrideValue = { {"overridden key", "overridden field"}, }; statsig::overrideConfig("a_config_name", overrideValue) ``` ## FAQ #### How do I run experiments for logged out users Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). ## Reference ### User ```cpp struct User { std::string userID; std::string email; std::string ipAddress; std::string userAgent; std::string country; std::string locale; std::string appVersion; std::unordered_map<std::string, JSON::any> custom; std::unordered_map<std::string, JSON::any> privateAttribute; std::unordered_map<std::string, std::string> statsigEnvironment; std::unordered_map<std::string, std::string> customIDs; }; inline bool operator==(User const &a, User const &b) { return a.userID == b.userID && a.email == b.email && a.ipAddress == b.ipAddress && a.userAgent == b.userAgent && a.country == b.country && a.locale == b.locale && a.appVersion == b.appVersion && a.custom == b.custom && a.privateAttribute == b.privateAttribute && a.statsigEnvironment == b.statsigEnvironment && a.customIDs == b.customIDs; }; ``` ### Options ```cpp struct Options { std::string api; bool localMode; int rulesetsSyncIntervalMs; int loggingIntervalMs; int loggingMaxBufferSize; Options() : api("https://statsigapi.net"), localMode(false), rulesetsSyncIntervalMs(10 * 1000), loggingIntervalMs(60 * 1000), loggingMaxBufferSize(1000){}; }; ``` ================================================================================ # Legacy Go Server SDK URL: https://docs.statsig.com/server/go ================================================================================ # Legacy Go Server SDK - **Package:** `github.com/statsig-io/go-sdk` ([gomod](https://pkg.go.dev/github.com/statsig-io/go-sdk)) - **Latest version:** v1.40.1 - **Repository:** [go-sdk](https://github.com/statsig-io/go-sdk) > **Warning:** > > This page covers the legacy Go SDK. For new implementations, use the [Go Core SDK](https://docs.statsig.com/server-core/go-core) built on the Server Core framework. ## Setup the SDK 1. **Install the SDK** Using the `go get` CLI: ```bash go get github.com/statsig-io/go-sdk ``` Or, add a dependency on the most recent version of the SDK in go.mod: ```go require ( github.com/statsig-io/go-sdk v1.26.0 ) ``` Refer to the [Releases tab in GitHub](https://github.com/statsig-io/go-sdk/releases) for the latest versions. 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console. ```go import ( statsig "github.com/statsig-io/go-sdk" ) statsig.Initialize("server-secret-key") // Or, if you want to initialize with certain options statsig.InitializeWithOptions("server-secret-key", &Options{Environment: Environment{Tier: "staging"}}) ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```go user := statsig.User{UserID: "some_user_id"} feature := statsig.CheckGate(user, "use_new_feature") if feature { // Gate is on, enable new feature } else { // Gate is off } ``` ## Retrieving Feature Gate Metadata When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata: ```go user := statsig.User{UserID: "some_user_id"} feature := statsig.GetGate(user, "use_new_feature") if feature.Value { // Gate is on, enable new feature fmt.Print(feature.EvaluationDetails.Reason) } ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```go config := statsig.GetConfig(user, "awesome_product_details") // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. itemName := config.GetString("product_name", "Awesome Product v1"); double price = config.GetNumber("price", 10.0); bool shouldDiscount = config.GetBool("discount", false); // Or just get the whole json object backing this config if you prefer json := config.Value ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```go // Values via getLayer layer := Statsig.GetLayer(user, "user_promo_experiments"); promoTitle := layer.GetString("title", "Welcome to Statsig!"); discount := layer.GetDouble("discount", 0.1); // or, via getExperiment titleExperiment := Statsig.GetExperiment(user, "new_user_promo_title"); priceExperiment := Statsig.GetExperiment(user, "new_user_promo_price"); promoTitle := titleExperiment.GetString("title", "Welcome to Statsig!"); discount := priceExperiment.GetNumber("discount", 0.1); ... price := msrp * (1 - discount); // getting the layer name that an experiment belongs to userPromoLayer := Statsig.GetExperimentLayer("new_user_promo_title"); ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```go statsig.LogEvent(Event{ User: user, EventName: "add_to_cart", Value: "SKU_12345", Metadata: map[string]string{"price": "9.99","item_name": "diet_coke_48_pack"}, }) ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options `initialize()` takes an optional `options` parameter in addition to the secret key to customize the Statsig client. Specify optional parameters when initializing using `InitializeWithOptions()`: ```go type Options struct { API string `json:"api"` Environment Environment `json:"environment"` LocalMode bool `json:"localMode"` ConfigSyncInterval time.Duration IDListSyncInterval time.Duration BootstrapValues string RulesUpdatedCallback func(rules string, time int64) } ``` - **Environment**: default nil. An object used to set environment variables that apply to all users in the same session, for targeting purposes. The most common use is to set the environment tier (string) so feature gates pass or fail for specific environments. Accepted values are "production", "staging", and "development". - **LocalMode**: default false. Restricts the SDK to not issue any network requests and only respond with default values (or local overrides). - **ConfigSyncInterval**: default 10 seconds. The interval for polling gate/experiment/config changes. - **IDListSyncInterval**: default 1 minute. The interval for polling ID list changes. - **BootstrapValues**: default nil. A string representing all rules for all feature gates, dynamic configs, and experiments. Provide this to bootstrap the Statsig server SDK at initialization if your server encounters a network issue or Statsig servers are temporarily unavailable. - **RulesUpdatedCallback**: default nil. A callback invoked whenever the rulesets update. Called with a JSON string representing the rulesets and a timestamp for when the rules were updated. - **UserPersistentStorage**: IUserPersistentStorage, default nil. A persistent storage adapter for running sticky experiments. - **DisableIdList**: default false. Disables fetching the ID list during initialization and background polling for both network and data adapter. ### Client initialize response options When using `getClientInitializeResponse()`, you can specify additional options through the `GCIROptions` struct: ```go type GCIROptions struct { IncludeLocalOverrides bool ClientKey string TargetAppID string HashAlgorithm string IncludeConfigType bool ConfigTypesToInclude []ConfigType } ``` - **IncludeLocalOverrides**: default false. When set to true, the client initialize response includes local overrides. Useful for testing local configuration changes without affecting other users. - **ClientKey**: default empty string. The client SDK key for the initialize response. This key identifies the client application and determines which configurations it receives. Required when generating a client initialize response for client SDKs. - **TargetAppID**: default empty string. Filters configurations (feature gates, dynamic configs, experiments, and layers) to those targeted to this application ID. Useful in multi-tenant or multi-application environments. If not specified, the SDK attempts to determine the target app ID from the provided client key. - **HashAlgorithm**: default empty string. The hashing algorithm used to generate stable IDs in the client. Common values are "djb2" (default if not specified) and "sha256". This should match the hashing algorithm the client SDK uses. - **IncludeConfigType**: default false (deprecated). When set to true, the response includes the type of each configuration. This option is deprecated, and Statsig may remove it in a future version. - **ConfigTypesToInclude**: default empty array. An array of configuration types to include in the response. Possible values include FeatureGateType, DynamicConfigType, ExperimentType, and LayerType. If empty, the response includes all configuration types (subject to other filtering options). ## Shutdown To gracefully shutdown the SDK and flush all events: ```go statsig.Shutdown() ``` ## Local Overrides You can override the values the SDK returns for testing purposes, which is useful for local development when testing specific scenarios. ```go func OverrideGate(gate string, val bool) func OverrideConfig(config string, val map[string]interface{}) ``` ## Client SDK bootstrapping The Statsig server SDK can generate the initialization values for a client SDK. This is useful for server-side rendering (SSR) or when you want to pre-fetch values for a client. ```go user := statsig.User{UserID: "some_user_id"} options := statsig.GCIROptions{} options.ClientKey = "client-YOUR_CLIENT_KEY" result := statsig.GetClientInitializeResponseWithOptions(user, &options) // You can then pass 'result' into a Statsig Client SDK ``` ## Data Store A data store synchronizes configuration/value downloads across multiple SDK instances and bootstraps the SDK in offline environments. ### Interface ```go type IDataAdapter interface { /** * Returns the data stored for a specific key */ Get(key string) string /** * Updates data stored for each key */ Set(key string, value string) /** * Startup tasks to run before any get/set calls can be made */ Initialize() /** * Cleanup tasks to run when statsig is shutdown */ Shutdown() /** * Determines whether the SDK should poll for updates from * the data adapter (instead of Statsig network) for the given key */ ShouldBeUsedForQueryingUpdates(key string) bool } ``` ### Example Implementation ```go type dataAdapterExample struct { store map[string]string mu sync.RWMutex } func (d *dataAdapterExample) Get(key string) string { d.mu.RLock() defer d.mu.RUnlock() return d.store[key] } func (d *dataAdapterExample) Set(key string, value string) { d.mu.Lock() defer d.mu.Unlock() d.store[key] = value } func (d *dataAdapterExample) Initialize() {} func (d *dataAdapterExample) Shutdown() {} func (d *dataAdapterExample) ShouldBeUsedForQueryingUpdates(key string) bool { return false } ``` ## User persistent storage User Persistent Storage is a storage adapter for running sticky experiments that persists user assignments across sessions. ### Interface ```go type IUserPersistentStorage interface { /** * Returns the data stored for a specific key */ Load(key string) (string, bool) /** * Updates data stored for a specific key */ Save(key string, data string) } ``` ### Example Implementation ```go type userPersistentStorageExample struct { store map[string]string loadCalled int saveCalled int } func (d *userPersistentStorageExample) Load(key string) (string, bool) { d.loadCalled++ val, ok := d.store[key] return val, ok } func (d *userPersistentStorageExample) Save(key string, value string) { d.saveCalled++ d.store[key] = value } ``` ## Multi-instance usage To create multiple independent instances of the Statsig SDK (for example, to use different API keys or configurations), use the instance-based approach: ```go sdkInstance := NewClientWithOptions(sdkKey, &Options{}) ``` ## FAQ #### How do I run experiments for logged out users Refer to the guide on [device level experiments](https://docs.statsig.com/guides/first-device-level-experiment). #### How can I mock Statsig in tests Use the [Local Override](#local-overrides) APIs in v1.3.0+, in combination with the `LocalMode` option in `StatsigOptions`, to force gate/config values in test environments and remove network access to Statsig servers. For example: ```go c := NewClientWithOptions(secret, &Options{LocalMode: true}) user := User{ UserID: "123", } gateDefault := c.CheckGate(user, "any_gate") // "any_gate" is false by default c.OverrideGate("any_gate", true) // "any_gate" is now true ``` Refer to [https://github.com/statsig-io/go-sdk/blob/main/overrides\_test.go](https://github.com/statsig-io/go-sdk/blob/main/overrides_test.go) ## Reference ### StatsigUser ```go // User specific attributes for evaluating Feature Gates, Experiments, and DynamicConfigs // // Learn more why a UserID or a customID is required: /sdks/user#why-is-an-id-always-required-for-server-sdks // PrivateAttributes are only used for user targeting/grouping in feature gates, dynamic configs, // experiments and etc; they are omitted in logs. type User struct { UserID string `json:"userID"` Email string `json:"email,omitempty"` IpAddress string `json:"ip,omitempty"` // Many jurisdictions categorize this as PII; verify whether you should log this. UserAgent string `json:"userAgent,omitempty"` Country string `json:"country,omitempty"` Locale string `json:"locale,omitempty"` AppVersion string `json:"appVersion,omitempty"` Custom map[string]interface{} `json:"custom,omitempty"` PrivateAttributes map[string]interface{} `json:"privateAttributes,omitempty"` StatsigEnvironment map[string]string `json:"statsigEnvironment,omitempty"` CustomIDs map[string]string `json:"customIDs"` } ``` ### StatsigOptions ```go // Advanced options for configuring the Statsig SDK type Options struct { API string `json:"api"` APIOverrides APIOverrides `json:"api_overrides"` Environment Environment `json:"environment"` LocalMode bool `json:"localMode"` ConfigSyncInterval time.Duration IDListSyncInterval time.Duration LoggingInterval time.Duration LoggingMaxBufferSize int BootstrapValues string RulesUpdatedCallback func(rules string, time int64) InitTimeout time.Duration DataAdapter IDataAdapter OutputLoggerOptions OutputLoggerOptions StatsigLoggerOptions StatsigLoggerOptions EvaluationCallbacks EvaluationCallbacks DisableCDN bool // Disables use of CDN for downloading config specs UserPersistentStorage IUserPersistentStorage IPCountryOptions IPCountryOptions UAParserOptions UAParserOptions } type APIOverrides struct { DownloadConfigSpecs string `json:"download_config_specs"` GetIDLists string `json:"get_id_lists"` LogEvent string `json:"log_event"` } type EvaluationCallbacks struct { GateEvaluationCallback func(name string, result bool, exposure *ExposureEvent) ConfigEvaluationCallback func(name string, result DynamicConfig, exposure *ExposureEvent) ExperimentEvaluationCallback func(name string, result DynamicConfig, exposure *ExposureEvent) LayerEvaluationCallback func(name string, param string, result DynamicConfig, exposure *ExposureEvent) ExposureCallback func(name string, exposure *ExposureEvent) IncludeDisabledExposures bool } type OutputLoggerOptions struct { LogCallback func(message string, err error) EnableDebug bool DisableInitDiagnostics bool DisableSyncDiagnostics bool } type StatsigLoggerOptions struct { DisableInitDiagnostics bool DisableSyncDiagnostics bool DisableApiDiagnostics bool DisableAllLogging bool } type IPCountryOptions struct { Disabled bool // Fully disable IP to country lookup LazyLoad bool // Load in background EnsureLoaded bool // Wait until loaded when needed } type UAParserOptions struct { Disabled bool // Fully disable UA parser LazyLoad bool // Load in background EnsureLoaded bool // Wait until loaded when needed } // See /guides/using-environments type Environment struct { Tier string `json:"tier"` Params map[string]string `json:"params"` } // options for getClientInitializeResponse type GCIROptions struct { IncludeLocalOverrides bool ClientKey string HashAlgorithm string //supports "sha256", "djb2", "none", default "sha256" } ``` ### Event ```go type Event struct { EventName string `json:"eventName"` User User `json:"user"` Value string `json:"value"` Metadata map[string]string `json:"metadata"` Time int64 `json:"time"` } ``` ### FeatureGate ```go type FeatureGate struct { Name string `json:"name"` Value bool `json:"value"` RuleID string `json:"rule_id"` IDType string `json:"id_type"` GroupName string `json:"group_name"` EvaluationDetails *EvaluationDetails `json:"evaluation_details"` } ``` ### DynamicConfig ```go type DynamicConfig struct { Name string `json:"name"` Value map[string]interface{} `json:"value"` RuleID string `json:"rule_id"` IDType string `json:"id_type"` GroupName string `json:"group_name"` EvaluationDetails *EvaluationDetails `json:"evaluation_details"` AllocatedExperimentName string `json:"allocated_experiment_name"` GetString(key string, fallback string) string GetNumber(key string, fallback float64) float64 GetBool(key string, fallback bool) bool GetSlice(key string, fallback []interface{}) []interface{} GetMap(key string, fallback map[string]interface{}) map[string]interface{} } ``` ================================================================================ # Legacy Node.js Server SDK URL: https://docs.statsig.com/server/nodejsServerSDK ================================================================================ # Legacy Node.js Server SDK - **Package:** `statsig-node` ([npm](https://www.npmjs.com/package/statsig-node)) - **Latest version:** 6.5.2 - **Package size:** 287.0 kB gzip - **Repository:** [node-js-server-sdk](https://github.com/statsig-io/node-js-server-sdk) ## Setup the SDK 1. **Install the SDK** Statsig hosts the Node.js SDK on [npm](https://www.npmjs.com/package/statsig-node). You can install the SDK using NPM or Yarn: #### npm ```bash npm install statsig-node ``` #### yarn ```bash yarn add statsig-node ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. ```javascript const Statsig = require("statsig-node"); await Statsig.initialize( "server-secret-key", { environment: { tier: "staging" } } // optional, if not set, for >v6.0.0, sdk will default to be production ); ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```javascript const user = { userID: '12345', email: '12345@gmail.com', ... }; const showNewDesign = Statsig.checkGate(user, 'new_homepage_design'); if (showNewDesign) { // show new design here } else { // show old design here } ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```javascript const config = Statsig.getConfig(user, "awesome_product_details"); // The 2nd parameter is the default value to be used in case the given parameter name does not exist on // the Dynamic Config object. This can happen when there is a typo, or when the user is offline and the // value has not been cached on the client. const itemName = config.get("product_name", "Awesome Product v1"); const price = config.get("price", 10.0); const shouldDiscount = config.get("discount", false); ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```javascript // Values via getLayer const layer = Statsig.getLayer(user, "user_promo_experiments"); const promoTitle = layer.get("title", "Welcome to Statsig!"); const discount = layer.get("discount", 0.1); // or, via getExperiment const promoExperiment = Statsig.getExperiment(user, "new_user_promo"); const promoTitle = promoExperiment.get("title", "Welcome to Statsig!"); const discount = promoExperiment.get("discount", 0.1); ... const price = msrp * (1 - discount); ``` ## Retrieving Feature Gate Metadata When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata: ```javascript const gate = Statsig.getFeatureGate(user, 'new_homepage_design'); console.log(gate.name); // 'new_homepage_design' console.log(gate.value); // true or false console.log(gate.ruleID); // rule ID that was evaluated console.log(gate.evaluationDetails); // evaluation metadata ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```javascript Statsig.logEvent(user, "add_to_cart", "SKU_12345", { price: "9.99", item_name: "diet_coke_48_pack", }); ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options `initialize()` takes an optional `options` parameter in addition to the secret key to customize the Statsig client: | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | api | string | No | — | The base url to use for all network requests. Defaults to the statsig API. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environment | StatsigEnvironment | No | — | An object you can use to set environment variables that apply to all your users in the same session, for targeting purposes.The most common usage is to set the environment tier ('production', 'staging' or 'development'), e.g. `{ tier: 'staging' }`, and have feature gates pass/fail for specific environments. Since v6.0.0 the default environment tier is production. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | bootstrapValues | string | No | — | A string that represents all rules for all feature gates, dynamic configs and experiments. Provide it to bootstrap the Statsig server SDK at initialization in case your server runs into network issue or Statsig server is down temporarily. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | rulesUpdatedCallback | function | No | — | A callback function the SDK calls whenever the rules update. The SDK calls it with a JSON string (used as is for the `bootstrapValues` parameter) and a timestamp, like this:```plaintext options.rulesUpdatedCallback(specsString, timeStamp) ``` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | logger | LoggerInterface | No | — | The logger interface to use for printing to stdout/stderr | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | localMode | boolean | No | — | Disables all network access, so the SDK only returns default (or overridden) values. Useful in testing. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initTimeoutMs | number | No | — | Sets a maximum time to wait for the config download network request to resolve before considering the SDK initialized and resolving the call to `initialize()` | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dataAdapter | IDataAdapter | No | — | An adapter with custom storage behavior for config specs. Use it to bootstrap Statsig server (takes priority over `bootstrapValues`). You can also use it to continuously fetch updates in place of the Statsig network. Refer to [Data Stores](https://docs.statsig.com/server/concepts/data_store).For example, go to the 1P implementation using Redis [statsig-node-redis](https://github.com/statsig-io/node-js-server-sdk-redis). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | UserPersistentStorage | IUserPersistentStorage | No | — | A persistent storage adapter for running sticky experiments. Refer to [examples](https://docs.statsig.com/server/nodejsServerSDK#user-persistent-storage). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | rulesetsSyncIntervalMs | number | No | — | Sets the polling interval for the SDK to ask Statsig backend for changes on the rulesets. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | idListsSyncIntervalMs | number | No | — | Sets the polling interval for the SDK to ask Statsig backend for changes on the ID Lists. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingIntervalMs | number | No | — | Sets the interval for the SDK to periodically flush all logging events to Statsig backend. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | loggingMaxBufferSize | number | No | — | Sets the maximum number of events the SDK's logger batches before flushing them all to Statsig backend. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | disableDiagnostics | boolean | No | — | Disables diagnostics events from being logged and sent to Statsig | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initStrategyForIP3Country | 'await' | 'lazy' | 'none' | No | — | Method of initializing IP to country lookup on `statsig.initialize()`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initStrategyForIDLists | 'await' | 'lazy' | 'none' | No | — | Method of initializing ID lists on `statsig.initialize()`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | postLogsRetryLimit | number | No | — | The maximum number of retry attempts when sending `/log_event` requests to Statsig server | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | postLogsRetryBackoff | number | (retry: number) => number | No | — | A fixed number or callback on the retry attempt number to configure the time in ms to wait between each `/log_event` retry.If using a fixed number, a 10x multiplier applies on each subsequent retry. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | evaluationCallbacks | EvaluationCallbacks | No | — | Provides callback functions for handling custom logic during evaluations of gates, dynamic configs, experiments, or layers. You can provide specific callbacks for each evaluation type to perform tasks such as custom logging (if you prefer not to use Statsig's default logging), or side effects.To turn off Statsig's default logging, set `disableExposureLogging: true` when making checks.Available callbacks:```plaintext gateCallback?: (gate: FeatureGate, user: StatsigUser, event: LogEvent) => void; dynamicConfigCallback?: (config: DynamicConfig, user: StatsigUser, event: LogEvent) => void; experimentCallback?: (config: DynamicConfig, user: StatsigUser, event: LogEvent) => void; layerCallback?: (layer: Layer, user: StatsigUser) => void; layerParamCallback?: (layer: Layer, paramName: string, user: StatsigUser, event: LogEvent) => void; ``` | ## Shutdown To gracefully shutdown the SDK and flush all events: ```javascript statsig.shutdown(); ``` ## Flush To manually flush logged events: ```javascript await statsig.flush(); ``` ## Client SDK bootstrapping The Statsig server SDK can generate the initialization values for a client SDK. This is useful for server-side rendering (SSR) or when you want to pre-fetch values for a client. ```typescript const values = Statsig.getClientInitializeResponse(user); // Record<string, unknown> | null if (values != null) { // Bootstrap the Statsig React Client SDK return <StatsigSynchronousProvider initializeValues={values} ... />; } ``` ## Local Overrides You can override the values the SDK returns for testing purposes, which is useful for local development when testing specific scenarios. #### TypeScript ```typescript // Overrides the given gate to the specified value Statsig.overrideGate("a_gate_name", true, "a_user_id"); // Overrides the given config (dynamic config or experiment) to the provided value Statsig.overrideConfig("a_config_or_experiment_name", { key: "value" }, "a_user_id"); // Overrides the given layer to the provided value Statsig.overrideLayer("a_layer_name", { key: "value" }, "a_user_id"); ``` #### JavaScript ```javascript // Overrides the given gate to the specified value Statsig.overrideGate("a_gate_name", true, "a_user_id"); // Overrides the given config (dynamic config or experiment) to the provided value Statsig.overrideConfig("a_config_or_experiment_name", { key: "value" }, "a_user_id"); // Overrides the given layer to the provided value Statsig.overrideLayer("a_layer_name", { key: "value" }, "a_user_id"); ``` Use these to set an override for a specific user, or for all users (by not providing a specific user ID). Override experiments/Autotune with the `overrideConfig` API. ### Overriding in getClientInitializeResponse You can also override feature gates, dynamic configs, experiments, and layers when calling `getClientInitializeResponse`. This is useful when you need to provide specific values to the client SDK. #### TypeScript ```typescript // Get client initialize response with overrides const response = Statsig.getClientInitializeResponse(user, clientSDKKey, { overrides: { // Override feature gates featureGates: { 'my_gate': true, // Override gate value to true }, // Override dynamic configs and experiments dynamicConfigs: { // Override config value directly 'price_config': { value: { price: 9.99 } }, // Override experiment by setting the group assignment 'color_experiment': { groupName: 'Control' // Uses the value for the Control group }, // Override both value and group assignment 'spacing_experiment': { value: { spacing: 64 }, groupName: 'Variant_B' } }, // Override layers layers: { 'my_layer': { value: { param: 123 } } } } }); ``` #### JavaScript ```javascript // Get client initialize response with overrides const response = Statsig.getClientInitializeResponse(user, clientSDKKey, { overrides: { // Override feature gates featureGates: { 'my_gate': true, // Override gate value to true }, // Override dynamic configs and experiments dynamicConfigs: { // Override config value directly 'price_config': { value: { price: 9.99 } }, // Override experiment by setting the group assignment 'color_experiment': { groupName: 'Control' // Uses the value for the Control group }, // Override both value and group assignment 'spacing_experiment': { value: { spacing: 64 }, groupName: 'Variant_B' } }, // Override layers layers: { 'my_layer': { value: { param: 123 } } } } }); ``` For experiments, you can override them in two ways: 1. By setting a `value` override on their dynamic config to directly specify the parameter values 2. By setting the `groupName` assignment to use the value for that group name (e.g., "Control" or "Test") You can also combine both approaches to override both the group assignment and the parameter values. ## Manual Exposures Statsig SDKs automatically log an exposure event every time you check a gate/experiment/config. In some scenarios, you may want to control when to log an exposure. You can disable the automatic logging like this: ### Gates ```javascript const result = Statsig.checkGate(aUser, 'a_gate_name', {disableExposureLogging: true}); ``` Then, to manually log the exposure: ```javascript Statsig.manuallyLogGateExposure(aUser, 'a_gate_name'); ``` ### Dynamic Configs ```javascript const config = Statsig.getConfigWithExposureLoggingDisabledSync(aUser, 'a_dynamic_config_name'); ``` Then, to manually log the exposure: ```javascript Statsig.manuallyLogConfigExposure(aUser, 'a_dynamic_config_name'); ``` ### Experiments ```javascript const experiment = Statsig.getExperimentWithExposureLoggingDisabledSync(aUser, 'an_experiment_name'); ``` Then, to manually log the exposure: ```javascript Statsig.manuallyLogExperimentExposure(aUser, 'an_experiment_name'); ``` ### Layers ```javascript const layer = Statsig.getLayerWithExposureLoggingDisabledSync(aUser, 'a_layer_name'); const paramValue = layer.get('a_param_name', 'fallback_value'); ``` Then, to manually log the layer parameter exposure: ```javascript Statsig.manuallyLogLayerParameterExposure(aUser, 'a_layer_name', 'a_param_name'); ``` ## Cloudflare Workers setup ### Polling for updates The SDK can't poll for updates across requests since Cloudflare doesn't allow for timers. To solve for this, Statsig provides a manual sync API for independently updating the SDK internal store. ```javascript if (env.lastSyncTime < Date.now() - env.syncInterval) { env.lastSyncTime = Date.now(); context.waitUntil(Statsig.syncConfigSpecs()); } ``` ### Flushing events The SDK enqueues logged events and flushes them in batches. To ensure the SDK properly flushes events, call `flush` using [`context.waitUntil`](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/#contextwaituntil). This keeps the request handler alive until the SDK flushes events, without blocking the response. ```javascript context.waitUntil(Statsig.flush()); ``` ### Node.JS Compatibility You can access many native JavaScript API and Node standard libraries in Cloudflare through the [`nodejs_compat`](https://developers.cloudflare.com/workers/runtime-apis/nodejs/) compatibility flag. The SDK is now compatible with `nodejs_compat` (since v5.16.0). In older versions, you need manual polyfilling. ## User persistent storage User Persistent Storage is a storage adapter for running sticky experiments. It allows you to persist user assignments across sessions. ### Interface ```typescript export interface IUserPersistentStorage { /** * Returns the full map of persisted values for a specific user key * @param key user key */ load(key: string): UserPersistedValues; /** * Save the persisted values of a config given a specific user key * @param key user key * @param configName Name of the config/experiment * @param data Object representing the persistent assignment to store for the given user-config */ save(key: string, configName: string, data: StickyValues): void; /** * Delete the persisted values of a config given a specific user key * @param key user key * @param configName Name of the config/experiment */ delete(key: string, configName: string): void; } ``` ### Example Implementation ```typescript class UserPersistentStorageExample implements IUserPersistentStorage { public store: Record<string, UserPersistedValues> = {}; load(key: string): UserPersistedValues { return this.store[key]; } save(key: string, configName: string, data: StickyValues): void { if (!(key in this.store)) { this.store[key] = {}; } this.store[key][configName] = data; } delete(key: string, configName: string): void { delete this.store[key][configName]; } } ``` ## Multi-instance usage To create multiple independent instances of the Statsig SDK (for example, to use different API keys or configurations), use the instance-based approach: ```javascript // Statsig.initialize becomes: const sdkInstance = new StatsigServer(secretKey, options); await sdkInstance.initializeAsync(); ``` ## Forward proxy configuration You can configure the SDK to use a forward proxy for network requests: ```javascript const proxyAddress = "0.0.0.0:50051" const options = { proxyConfigs: { 'download_config_specs': { "proxyAddress": proxyAddress, "protocol": "grpc_websocket" as NetworkProtocol } } } await Statsig.initialize(secretKey, options) ``` ## FAQs ### How can I use the node SDK for server side rendering Refer to [Client SDK Bootstrapping | SSR](#bootstrap). ### How can I mock Statsig for testing Refer to [LocalOverrides](#local-overrides). ## Reference ### Type StatsigUser ```typescript export type StatsigUser = // at least one of userID or customIDs must be provided ({ userID: string } | { customIDs: Record<string, string> }) & { userID?: string; customIDs?: Record<string, string>; email?: string; ip?: string; userAgent?: string; country?: string; locale?: string; appVersion?: string; custom?: Record< string, string | number | boolean | Array<string> | undefined >; privateAttributes?: Record< string, string | number | boolean | Array<string> | undefined > | null; statsigEnvironment?: StatsigEnvironment; } ``` ### Type StatsigOptions ```typescript export type StatsigOptions = { api: string; apiForDownloadConfigSpecs: string; apiForGetIdLists: string; bootstrapValues: string | null; environment: StatsigEnvironment | null; rulesUpdatedCallback: RulesUpdatedCallback | null; logger: LoggerInterface; localMode: boolean; initTimeoutMs: number; dataAdapter: IDataAdapter | null; rulesetsSyncIntervalMs: number; idListsSyncIntervalMs: number; loggingIntervalMs: number; loggingMaxBufferSize: number; disableDiagnostics: boolean; initStrategyForIP3Country: InitStrategy; initStrategyForIDLists: InitStrategy; postLogsRetryLimit: number; postLogsRetryBackoff: RetryBackoffFunc | number; disableRulesetsSync: boolean; disableIdListsSync: boolean; disableAllLogging: boolean; }; export type RulesUpdatedCallback = (rulesJSON: string, time: number) => void; export type RetryBackoffFunc = (retriesRemaining: number) => number; export type StatsigEnvironment = { tier?: 'production' | 'staging' | 'development' | string; [key: string]: string | undefined; }; export type InitStrategy = 'await' | 'lazy' | 'none'; export interface LoggerInterface { debug?(message?: any, ...optionalParams: any[]): void; info?(message?: any, ...optionalParams: any[]): void; warn(message?: any, ...optionalParams: any[]): void; error(message?: any, ...optionalParams: any[]): void; logLevel: 'none' | 'debug' | 'info' | 'warn' | 'error'; } ``` ### Type FeatureGate ```typescript export type FeatureGate = { readonly name: string; readonly ruleID: string; readonly idType: string | null; readonly value: boolean; readonly evaluationDetails: EvaluationDetails | null; readonly groupName: null; // deprecated }; ``` ### Type DynamicConfig ```typescript export default class DynamicConfig { name: string; value: Record<string, unknown>; get<T>( key: string, defaultValue: T, typeGuard: ((value: unknown) => value is T | null) | null = null, ): T; getValue( key: string, defaultValue?: boolean | number | string | object | Array<any> | null, ): unknown | null; getRuleID(): string; getGroupName(): string | null; getIDType(): string | null; getEvaluationDetails(): EvaluationDetails | null; ``` ### Type Layer ```typescript export default class Layer { name: string; public get<T>( key: string, defaultValue: T, typeGuard: ((value: unknown) => value is T) | null = null, ): T; getValue( key: string, defaultValue?: boolean | number | string | object | Array<any> | null, ): unknown | null; getRuleID(): string; getGroupName(): string | null; getAllocatedExperimentName(): string | null; getEvaluationDetails(): EvaluationDetails | null; ``` ### DataAdapter ```typescript export interface IDataAdapter { get(key: string): Promise<AdapterResponse>; set(key: string, value: string, time?: number): Promise<void>; initialize(): Promise<void>; shutdown(): Promise<void>; supportsPollingUpdatesFor(key: DataAdapterKey): boolean; } ``` ### EvaluationDetails ```typescript export class EvaluationDetails { readonly configSyncTime: number; readonly initTime: number; readonly serverTime: number; readonly reason: EvaluationReason; } ``` ### EvaluationReason ```typescript export type EvaluationReason = | 'Network' | 'LocalOverride' | 'Unrecognized' | 'Uninitialized' | 'Bootstrap' | 'DataAdapter' | 'Unsupported'; ``` ================================================================================ # Legacy Python Server SDK URL: https://docs.statsig.com/server/pythonSDK ================================================================================ # Legacy Python Server SDK - **Package:** `statsig` ([pypi](https://pypi.org/project/statsig)) - **Latest version:** 0.72.1 - **Repository:** [python-sdk](https://github.com/statsig-io/python-sdk) ## Setup the SDK 1. **Install the SDK** Install the sdk using [pip3](https://pypi.org/project/statsig/): > **Note:** > > The Statsig SDK isn't compatible with python 2. You must be on python 3.7+ to use the Statsig SDK. ```bash pip3 install statsig ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. There's also an optional parameter named `options` that allows you to pass in a [StatsigOptions](#statsig-options) to customize the SDK. ```python from statsig import statsig statsig.initialize("server-secret-key") # or with StatsigOptions options = StatsigOptions(tier=StatsigEnvironmentTier.development) statsig.initialize("server-secret-key", options) # check if sdk is initialized initialized = statsig.is_initialized() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```python from statsig.statsig_user import StatsigUser ... statsig.check_gate(StatsigUser("user-id"), "gate-name") ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```python config = statsig.get_config(StatsigUser("user-id"), "config-name") config_json = config.get_value() ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```python # Values via getLayer layer = statsig.get_layer(user, "user_promo_experiments") title = layer.get("title", "Welcome to Statsig!") discount = layer.get("discount", 0.1) # or, via getExperiment title_exp = statsig.get_experiment(user, "new_user_promo_title") price_exp = statsig.get_experiment(user, "new_user_promo_price") title = title_exp.get("title", "Welcome to Statsig!") discount = price_exp.get("discount", 0.1) ... price = msrp * (1 - discount) ``` ## Retrieving Feature Gate Metadata When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata: ```python gate = statsig.get_feature_gate(StatsigUser("user-id"), "gate-name") print(gate.name) # 'gate-name' print(gate.value) # True or False print(gate.rule_id) # rule ID that was evaluated print(gate.evaluation_details) # evaluation metadata ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```python from statsig.statsig_user import StatsigUser from statsig.statsig_event import StatsigEvent statsig.log_event(StatsigEvent(StatsigUser("user-id"), "event-name")) ``` Python supports `retry_queue_size`, which allows you to adjust the memory allocated for handling retries. While service outages are rare, increasing the retry\_queue\_size can help minimize event loss by providing additional memory to buffer events during outages. You generally don't need this option for typical use, but it offers added flexibility in exceptional situations. ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Statsig Options `initialize()` takes an optional `options` parameter in addition to the secret key to customize the Statsig client. Create a `StatsigOptions` class with the following available parameters: (unit of measure for time related options is seconds) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | tier | StatsigEnvironmentTier | str | No | — | Sets the environment tier (for gates to evaluate differently in development and production)Set the environment tier using the `StatsigEnvironmentTier` enum or as a `str`. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | timeout | int | No | — | Enforces a minimum timeout on network requests from the SDK | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | init_timeout | int | No | — | Sets the maximum timeout on download config specs and id lists network requests for initialization | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | rulesets_sync_interval | int | No | — | How often the SDK updates rulesets from Statsig servers | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | idlists_sync_interval | int | No | — | How often the SDK updates idlists from Statsig servers | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | local_mode | bool | No | — | Disables all network requests. SDK returns default values and doesn't log events. Useful in combination with overrides to mock behavior for tests. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | bootstrap_values | str | No | — | a string that represents all rules for all feature gates, dynamic configs and experiments. Provide it to bootstrap the Statsig server SDK at initialization in case your server runs into network issue or Statsig server is down temporarily. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | rules_updated_callback | typing.Callable | No | — | a callback function the SDK calls whenever the rules update. The SDK calls it with a logical timestamp and a JSON string (used as is for the bootstrapValues parameter). As of v0.6.0, the SDK calls this from a background thread that it uses to update config values. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | event_queue_size | int | No | — | The number of events to batch before flushing the queue to the network. Default 500.A background thread also batches events every minute | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | data_store | IDataStore | No | — | A data store with custom storage behavior for config specs. Use it to bootstrap Statsig server (takes priority over `bootstrap_values`). | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | proxy_configs | Optional[Dict[NetworkEndpoint, ProxyConfig]] | No | — | Configuration network for each endpoint, for example, download\_config\_spec, get\_id\_lists | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fallback_to_statsig_api | Optional[bool] | No | — | Fallback to Statsig CDN for download config specs and get id lists if the overridden api failed. | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | initialize_sources | Optional[List[DataSource]] | No | — | List of sources SDK tries to get download\_config\_specs from when initialize. The list is ordered, SDK tries to get source from first element, and stops when getting dcs successfully | | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | config_sync_sources | Optional[List[DataSource]] | No | — | List of sources SDK tries to get download\_config\_specs from when downloading. The list is ordered, SDK tries to get source from first element, and stops when getting dcs successfully | Example: ```python from statsig import statsig, StatsigEnvironmentTier, StatsigOptions options = StatsigOptions(None, StatsigEnvironmentTier.development) statsig.initialize("secret-key", options).wait() ``` You can also use the `set_environment_parameter` function, but that takes in string values only: ```python from statsig import statsig, StatsigEnvironmentTier, StatsigOptions options = StatsigOptions() options.set_environment_parameter("tier", StatsigEnvironmentTier.development.value) statsig.initialize("secret-key", options).wait() ``` ## Shutdown To gracefully shutdown the SDK and flush all events: ```python statsig.shutdown() ``` ## Client SDK bootstrapping The Statsig server SDK can generate the initialization values for a client SDK. This is useful for server-side rendering (SSR) or when you want to pre-fetch values for a client. ```python values = statsig.get_client_initialize_response(user); # dict() | None # To apply local overrides, set include_local_overrides = True (python sdk v0.32.0+) values = statsig.get_client_initialize_response(user=user, include_local_overrides=True); # dict() | None ``` ## Local Overrides You can override the values the SDK returns for testing purposes, which is useful for local development when testing specific scenarios. ```python # Adding/Removing gate overrides statsig.override_gate("a_gate_name", true, "a_user_id") statsig.remove_gate_override("a_gate_name", "a_user_id") # Adding/Removing config overrides statsig.override_config("a_config_name", {"key": "value"}, "a_user_id") statsig.remove_config_override("a_config_name", "a_user_id") # Adding/Removing experiment overrides statsig.override_experiment("an_experiment_name", {"key": "value"}, "a_user_id") statsig.remove_experiment_override("an_experiment_name", "a_user_id") # Remove All Overrides statsig.remove_all_overrides() # You can also override with custom ids custom_id_user = StatsigUser("a_user_id", custom_ids={"statsigId": "a_statsig_id"}) statsig.override_gate("a_gate_name", true, "a_statsig_id") # Local overrides will prioritize override with userId, then look up the custom id to override. # To prevent clashing overrides, it is recommended to not use the same value for userId and customIds for different users. ``` ## Multi-instance usage To create multiple independent instances of the Statsig SDK (for example, to use different API keys or configurations), use the instance-based approach: ```python sdk_instance = StatsigServer() sdk_instance.initialize(secret_key, options); ``` ## Forward proxy configuration You can configure the SDK to use a forward proxy for network requests: Basic setup to stream download config spec from forward proxy: ```python proxyAddress = "0.0.0.0:50051" // local address update to your address Statsig.initialize(secret_key, StatsigOptions(proxy_configs={ NetworkEndpoint.DOWNLOAD_CONFIG_SPECS: ProxyConfig(NetworkProtocol.GRPC_WEBSOCKET, proxyAddress)})) ``` When the SDK disconnects from the forward proxy when using grpc\_websocket, the SDK retries the connection with exponential backoff. After `push_worker_failover_threshold` retries, the SDK starts polling from Statsig until it reconnects to the forward proxy. You can customize Streaming Failover Behavior. You can also define the sources/endpoints SDK poll from, SDK tries from source at index 0, and stops trying if get a response. ```python statsigOptions = StatsigOptions( proxy_configs={ NetworkEndpoint.DOWNLOAD_CONFIG_SPECS: ProxyConfig( protocol=NetworkProtocol.GRPC_WEBSOCKET, proxy_address=address, push_worker_failover_threshold=1, # start polling from Statsig endpoint after 1 retry failed # 1st retry 5000 ms later, 2nd retry 2 * 5000ms = 10 seconds .... retry_backoff_multiplier=2, max_retry_attempt=8, retry_backoff_base_ms=5000 ) }, # Get from network first, which is forward proxy here, if fails, try datastore, if fails try poll from Statsig endpoint initialize_sources=[ DataSource.NETWORK, DataSource.DATASTORE, DataSource.STATSIG_NETWORK, ], ) ``` ## FAQs ### How can I mock Statsig for testing The python server SDK, starting in version 0.5.1+, supports a few features to make testing easier. The `StatsigOptions` parameter `localMode`, when set to true, prevents the SDK from making network requests and causes it to return only default values. This is useful for placeholder or test environments that shouldn't access the network. The `overrideGate` and `overrideConfig` APIs on the global `statsig` interface (refer to [Local Overrides](#local-overrides)) can set a gate or config override for a specific user, or for all users (by not providing a specific user ID). Enable `localMode` and then override gates/configs/experiments to specific values to test the code flows you're building. ### Can I generate the initialize response for a client SDK using the Python server SDK Yes. Refer to [Client Initialize Response](#bootstrap). ## Reference ### StatsigUser ```python @dataclass class StatsigUser: """An object of properties relating to the current user user_id or customID is required: /sdks/user#why-is-an-id-always-required-for-server-sdks Provide as many as possible to take advantage of advanced conditions in the statsig console A dictionary of additional fields can be provided under the custom field Set private_attributes for any user property you need for gate evaluation but prefer stripped from logs/metrics """ user_id: Optional[str] = None email: Optional[str] = None ip: Optional[str] = None user_agent: Optional[str] = None country: Optional[str] = None locale: Optional[str] = None app_version: Optional[str] = None custom: Optional[dict] = None # key: string, value: string private_attributes: Optional[dict] = None # key: string, value: string custom_ids: Optional[dict] = None # key: string, value: string ``` ### StatsigOptions ```python class StatsigOptions: """An object of properties for initializing the sdk with additional parameters""" def __init__( self, api: Optional[str] = None, api_for_download_config_specs: Optional[str] = None, api_for_get_id_lists: Optional[str] = None, api_for_log_event: Optional[str] = None, tier: Union[str, StatsigEnvironmentTier, None] = None, init_timeout: Optional[int] = None, timeout: Optional[int] = None, rulesets_sync_interval: int = DEFAULT_RULESET_SYNC_INTERVAL, idlists_sync_interval: int = DEFAULT_IDLIST_SYNC_INTERVAL, local_mode: bool = False, bootstrap_values: Optional[str] = None, rules_updated_callback: Optional[Callable] = None, event_queue_size: Optional[int] = DEFAULT_EVENT_QUEUE_SIZE, data_store: Optional[IDataStore] = None, idlists_thread_limit: int = DEFAULT_IDLISTS_THREAD_LIMIT, logging_interval: int = DEFAULT_LOGGING_INTERVAL, #deprecated disable_diagnostics: bool = False, custom_logger: Optional[OutputLogger] = None, enable_debug_logs = False, disable_all_logging = False, evaluation_callback: Optional[Callable[[Union[Layer, DynamicConfig, FeatureGate]], None]] = None, retry_queue_size: int = DEFAULT_RETRY_QUEUE_SIZE, proxy_configs: Optional[Dict[NetworkEndpoint, ProxyConfig]] = None, fallback_to_statsig_api: Optional[bool] = False, initialize_sources: Optional[List[DataSource]] = None, config_sync_sources: Optional[List[DataSource]] = None, ): ``` ### FeatureGate ```python class FeatureGate: def get_value(self): """Returns the underlying value of this FeatureGate""" def get_name(self): """Returns the name of this FeatureGate""" def get_evaluation_details(self): """Returns the evaluation detail of this FeatureGate""" ``` ### DynamicConfig ```python class DynamicConfig: def get(self, key, default=None): """Returns the value of the config at the given key or the provided default if the key is not found """ def get_typed(self, key, default=None): """Returns the value of the config at the given key iff the type matches the type of the provided default. Otherwise, returns the default value """ def get_value(self): """Returns the underlying value of this DynamicConfig""" def get_name(self): """Returns the name of this DynamicConfig""" def get_evaluation_details(self): """Returns the evaluation detail of this DynamicConfig""" ``` ### Layer ```python class Layer: def get(self, key, default=None): """Returns the value of the layer at the given key or the provided default if the key is not found """ def get_typed(self, key, default=None): """Returns the value of the layer at the given key iff the type matches the type of the provided default. Otherwise, returns the default value """ def get_name(self): """Returns the name of this Layer""" def get_values(self): """Returns all the values in this Layer but does not trigger an exposure log""" def get_evaluation_details(self): """Returns the evaluation detail of this Layer""" ``` ### EvaluationDetails ```python class EvaluationDetails: reason: EvaluationReason config_sync_time: int init_time: int server_time: int class EvaluationReason(str, Enum): network = "Network" local_override = "LocalOverride" unrecognized = "Unrecognized" uninitialized = "Uninitialized" bootstrap = "Bootstrap" data_adapter = "DataAdapter" unsupported = "Unsupported" error = "error" ``` ### DataStore ```python class IDataStore: def get(self, key: str) -> Optional[str]: return None def set(self, key: str, value: str): pass def shutdown(self): pass def should_be_used_for_querying_updates(self, key: str) -> bool: return False ``` ### ForwardProxy - ProxyConfig ```python class NetworkProtocol(Enum): HTTP = "http" GRPC = "grpc" GRPC_WEBSOCKET = "grpc_websocket" class NetworkEndpoint(Enum): LOG_EVENT = "log_event" DOWNLOAD_CONFIG_SPECS = "download_config_specs" GET_ID_LISTS = "get_id_lists" ALL = "all" class ProxyConfig: def __init__( self, protocol: NetworkProtocol, proxy_address: str, # Websocket worker failover config max_retry_attempt: Optional[int] = None, # default is 10 retry_backoff_multiplier: Optional[int] = None, # default is # default is 5 retry_backoff_base_ms: Optional[int] = None, # default is 10,000 ms # Push worker failback to polling threshold, fallback immediate set 0, # n means fallback after n retry failed push_worker_failover_threshold: Optional[int] = None, # default is 4, about 30 minutes ): self.proxy_address = proxy_address self.protocol = protocol self.max_retry_attempt = max_retry_attempt self.retry_backoff_multiplier = retry_backoff_multiplier self.retry_backoff_base_ms = retry_backoff_base_ms self.push_worker_failover_threshold = push_worker_failover_threshold ``` ================================================================================ # Legacy Erlang/Elixir Server SDK URL: https://docs.statsig.com/server/erlang ================================================================================ # Legacy Erlang/Elixir Server SDK - **Package:** `statsig` ([hex](https://hex.pm/packages/statsig)) - **Latest version:** 0.0.3 - **Repository:** [erlang-sdk](https://github.com/statsig-io/erlang-sdk) > **Warning:** > > Support for the Legacy Erlang SDK ends April 30, 2026. Migrate to the > > [new Elixir SDK](https://docs.statsig.com/server-core/elixir-core) > > soon. > **Warning:** > > The erlang SDK repository, and this docs site, are a work in progress. If you're trying to use Statsig in erlang or elixir, reach out to the support team, your sales contact, or in the [Slack community](https://statsig.com/slack). ## Setup the SDK 1. **Install the SDK** Add a dependency on statsig to your: **mix.exs**: ```elixir {:statsig, "~> 0.0.1"} ``` **rebar.config**: ```erlang {statsig, "0.0.1"}. ``` **erlang.mk**: ```makefile dep_statsig = hex 0.0.1 ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console. #### Erlang ```erlang statsig:initialize(<<"secret-key">>). % or with options Options = #{environment => #{tier => <<"staging">>}}, statsig:initialize(<<"secret-key">>, Options). ``` #### Elixir ```elixir Statsig.initialize("secret-key") # or with options options = %{environment: %{tier: "staging"}} Statsig.initialize("secret-key", options) ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: #### Erlang ```erlang User = #{<<"userID">> => <<"user-id">>}, GateValue = statsig:check_gate(User, <<"gate_name">>). ``` #### Elixir ```elixir user = %{"userID" => "user-id"} gate_value = Statsig.check_gate(user, "gate_name") ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. #### Erlang ```erlang Config = statsig:get_config(User, <<"config_name">>), Value = statsig_config:get(Config, <<"param">>, <<"default">>). ``` #### Elixir ```elixir config = Statsig.get_config(user, "config_name") value = StatsigConfig.get(config, "param", "default") ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. #### Erlang ```erlang Layer = statsig:get_layer(User, <<"layer_name">>), ParamValue = statsig_layer:get(Layer, <<"param">>, <<"default">>). ``` #### Elixir ```elixir layer = Statsig.get_layer(user, "layer_name") param_value = StatsigLayer.get(layer, "param", "default") ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: #### Erlang ```erlang statsig:log_event(User, <<"event_name">>). ``` #### Elixir ```elixir Statsig.log_event(user, "event_name") ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Shutdown To gracefully shutdown the SDK and flush all events: #### Erlang ```erlang statsig:shutdown(). ``` #### Elixir ```elixir Statsig.shutdown() ``` ================================================================================ # Legacy Java/Kotlin Server SDK URL: https://docs.statsig.com/server/java ================================================================================ # Legacy Java/Kotlin Server SDK - **Package:** `com.statsig:serversdk` ([maven](https://search.maven.org/artifact/com.statsig/serversdk)) - **Latest version:** 3.2.0 - **Repository:** [java-server-sdk](https://github.com/statsig-io/java-server-sdk) > **Note:** > > These docs cover the Java/Kotlin SDK in a multi-user, server-side context. For client-side Android applications, go to the [Android SDK](https://docs.statsig.com/client/Android) or one of the other client SDKs for your client-side applications. Statsig wrote this SDK in Kotlin, but it exposes methods and overrides to Java based applications. ## Setup the SDK 1. **Install the SDK** Statsig now publishes `v1.X.X+` of the SDK only to Maven Central. To install the SDK, set the Maven Central repository in your `build.gradle`. You probably already have this for other dependencies. ```groovy repositories { mavenCentral() } ``` Then add the dependency: ```groovy implementation 'com.statsig:serversdk:1.X.X' // replace with the most up to date version // For >v1.24.0 If you are not using streaming and want to reduce the package size you can: implementation 'com.statsig:serversdk:1.X.X' { exclude(group = "io.grpc", module = "*") } ``` You can find the versions in the github releases of the [open source sdk repository](https://github.com/statsig-io/java-server-sdk/releases), or from the [maven central repository](https://mvnrepository.com/artifact/com.statsig/serversdk). ### Jitpack deprecation jitpack provides `v0.X.X` versions of the SDK, but Statsig won't publish newer versions to jitpack. > **Note:** > > If you update Statsig to be pulled from Maven Central instead of jitpack, you can remove `maven { url 'https://jitpack.io' }` if Statsig was the only library you got from jitpack and you previously relied on v0.X.X of the SDK. 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. #### Java ```java import com.statsig.sdk.Statsig; StatsigOptions options = new StatsigOptions(); // Customize options as needed. For example: // options.initTimeoutMs = 9999; Future initFuture = Statsig.initializeAsync("server-secret-key", options); initFuture.get(); ``` #### Kotlin ```kotlin import com.statsig.sdk.Statsig val options = StatsigOptions().apply { // Customize options as needed. For example: initTimeoutMs = 9999 } async { Statsig.initialize("server-secret-key", options) }.await() ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: #### Java ```java StatsigUser user = new StatsigUser("user_id"); Boolean isFeatureOn = Statsig.checkGateSync(user, "use_new_feature"); if (isFeatureOn) { // Gate is on, use new feature } else { // Gate is off } ``` #### Kotlin ```kotlin val user = StatsigUser("user_id"); val featureOn = Statsig.checkGateSync(user, "use_new_feature") if (featureOn) { // Gate is on, use new feature } else { // Gate is off } ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. #### Java ```java DynamicConfig config = Statsig.getConfigSync(user, "awesome_product_details"); String itemName = config.getString("product_name", "Awesome Product v1"); double price = config.getDouble("price", 10.0); ``` #### Kotlin ```kotlin val config = Statsig.getConfigSync(user, "awesome_product_details") val itemName = config.getString("product_name", "Awesome Product v1") val price = config.getDouble("price", 10.0) ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. #### Java ```java // Values via getLayer Layer layer = Statsig.getLayerSync(user, "user_promo_experiments"); String title = layer.getString("title", "Welcome to Statsig!"); double discount = layer.getDouble("discount", 0.1); // or, via getExperiment DynamicConfig experiment = Statsig.getExperimentSync(user, "new_user_promo"); String expTitle = experiment.getString("title", "Welcome to Statsig!"); double expDiscount = experiment.getDouble("discount", 0.1); ``` #### Kotlin ```kotlin // Values via getLayer val layer = Statsig.getLayerSync(user, "user_promo_experiments") val title = layer.getString("title", "Welcome to Statsig!") val discount = layer.getDouble("discount", 0.1) // or, via getExperiment val experiment = Statsig.getExperimentSync(user, "new_user_promo") val expTitle = experiment.getString("title", "Welcome to Statsig!") val expDiscount = experiment.getDouble("discount", 0.1) ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: #### Java ```java Statsig.logEvent(user, "add_to_cart", "SKU_12345", Map.of("price", "9.99", "item_name", "diet_coke_48_pack")); ``` #### Kotlin ```kotlin Statsig.logEvent(user, "add_to_cart", "SKU_12345", mapOf("price" to "9.99", "item_name" to "diet_coke_48_pack")) ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Retrieving Feature Gate Metadata When you need more than a boolean value from a gate evaluation, use the Get Feature Gate API, which returns a FeatureGate object with additional evaluation metadata: #### Java ```java FeatureGate gate = Statsig.getFeatureGateSync(user, "use_new_feature"); boolean value = gate.getValue(); String ruleId = gate.getRuleID(); EvaluationDetails details = gate.getEvaluationDetails(); ``` #### Kotlin ```kotlin val gate = Statsig.getFeatureGateSync(user, "use_new_feature") val value = gate.getValue() val ruleId = gate.getRuleID() val details = gate.getEvaluationDetails() ``` ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Shutdown To gracefully shutdown the SDK and flush all events: #### Java ```java Statsig.shutdown(); ``` #### Kotlin ```kotlin Statsig.shutdown() ``` ================================================================================ # Legacy Rust Server SDK URL: https://docs.statsig.com/server/rust ================================================================================ # Legacy Rust Server SDK - **Package:** `statsig` ([crates](https://crates.io/crates/statsig)) - **Latest version:** 1.4.0 - **Repository:** [rust-sdk](https://github.com/statsig-io/rust-sdk) > **Warning:** > > Support for the Legacy Rust SDK ends April 30, 2026. Migrate to the > > [new Rust SDK](https://docs.statsig.com/server-core/rust-core) > > soon. ## Setup the SDK 1. **Install the SDK** To use the SDK, add `statsig` as a dependency in your `Cargo.toml`. You can find the latest version at [crates.io/crates/statsig](https://crates.io/crates/statsig). ```toml [dependencies] statsig = "X.Y.Z" # <- update version ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. ```rust use statsig::{Statsig}; Statsig::initialize("secret-key").await; // or with StatsigOptions use statsig::{Statsig, StatsigOptions}; let env = HashMap::from([("tier".to_string(), "staging".to_string())]); let opts = StatsigOptions { environment: Some(env), ..StatsigOptions::default() }; Statsig::initialize_with_options("secret-key", opts).await; ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```rust let user = StatsigUser::with_user_id("a-user".to_string()); if Statsig::check_gate(&user, "a_gate").ok().unwrap_or(false) { // Gate is on, enable new feature } else { // Gate is off } ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```rust let config = Statsig::get_config(&user, "a_config").ok().unwrap(); let value = config.get_string("a_key", "default_value"); ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```rust let layer = Statsig::get_layer(&user, "a_layer").ok().unwrap(); let param_value = layer.get_string("a_parameter", "default_value"); // or via get_experiment let experiment = Statsig::get_experiment(&user, "an_experiment").ok().unwrap(); let exp_value = experiment.get_string("a_parameter", "default_value"); ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```rust let event = StatsigEvent::new("event_name".to_string()); Statsig::log_event(&user, event); ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Shutdown To gracefully shutdown the SDK and flush all events: ```rust Statsig::shutdown().await; ``` ================================================================================ # Legacy PHP Server SDK URL: https://docs.statsig.com/server/php ================================================================================ # Legacy PHP Server SDK - **Package:** `statsig/statsigsdk` ([composer](https://packagist.org/packages/statsig/statsigsdk)) - **Latest version:** 3.7.2 - **Repository:** [php-sdk](https://github.com/statsig-io/php-sdk) ## Setup the SDK 1. **Install the SDK** You can install the PHP SDK using composer. ```bash composer require statsig/statsigsdk ``` The SDK is also [open source and hosted on github](https://github.com/statsig-io/php-sdk). Statsig publishes the package to [packagist](https://packagist.org/packages/statsig/statsigsdk). To successfully use the PHP SDK, you need to: 1. Install it 2. Provide a storage adapter to cache config and event logs (easy default exists) 3. Schedule a Cron job to poll for config changes and flush event logs to Statsig 4. Initialize and use the SDK 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. However, if you accidentally expose it, you can create a new one in the Statsig console. The `options` parameter requires a storage adapter for storing configurations and event logs. The example below uses a local file storage adapter, but you can write your own to connect Redis or another storage solution. Create an adapter that implements `Statsig\Adapters\IConfigAdapter` connected to your caching solution. By default, the SDK provides a local file solution, which is useful for initial setup but isn't suitable for production settings. For help with the interface and implementing an adapter, browse the [adapters directory](https://github.com/statsig-io/php-sdk/tree/main/src/Adapters) in the open source SDK repository. ```php require_once __DIR__ . '/vendor/autoload.php'; // path to installation folder use Statsig\StatsigServer; use Statsig\StatsigOptions; use Statsig\Adapters\LocalFileDataAdapter; use Statsig\Adapters\LocalFileLoggingAdapter; $config_adapter = new LocalFileDataAdapter(); $logging_adapter = new LocalFileLoggingAdapter(); $options = new StatsigOptions($config_adapter, $logging_adapter); $this->statsig = new StatsigServer("server-sdk-key", $options); ``` ### 🔥 Warning - You need to schedule a job 🔥 > **Warning:** > > #### V3.0+ > > If you don't configure a job to update the config values, the SDK doesn't fire a network request to fetch the latest config value anymore, and instead uses config values fetched earlier. Refer to [Cron Jobs](#cron-jobs). ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```php use Statsig\StatsigUser; $user = StatsigUser::withUserID("123"); $user->setEmail("testuser@statsig.com"); $this->statsig->checkGate($user, "<gate_name>"); ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```php $this->statsig->getConfig($user, "<config_name>"); ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```php // Values via getLayer $layer = $this->statsig->getLayer($user, "user_promo_experiments"); $title = $layer->get("title", "Welcome to Statsig!"); $discount = $layer->get("discount", 0.1); // or, via getExperiment $title_experiment = $this->statsig->getExperiment($user, "new_user_promo_title"); $price_experiment = $this->statsig->getExperiment($user, "new_user_promo_price"); $title = $title_experiment->get("title", "Welcome to Statsig!") $discount = $price_experiment->get("discount", 0.1) ... $price = $msrp * (1 - $discount) ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```php $event = new StatsigEvent("purchase"); $event->setUser($user); $event->setValue("subscription"); $event->setMetadata(array("promotion" => "2022 deals")); $this->statsig->logEvent($event); ``` At the end of the request, you can flush events to the log file using: ```php $this->statsig->flush(); ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Cron jobs To keep your configurations up to date and send event data to Statsig, create two jobs. This guide documents these as cron jobs, but you can use any out-of-band process. If you're using Laravel, you can use Commands to run them locally and on a schedule. ### Sync The first job runs `sync.php` to download the latest definition of gates/configs/experiments from Statsig and save it to a local config file. If the job doesn't update this file, gate/config/experiment values may be stale. The SDK refetches stale values during a request, which can cause slower response times. ```bash # Run once php sync.php --secret <STATSIG_SECRET_KEY> ``` ```bash # Create a cron job that runs as statsigsync every minute echo '*/1 * * * * statsigsync php /my/path/to/statsig/sync.php --secret <STATSIG_SECRET_KEY> > /dev/null' | sudo tee /etc/cron.d/statsigsync sudo service cron reload # reload the cron daemon ``` You should provide your own custom adapter that implements Statsig\\Adapters\\IDataAdapter ```bash php send.php --secret <STATSIG_SECRET_KEY> \ --adapter-class Namespace\For\MyConfigAdapter \ --adapter-path /path/to/MyConfigAdapter.php \ --adapter-arg an_argument_for_my_adapter \ --adapter-arg another_argument ``` By default, sync.php uses the Statsig LocalFileDataAdapter which writes to /tmp/statsig.configs. ### Send The second job runs `send.php` to send exposure data and log events to Statsig. Without this, the SDK logs events during the lifetime of the request, which can cause slower response times. ```bash # Run once php send.php --secret <STATSIG_SECRET_KEY> ``` ```bash # Create a cron job that runs as statsigdata every minute echo '*/1 * * * * statsigdata php /my/path/to/statsig/send.php --secret <STATSIG_SECRET_KEY> > /dev/null' | sudo tee /etc/cron.d/statsigdata sudo service cron reload # reload the cron daemon ``` You should provide your own custom adapter that implements Statsig\\Adapters\\ILoggingAdapter ```bash php send.php --secret <STATSIG_SECRET_KEY> \ --adapter-class Namespace\For\MyLoggingAdapter \ --adapter-path /path/to/MyLoggingAdapter.php \ --adapter-arg an_argument_for_my_adapter \ --adapter-arg another_argument ``` By default, send.php uses the Statsig LocalFileDataAdapter which writes to /tmp/statsig.logs. ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ================================================================================ # Legacy .NET Server SDK URL: https://docs.statsig.com/server/dotnet ================================================================================ # Legacy .NET Server SDK - **Repository:** [dotnet-sdk](https://github.com/statsig-io/dotnet-sdk) ## Setup the SDK 1. **Install the SDK** The package is hosted on [Nuget](https://www.nuget.org/packages/Statsig/). Install it through Visual Studio's Nuget package manager or through the NuGet CLI: ```bash nuget install Statsig ``` 2. **Initialize the SDK** After installation, initialize the SDK using a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Don't embed your Server Secret Key in client-side applications, or expose it in any external-facing documents. If you accidentally expose it, you can create a new one in the Statsig console. ```csharp using Statsig; using Statsig.Server; await StatsigServer.Initialize( "server-secret-key", // optionally customize the SDKs configuration via StatsigOptions new StatsigOptions( environment: new StatsigEnvironment(EnvironmentTier.Development) ) ); ``` `initialize` performs a network request. After `initialize` completes, virtually all SDK operations are synchronous (refer to [Evaluating Feature Gates in the Statsig SDK](https://blog.statsig.com/evaluating-feature-gates-in-the-statsig-sdk-a6f8881a1ad8)). The SDK fetches updates from Statsig in the background, independently of API calls. ## Working with the SDK ## Checking a Feature Flag/Gate After you initialize the SDK, you can check a [**Feature Gate**](https://docs.statsig.com/feature-flags/overview). Feature Gates create logic branches in code that you can roll out to different users from the Statsig Console. Gates are always **CLOSED** or **OFF** (`return false;`) by default. All APIs require you to specify the user (refer to [Statsig user](#statsig-user)) associated with the request. For example, to check a gate for a user: ```csharp var user = new StatsigUser { UserID = "some_user_id", Email = "user@email.com" }; var useNewFeature = await StatsigServer.CheckGate(user, "use_new_feature"); if (useNewFeature) { // Gate is on, enable new feature } else { // Gate is off } ``` ## Reading a Dynamic Config Feature Gates work well for simple on/off switches with optional user targeting. To send a different set of values (strings, numbers, and so on) to clients based on specific user attributes such as country, use [**Dynamic Configs**](https://docs.statsig.com/dynamic-config/overview). The Dynamic Config API is similar to Feature Gates, but returns a full JSON object configured on the server, from which you can fetch typed parameters. ```csharp var config = await StatsigServer.GetConfig(user, "awesome_product_details"); var itemName = config.Get<string>("product_name", "Awesome Product v1"); var price = config.Get<double>("price", 10.0); ``` ## Getting a Layer/Experiment Use **Layers/Experiments** to run A/B/n experiments. Two APIs are available, but Statsig recommends [layers](https://docs.statsig.com/experiments/layers-overview) for faster iterations with parameter reuse. ```csharp // Values via GetLayer var layer = await StatsigServer.GetLayer(user, "user_promo_experiments"); var title = layer.Get<string>("title", "Welcome to Statsig!"); var discount = layer.Get<double>("discount", 0.1); // or, via GetExperiment var experiment = await StatsigServer.GetExperiment(user, "new_user_promo"); var expTitle = experiment.Get<string>("title", "Welcome to Statsig!"); var expDiscount = experiment.Get<double>("discount", 0.1); var price = msrp * (1 - discount); ``` ## Logging an Event To track custom events and measure how features or experiment groups affect those events, call the Log Event API. Specify the user and event name to log, and optionally provide a value and metadata object: ```csharp StatsigServer.LogEvent(user, "add_to_cart", "SKU_12345", new Dictionary<string, string> { { "price", "9.99" }, { "item_name", "diet_coke_48_pack" } }); ``` For more about identifying users, group analytics, and best practices, go to the [logging events guide](https://docs.statsig.com/guides/logging-events). ## Statsig User When calling APIs that require a user, pass as much information as possible. More user information enables advanced gate and config conditions (like country or OS/browser level checks), and lets Statsig accurately measure the impact of your experiments on your metrics and events. Statsig requires at least one identifier (userID or customID) to provide a consistent experience for a given user. Refer to [userID requirements](https://docs.statsig.com/sdks/user#why-is-an-id-always-required-for-server-sdks) for more detail. In addition to `userID`, the top-level fields on StatsigUser are `email`, `ip`, `userAgent`, `country`, `locale`, and `appVersion`. You can also pass any key-value pairs in an object/dictionary to the `custom` field to create targeting based on them. Typing on the `StatsigUser` object is lenient: you can pass numbers, strings, arrays, objects, and even enums or classes. However, evaluation operators only work on primitive types, mostly strings and numbers. The SDK attempts to cast custom field types to match the operator, but Statsig doesn't guarantee evaluation results for other types. For example, the SDK compares an array set as a custom field only as a string: there's no operator to match a value within that array. ### Private Attributes To keep sensitive user PII data out of logs, use the `privateAttributes` field on the StatsigUser object. This field accepts an object/dictionary of private user attributes. The SDK uses any attribute set in `privateAttributes` only for evaluation/targeting and removes it from all logs before Statsig sends them to its servers. For example, if a feature gate should only pass for users with emails ending in "@statsig.com", but you don't want to log email addresses to Statsig, add the key-value pair `{ email: "my_user@statsig.com" }` to `privateAttributes` on the user. ## Shutdown To gracefully shutdown the SDK and flush all events: ```csharp await StatsigServer.Shutdown(); ``` ================================================================================ # Node AI SDK URL: https://docs.statsig.com/ai-evals/node ================================================================================ # Node AI SDK - **Repository:** [statsig-ai-node](https://github.com/statsig-io/statsig-ai-node) The Statsig Node AI SDK (`@statsig/statsig-ai`) is the Node.js server SDK for Agent Experimentation. It serves AI Configs, so you can change prompts and models without deploying code. It also traces OpenAI, Anthropic, and Gemini calls to [AI Traces](https://docs.statsig.com/ai-evals/ai-traces) as OpenTelemetry spans, logs eval grades that your code computes, and runs evals from code. The SDK builds on the [Statsig Node Server SDK](https://docs.statsig.com/server-core/node-core). The SDK uses `prompt`, the earlier name for an AI Config, in its method names. For example, `getPrompt()` returns an AI Config. This page describes `@statsig/statsig-ai` version `0.0.1-beta.34`. ## Set up the SDK 1. **Install the SDK** Install the AI SDK and the Node Server SDK: #### npm ```shell npm install @statsig/statsig-ai @statsig/statsig-node-core ``` #### pnpm ```shell pnpm add @statsig/statsig-ai @statsig/statsig-node-core ``` #### yarn ```shell yarn add @statsig/statsig-ai @statsig/statsig-node-core ``` > **Note:** > > Versions `0.0.1-beta.30` through `0.0.1-beta.33` load `@statsig/statsig-node-core-rc` at startup, but no package with that name exists on npm. To install one of those versions, add `@statsig/statsig-node-core-rc@npm:@statsig/statsig-node-core` to the install command. This alias installs the Node Server SDK under that name. Without it, the install fails or the import throws `Cannot find module '@statsig/statsig-node-core-rc'`. The Node Server SDK includes native binaries. If you use a frozen lockfile or bundle your server with webpack, esbuild, or Next.js, follow the [Node Server SDK setup steps](https://docs.statsig.com/server-core/node-core#set-up-the-sdk). 2. **Initialize the SDK** Initialize the AI SDK with a [Server Secret Key](https://docs.statsig.com/access-management/api-keys#server-secret-keys). The examples on this page read the key from the `STATSIG_SDK_KEY` environment variable, which `initializeTracing()` also reads. > **Warning:** > > Keep Server Secret Keys private. If you expose one, disable it and create a new key in the Statsig console. Choose one of these setups: #### Create a Statsig instance The AI SDK creates and owns its own Statsig instance. `statsigOptions` accepts any [Statsig option](https://docs.statsig.com/server-core/node-core#statsig-options). ```ts import { StatsigAI } from "@statsig/statsig-ai"; const statsigAI = StatsigAI.newShared({ sdkKey: process.env.STATSIG_SDK_KEY!, statsigOptions: { environment: "production" }, // optional }); await statsigAI.initialize(); ``` #### Use an existing Statsig instance Pass in a Statsig instance that your app already initializes. The AI SDK doesn't initialize, flush, or shut down an instance you pass in. ```ts import { Statsig } from "@statsig/statsig-node-core"; import { StatsigAI } from "@statsig/statsig-ai"; const statsig = new Statsig(process.env.STATSIG_SDK_KEY!, { environment: "production", }); await statsig.initialize(); const statsigAI = StatsigAI.newShared({ statsig }); ``` `StatsigAI.newShared()` creates the instance and registers it as the shared instance. Get the shared instance anywhere in your app with `StatsigAI.shared()`. The tracing wrappers log each traced call as a `statsig::gen_ai` event through the shared instance. When no shared instance exists, they print a warning on every traced call. To create an instance that isn't shared, pass the same options to `new StatsigAI()`. ## Get an AI Config An AI Config holds versions of a prompt and its model settings, so you can change them in the Statsig console without deploying code. For details, go to [AI Configs](https://docs.statsig.com/ai-evals/prompts). Call `getPrompt()` with a user and the AI Config name. The SDK evaluates the AI Config for that user and returns its Live and Candidate versions. ```ts import { StatsigUser } from "@statsig/statsig-ai"; const user = new StatsigUser({ userID: "user-123" }); const prompt = statsigAI.getPrompt(user, "support_bot"); // The Live version, and any Candidate versions const live = prompt.getLive(); const candidates = prompt.getCandidates(); // Read the version's settings, and render its messages const model = live.getModel({ fallback: "gpt-5-mini" }); const messages = live.getPromptMessages({ question: "How do I reset my password?", }); ``` A version (`PromptVersion`) has these methods: | Method | Returns | | --- | --- | | `getName()`, `getID()` | The version name and ID. | | `getModel()`, `getProvider()` | The model and provider strings. | | `getTemperature()`, `getMaxTokens()`, `getTopP()`, `getFrequencyPenalty()`, `getPresencePenalty()` | Model parameters, as numbers. | | `getValue(key, fallback)` | Any other value stored on the version. | | `getPromptMessages(variables)` | The version's messages as `{ role, content }` objects, with each `{{variable}}` replaced. The SDK doesn't HTML-escape the values. | The model, provider, and parameter getters accept an optional `{ fallback }`, which they return when the version doesn't set the value. Without a fallback, the parameter getters return `0`, so pass a fallback for any parameter you send to your model provider. ## Trace model calls Tracing sends each model call to Statsig as an OpenTelemetry span. The spans appear in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces), where [online evals](https://docs.statsig.com/ai-evals/online-evals) can grade them. ### Initialize tracing Call `initializeTracing()` once, when your app starts and before you wrap any model client or call `wrap()`. If you call it in its own module, such as `instrumentation.ts`, import that module before any module that wraps a client or calls `wrap()`: ```ts // instrumentation.ts import { initializeTracing } from "@statsig/statsig-ai"; initializeTracing({ serviceName: "support-bot", environment: "production", }); ``` `initializeTracing()` throws `Statsig SDK Key is required for StatsigOTLPTraceExporter` unless you set the `STATSIG_SDK_KEY` environment variable or pass `exporterOptions.sdkKey`. Creating a `StatsigAI` instance doesn't set up tracing. Spans reach Statsig only after you call `initializeTracing()`. | Option | Description | | --- | --- | | `exporterOptions.sdkKey` | Your Server Secret Key. Defaults to the `STATSIG_SDK_KEY` environment variable. | | `exporterOptions.dsn` | A custom endpoint. The SDK appends `/v1/traces`. Defaults to `https://api.statsig.com/otlp`. | | `serviceName` | The `service.name` resource attribute. Defaults to the `OTEL_SERVICE_NAME` or `SERVICE_NAME` environment variable. | | `version` | The `service.version` resource attribute. | | `environment` | The `deployment.environment.name` resource attribute. Defaults to `NODE_ENV`. Go to [Set the environment](#set-the-environment). | | `enableGlobalTraceProviderRegistration` | When `true`, registers the SDK's tracer provider globally, so tracers you get from the OpenTelemetry API export to Statsig. | | `globalTraceProvider` | A tracer provider for the SDK to use instead of creating one. | | `globalContextManager` | A context manager for the SDK to use instead of creating one. | | `skipGlobalContextManagerSetup` | When `true`, the SDK doesn't create a global context manager. | `initializeTracing()` returns `{ exporter, processor, provider }`. If your app already runs the OpenTelemetry `NodeSDK`, add the returned processor to it, so the SDK's spans and your existing spans both reach Statsig. The AI SDK doesn't install `@opentelemetry/sdk-node`. Versions 0.300 and later of `@opentelemetry/sdk-node` use OpenTelemetry SDK 3.x, and the AI SDK uses 2.x. If your app doesn't list `@opentelemetry/sdk-node` as a dependency, install version 0.223: #### npm ```shell npm install @opentelemetry/sdk-node@0.223 ``` #### pnpm ```shell pnpm add @opentelemetry/sdk-node@0.223 ``` #### yarn ```shell yarn add @opentelemetry/sdk-node@0.223 ``` Then add the processor to `NodeSDK`: ```ts // instrumentation.ts import { NodeSDK } from "@opentelemetry/sdk-node"; import { initializeTracing } from "@statsig/statsig-ai"; const { processor } = initializeTracing({ serviceName: "support-bot", skipGlobalContextManagerSetup: true, // NodeSDK sets up its own }); const sdk = new NodeSDK({ spanProcessors: [processor], // ...your other NodeSDK options, such as instrumentations }); sdk.start(); ``` For more setups, go to the [SDK examples](https://github.com/statsig-io/statsig-ai-node/tree/main/examples/otel). ### Wrap your model client Wrap each model client once, after you call `initializeTracing()`, and use the wrapped client everywhere you call the model. Each wrapper gets its tracer when you wrap the client. A client that you wrap before `initializeTracing()` doesn't send spans, and the SDK logs `NoopOtelSingleton instance is being used`. ```ts import Anthropic from "@anthropic-ai/sdk"; import { GoogleGenAI } from "@google/genai"; import OpenAI from "openai"; import { wrapAnthropic, wrapGemini, wrapOpenAI } from "@statsig/statsig-ai"; const captureOptions = { capture_all: true }; const openai = wrapOpenAI(new OpenAI(), { captureOptions }); const anthropic = wrapAnthropic(new Anthropic(), { captureOptions }); const gemini = wrapGemini(new GoogleGenAI({}), { captureOptions }); ``` Each wrapper traces these methods, including streaming calls: | Wrapper | Client | Traced methods | | --- | --- | --- | | `wrapOpenAI` | `openai` | `chat.completions.create`, `completions.create`, `responses.create`, `responses.stream`, `responses.parse`, `embeddings.create`, `images.generate` | | `wrapAnthropic` | `@anthropic-ai/sdk` | `messages.create`, `messages.stream` | | `wrapGemini` | `@google/genai` | `models.generateContent`, `models.generateContentStream` | Each wrapper accepts the same optional configuration: | Option | Description | | --- | --- | | `captureOptions` | Which message content to record. All options are off by default. | | `customAttributes` | Attributes to add to every span from this client, such as `{ team: 'support' }`. They can't override the attributes the SDK sets. | | `maxJSONChars` | The longest JSON value to record per attribute, in characters. Defaults to `40000`. The SDK cuts off longer values and ends them with `…(truncated)`. | ### Record message content By default, the wrappers record the model, token counts, and timing, but no message content. Turn on `captureOptions` to view messages in the trace drawer. [Online evals](https://docs.statsig.com/ai-evals/online-evals) grade only spans that record both input and output messages. | Option | Records | | --- | --- | | `capture_all` | Everything in this table. | | `capture_input_messages` | `gen_ai.input.messages`, plus the variables passed to `getPromptMessages()`. | | `capture_output_messages` | `gen_ai.output.messages`. | | `capture_system_instructions` | `gen_ai.system_instructions`: system and developer messages, and the OpenAI `instructions` parameter. | | `capture_tool_definitions` | `gen_ai.tool.definitions`: the tools you pass to the model. | The SDK records messages in the [OpenTelemetry GenAI format](https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/), where each message has a `role` and a list of `parts`. For every attribute the spans carry, go to the [span attribute reference](https://docs.statsig.com/ai-evals/ai-traces#span-attribute-reference). ## Tag model calls with an AI Config version Run each model call inside `prompt.withLive()` or `prompt.withVersion()`, so its span records which AI Config version produced it. Online evals attribute each grade to the version on the span. A span without these attributes isn't linked to an AI Config: it doesn't appear on the AI Config's Traces tab, and its grades don't count toward any version. ```ts import type { PromptVersion } from "@statsig/statsig-ai"; async function answer(version: PromptVersion, question: string) { const response = await openai.chat.completions.create({ model: version.getModel({ fallback: "gpt-5-mini" }), messages: version.getPromptMessages({ question, }) as OpenAI.ChatCompletionMessageParam[], }); return response.choices[0].message.content; } const prompt = statsigAI.getPrompt(user, "support_bot"); // Serve the Live version const reply = await prompt.withLive((version) => answer(version, question)); // Serve a Candidate version const [candidate] = prompt.getCandidates(); if (candidate) { await prompt.withVersion(candidate, (version) => answer(version, question)); } ``` `withLive()` and `withVersion()` return a promise that resolves to the function's return value. Wrapped model calls and `wrap()` spans inside the function get these attributes: | Attribute | Value | | --- | --- | | `statsig.llm.prompt_name` | The AI Config name. | | `statsig.llm.prompt_version` | The version name. | | `statsig.llm.prompt_version_id` | The version ID. | | `statsig.llm.prompt_template_variables` | The variables passed to `getPromptMessages()`, as JSON. Model call spans record them only when you capture input messages. Workflow spans always record them. | The spans also record the user you passed to `getPrompt()`. ## Trace workflows and tools `wrap()` traces your own functions, such as an agent turn or a tool call, as spans in the same trace as the model calls they make. Pass a `type` and a `name`, and `wrap()` returns a function with the same signature. Call `wrap()` after `initializeTracing()`. A function that you wrap earlier doesn't send spans. ```ts import { wrap } from "@statsig/statsig-ai"; const searchDocs = wrap( { type: "tool", name: "search_docs" }, async (query: string) => { return docsIndex.search(query); }, ); const handleTurn = wrap( { type: "workflow", name: "support_turn" }, async (version: PromptVersion, question: string) => { const docs = await searchDocs(question); const response = await openai.chat.completions.create({ model: version.getModel({ fallback: "gpt-5-mini" }), messages: version.getPromptMessages({ question, docs: docs.join("\n"), }) as OpenAI.ChatCompletionMessageParam[], }); return response.choices[0].message.content; }, ); await prompt.withLive((version) => handleTurn(version, question)); ``` | Option | Description | | --- | --- | | `type` | `workflow` for a unit of work such as an agent turn, or `tool` for a tool call. | | `name` | The workflow or tool name, recorded as `statsig.gen_ai.workflow.name` or `statsig.gen_ai.tool.name`. | | `toolType` | Tool spans only. Recorded as `gen_ai.tool.type`. | | `attributes` | Extra span attributes. | | `user`, `activityID` | Tag this span and the spans inside it, like [`withStatsigContext()`](#add-users-and-activity-ids-to-spans). | The SDK names workflow spans `invoke_workflow` and tool spans `execute_tool`. Online evals grade a workflow span as the turn's answer, and never grade tool spans. The SDK doesn't mark the model calls inside a workflow span with `statsig.span.llm_root`, so online evals don't grade them on their own. `wrap()` doesn't record messages on workflow spans, and online evals skip a workflow span without them. To grade a workflow span, set its messages yourself, as [Grade a multi-step agent turn](https://docs.statsig.com/ai-evals/online-evals#grade-a-multi-step-agent-turn) shows. ## Add users and activity IDs to spans Context helpers add a user, and optionally an activity ID, to the spans that start inside a function: - `withStatsigUserContext(user, fn)`: Records the user's ID as `statsig.user_id` and the user's custom IDs as `statsig.custom_ids`, on every span that starts inside `fn`. - `withStatsigContext({ user, activityID }, fn)`: Records the user, and adds `activityID` to the custom IDs as `statsig.activity_id`, on wrapped model calls and `wrap()` spans inside `fn`. Use an activity ID to group the spans of a multi-turn conversation or a long-running job. AI Traces groups spans with the same activity ID in the trace drawer, even across traces. ```ts import { withStatsigContext } from "@statsig/statsig-ai"; await withStatsigContext({ user, activityID: conversationID }, () => prompt.withLive((version) => handleTurn(version, question)), ); ``` ## Set the environment Statsig reads each span's environment to filter AI Traces and to choose which spans online evals grade. Set the environment for all spans with the `environment` option of `initializeTracing()`. The option defaults to `NODE_ENV`, and the SDK records it as the `deployment.environment.name` resource attribute. To tag only some spans, run the code that creates them inside `withStatsigEnvironment()`. Spans that start inside the function get a `statsig.environment` attribute, which overrides the resource value for those spans. ```ts import { initializeTracing, withStatsigEnvironment } from "@statsig/statsig-ai"; initializeTracing({ environment: "production" }); // Tag canary traffic that runs in the production process await withStatsigEnvironment("staging_canary", () => handleRequest(request)); ``` Use `production` for live traffic. Statsig reserves `eval`, `online_eval_judge`, and `shadow` for spans it generates, and online evals never grade them. `Eval()` runs its tasks and scorers with `statsig.environment` set to `eval`. Don't use the reserved values for your own spans, except `eval` for the requests that a workflow eval sends. For details, go to [Join a workflow eval's trace](#join-a-workflow-eval-trace). For how Statsig reads environments, go to [Environments](https://docs.statsig.com/ai-evals/ai-traces#environments). ## Join a workflow eval's trace When Statsig runs an offline eval on an AI Config version with a [custom workflow](https://docs.statsig.com/ai-evals/prompts#call-your-own-endpoint-with-a-custom-workflow), it sends each dataset row to your endpoint as a POST request. Each request carries these headers: - `traceparent`: The W3C trace context of the row's trace in AI Traces. - `x-statsig-eval-run`: The ID of the eval run. Run your handler inside `withIncomingTraceContext()`, so the wrapped model calls and `wrap()` spans it starts join the row's trace. The trace drawer then shows them under the row's root span. ```ts import { withIncomingTraceContext } from "@statsig/statsig-ai"; // Node and Express app.post("/agent", (req, res) => withIncomingTraceContext(req.headers, async () => { res.json({ output: await runAgent(req.body) }); }), ); // Fetch-style handlers, such as Next.js route handlers export async function POST(request: Request) { return withIncomingTraceContext(request.headers, async () => Response.json({ output: await runAgent(await request.json()) }), ); } ``` `withIncomingTraceContext(headers, fn)` reads the `traceparent` and `tracestate` headers from Node request headers or a Fetch `Headers` object. It runs `fn` with the caller's span as the parent, and returns what `fn` returns. Without a valid `traceparent`, `fn` runs in the current context, so you can wrap every request. If OpenTelemetry HTTP instrumentation already started a span in the incoming trace, `withIncomingTraceContext()` keeps that span as the parent. Spans from your endpoint use your app's environment, such as `production`. To keep eval requests out of online evals and production traces, run them inside `withStatsigEnvironment("eval", ...)`: ```ts import { withIncomingTraceContext, withStatsigEnvironment, } from "@statsig/statsig-ai"; app.post("/agent", (req, res) => withIncomingTraceContext(req.headers, () => { const handle = async () => { res.json({ output: await runAgent(req.body) }); }; return req.headers["x-statsig-eval-run"] ? withStatsigEnvironment("eval", handle) : handle(); }), ); ``` Statsig sends these headers only during an eval run, not when you click **Test Connection**. A header that you set on the workflow with the same name replaces Statsig's. ## Log eval grades Use `logEvalGrade()` to send a grade that your own code computes, such as user feedback or a check in your app, to Statsig. Statsig shows these grades with the source SDK. ```ts const version = statsigAI.getPrompt(user, "support_bot").getLive(); statsigAI.logEvalGrade(user, version, 1, "user_feedback", { sessionId: conversationID, reasoning: "The user rated the reply as helpful.", }); ``` `logEvalGrade(user, version, score, graderName, options)` takes the AI Config version that produced the output, and a score from 0 to 1. The SDK drops a score outside that range and prints a warning. Always pass the `options` argument. Pass `{}` when you have no options to set. | Option | Description | | --- | --- | | `sessionId` | Groups grades from the same session. | | `activityId` | Sets `statsig.activity_id` on the user's custom IDs. | | `traceId`, `spanId` | The span the grade belongs to. When you set neither, the SDK uses the active span, so a grade logged inside a `wrap()` workflow belongs to that workflow span. To grade a span after it ends, such as from feedback that arrives later, save its IDs while it's active (`trace.getActiveSpan()?.spanContext()` from `@opentelemetry/api`), then pass both. | | `reasoning` | Why the grader gave this score. | | `metadata` | Extra string fields to log with the grade. | The SDK logs each grade as a `statsig::eval_result` event. For how grades appear in Statsig, go to [Online evals](https://docs.statsig.com/ai-evals/online-evals). ## Flush events and spans The SDK sends events and spans in batches. Before a short-lived process exits, such as a script or a serverless function, flush them: ```ts await statsigAI.flushEvents(); ``` `flushEvents()` always flushes spans. It flushes Statsig events, including eval grades, only when the AI SDK created the Statsig instance. If you passed in your own instance, flush that instance too: ```ts await statsig.flushEvents(); ``` To flush and stop the SDK when your server shuts down, call `await statsigAI.shutdown()`. ## Run an eval from code `Eval()` runs a task over records you define in code, scores each output, and sends the results to an eval in Statsig. Before you call `Eval()`: - Set the `STATSIG_API_KEY` environment variable to a [Console API key](https://docs.statsig.com/access-management/api-keys#console-api-keys). `Eval()` throws when the variable isn't set. - Create an eval in the Statsig console, under _Agent Experimentation > Evals_. Pass its name as the first argument to `Eval()`. If no eval has that name, Statsig rejects the results, and the SDK prints `[Statsig] Failed to send eval results: 404 Not Found`. ```ts import { Eval } from "@statsig/statsig-ai"; const result = await Eval("greeting_eval", { data: [ { input: "world", expected: "Hello world" }, { input: "test", expected: "Hello test" }, ], task: (input: string) => `Hello ${input}`, scorer: ({ output, expected }) => output === expected, evalRunName: "run-123", // optional }); ``` `Eval()` takes these options: | Option | Description | | --- | --- | | `data` | Records with an `input`, an optional `expected` output, and an optional `category` (a string or an array of strings). Pass an array, a promise, a function that returns either, an async iterable, or `statsigDataset()`. | | `dataset` | The name or ID of the [Statsig dataset](#run-an-eval-on-a-statsig-dataset) that the records come from. Each record then needs the `rowID` of a different row of the dataset. `statsigDataset()` sets this for you. | | `task` | A function, sync or async, that returns the output for an input. It receives the input and `{ parameters, category }`. | | `scorer` | A scorer function, or an object of named scorer functions. The SDK names a single scorer function `Grader`. A scorer returns a boolean, a number, or `{ score, metadata }`. `true` counts as 1 and `false` as 0. | | `parameters` | Zod schemas whose default values the task receives as `parameters`. | | `evalRunName` | A name for this run. | | `summaryScoresFn` | A function that receives every result and returns summary scores, as an object of numbers. | `Eval()` returns `{ results, metadata, summaryScores }`. Each result has the record's `input`, `expected`, and `category`, plus the `output`, a `scores` object, and an `error` flag. With tracing on, each result also has the record's [`traceID` and `spanID`](#traces-for-eval-records). Statsig stores each result's input, output, expected value, and score metadata as strings. `Eval()` sends other values as JSON. The results that `Eval()` returns keep the original values. Errors don't stop the run: - When a task throws, the SDK prints a warning, scores every scorer 0 for that record, and sets the record's `error` to `true`. `metadata.error` is `true` when any record has an error. - When a scorer throws, the SDK prints a warning and scores that scorer 0 for that record. The following example uses named scorers, a parameter, categories, and a summary score: ```ts import { Eval } from "@statsig/statsig-ai"; import { z } from "zod"; const result = await Eval("greeting_eval", { data: [ { input: "world", expected: "Hi world", category: "greeting" }, { input: "test", expected: "Hi test", category: ["greeting", "test"] }, ], parameters: { greeting: z.string().default("Hi"), }, task: (input: string, { parameters }) => `${parameters.greeting} ${input}`, scorer: { correctness: ({ output, expected }) => output === expected, startsWithGreeting: ({ output }) => ({ score: output.startsWith("Hi"), metadata: { length: output.length }, }), }, summaryScoresFn: (results) => ({ accuracy: results.filter((r) => r.scores.correctness === 1).length / results.length, }), }); ``` ### Run an eval on a Statsig dataset To run on a [dataset](https://docs.statsig.com/ai-evals/datasets) from the Statsig console, pass `statsigDataset(name, toRecord)` as `data`. `Eval()` loads every row of the dataset with the key in `STATSIG_API_KEY`, and `toRecord` turns each row into a record. The run records the dataset, so the eval's _Compare_ tab compares runs on the same dataset row by row. ```ts import { Eval, statsigDataset } from "@statsig/statsig-ai"; await Eval("support_bot_quality", { data: statsigDataset("support_cases", (row) => ({ input: row.columns.question, expected: row.columns.answer, category: row.groups, })), task: (input) => answer(input), scorer: ({ output, expected }) => output === expected, }); ``` `statsigDataset()` takes the dataset's name or ID. `toRecord` receives each row as `{ rowID, columns, groups }`: - `columns` maps each column name to the row's value, as a string. - `groups` lists the row's categories. Each record keeps its row's `rowID`. When the dataset can't load, `Eval()` throws `[Statsig] Failed to load eval dataset` with the HTTP status, before any task runs. To run on records that you build yourself from a dataset, set the `dataset` option, and give each record the `rowID` of its row. `Eval()` throws before any task runs when a record has no `rowID` or repeats one. Statsig rejects the results when a `rowID` isn't a row of the dataset. ### Traces for eval records When you call `initializeTracing()` before `Eval()`, each record runs in its own trace, even when you call `Eval()` inside another span. The root of the trace is a workflow span with the eval name as its workflow name, and these attributes: | Attribute | Value | | --- | --- | | `statsig.eval.name` | The eval name. | | `statsig.eval.run_name` | The `evalRunName`, when you set one. | | `statsig.eval.record_index` | The record's position in the data, counting from 0. | Wrapped model calls and `wrap()` spans in the task become children of the root span. Each scorer runs in its own child workflow span, named after the scorer and tagged with `statsig.eval.scorer_name`. Every span in the trace has `statsig.environment` set to `eval`, so AI Traces hides these spans by default, and online evals don't grade them. `Eval()` sends each record's `traceID` and `spanID` with its scores, so the scores also appear on the root span in [AI Traces](https://docs.statsig.com/ai-evals/ai-traces). `Eval()` flushes the spans before it returns. Without `initializeTracing()`, `Eval()` doesn't create traces. ## Use other Statsig SDK methods `getStatsig()` returns the underlying Statsig instance, however you initialized the AI SDK. Use it for any [Node Server SDK](https://docs.statsig.com/server-core/node-core) method: ```ts const statsig = statsigAI.getStatsig(); // Check a gate const enabled = statsig.checkGate(user, "my_gate"); // Log an event statsig.logEvent(user, "my_event", 1); ``` ## Upgrade to version 0.0.1-beta.34 If you upgrade from version `0.0.1-beta.33`, check these changes: - **No alias package**: The SDK no longer needs `@statsig/statsig-node-core-rc`. You can remove the alias from your dependencies. - **Fewer OpenTelemetry dependencies**: The SDK no longer installs `@opentelemetry/sdk-node`, `@opentelemetry/auto-instrumentations-node`, `@opentelemetry/sdk-metrics`, or `@opentelemetry/sdk-trace-node`. With npm, an app could import them before without listing them as dependencies. If your app imports any of them, add it to your dependencies. For `NodeSDK`, go to [Initialize tracing](#initialize-tracing). - **Model calls inside workflows**: The SDK no longer marks model calls inside a `wrap()` workflow span with `statsig.span.llm_root`, so online evals grade only the workflow span. If your workflow spans don't record input and output messages, online evals grade nothing in those turns. To set the messages, go to [Grade a multi-step agent turn](https://docs.statsig.com/ai-evals/online-evals#grade-a-multi-step-agent-turn). - **Eval traces**: With `initializeTracing()`, `Eval()` creates a trace for each record and flushes spans before it returns. For details, go to [Traces for eval records](#traces-for-eval-records). - **Eval result values**: `Eval()` sends non-string inputs, outputs, expected values, and score metadata as JSON. Before, Statsig rejected the whole run with a 400 error when any of them wasn't a string. The release also adds [`statsigDataset()`](#run-an-eval-on-a-statsig-dataset), the `dataset` option of `Eval()`, and [`withIncomingTraceContext()`](#join-a-workflow-eval-trace). For every change, go to the [release notes](https://github.com/statsig-io/statsig-ai-node/releases). ## Upgrade to version 0.0.1-beta.33 Version `0.0.1-beta.33` is the first release on npm after `0.0.1-beta.30`. If you upgrade from an earlier version, check these changes: - **Message format**: Wrappers record `gen_ai.input.messages` and `gen_ai.output.messages` in the OpenTelemetry GenAI format (`role` plus `parts`), not as OpenAI-shaped messages. Update any code that parses these attributes. - **System instructions**: System and developer messages, and the OpenAI `instructions` parameter, move out of `gen_ai.input.messages` into `gen_ai.system_instructions`. Turn on `capture_system_instructions` or `capture_all` to record them. - **Duplicate OpenAI requests**: In versions `0.0.1-beta.11` through `0.0.1-beta.30`, `wrapOpenAI` sent every request to OpenAI twice. Version `0.0.1-beta.33` sends each request once. The release also adds `wrapAnthropic`, `wrapGemini`, `withVersion()`, `withStatsigEnvironment()`, and the `traceId`, `spanId`, and `reasoning` options of `logEvalGrade()`. For every change, go to the [release notes](https://github.com/statsig-io/statsig-ai-node/releases). ================================================================================ # Python AI SDK URL: https://docs.statsig.com/ai-evals/python ================================================================================ # Python AI SDK - **Package:** `statsig-ai` ([pypi](https://pypi.org/project/statsig-ai)) - **Latest version:** 0.0.1b8 - **Repository:** [statsig-ai-python](https://github.com/statsig-io/statsig-ai-python) The Statsig Python AI SDK manages LLM prompts, runs online and offline evals, and debugs LLM applications in production from a Python server. Reach for it when you want to version prompts without shipping code, log eval grades back to Statsig for analysis, and run programmatic evaluations over your datasets. It builds on the [Statsig Python Server SDK](https://docs.statsig.com/server-core/python-core) and adds hooks for AI-specific functionality. ## How the Python AI SDK works 1. **Install the SDK** #### pip ```python pip install statsig-ai ``` #### poetry ```python poetry add statsig-ai ``` #### pipenv ```python pipenv install statsig-ai ``` 2. **Initialize the SDK** > **Tip:** > > For initialization requirements in forking and WSGI servers, refer to the [Statsig Python Server SDK](https://docs.statsig.com/server-core/python-core) docs. If you already have a Statsig instance, you can pass it into the SDK. Otherwise, the SDK creates an instance internally. #### Don't use Statsig Initialize the AI SDK with a Server Secret Key from the Statsig console. > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. ```python from statsig_ai import StatsigAI, StatsigCreateConfig statsig_ai = StatsigAI(statsig_source=StatsigCreateConfig(server_secret_key='YOUR_SERVER_SECRET_KEY')) statsig_ai.initialize(). ``` #### Initializing With Options Optionally, you can configure [StatsigOptions](https://docs.statsig.com/server-core/python-core#statsig-options) for your Statsig instance: ```python from statsig_ai import StatsigAI from statsig_python_core import StatsigOptions # if you want to configure any statsig options, this is optional: statsig_options = StatsigOptions() statsig_options.environment = 'production' statsig_ai_options.statsig_options = statsig_options statsig_ai = StatsigAI(statsig_source=StatsigCreateConfig(server_secret_key='YOUR_SERVER_SECRET_KEY', statsig_options=statsig_options)) statsig_ai.initialize() # if you would like to use any statsig methods, you can access the statsig instance from the statsig_ai instance: gate = statsig_ai.get_statsig().check_gate(statsig_user, 'my_gate') ``` #### Already have Statsig instance After installation, initialize the SDK with a [Server Secret Key from the Statsig console](https://console.statsig.com/api_keys). > **Warning:** > > Always keep Server Secret Keys private. If you expose one, you can disable and recreate it in the Statsig console. If you initialize this way, the AI SDK won't handle initialization, flushing, or shutdown. ```python from statsig_python_core import Statsig from statsig_ai import StatsigAI, StatsigAttachConfig statsig = Statsig('YOUR_SERVER_SECRET_KEY') statsig.initialize() statsig_ai = StatsigAI(statsig_source=StatsigAttachConfig(statsig=statsig)) statsig_ai.initialize() ``` #### Initializing With Options Optionally, you can configure [StatsigOptions](https://docs.statsig.com/server-core/python-core#statsig-options): ```python from statsig_python_core import Statsig, StatsigOptions from statsig_ai import StatsigAI, StatsigAttachConfig options = StatsigOptions() options.environment = 'production' statsig = Statsig('YOUR_SERVER_SECRET_KEY', options) statsig.initialize() statsig_ai = StatsigAI(statsig_source=StatsigAttachConfig(statsig=statsig)) statsig_ai.initialize() ``` ## Using the SDK ### Getting a prompt Statsig can act as the control plane for your LLM prompts, allowing you to version and change them without deploying code. The Statsig console calls these AI Configs; the SDK still calls them prompts (`get_prompt`). For more information, refer to [AI Configs](https://docs.statsig.com/ai-evals/prompts). ```python from statsig_ai import StatsigUser # Create a user object user = StatsigUser(user_id='a-user') # Get the prompt my_prompt = statsig_ai.get_prompt(user, 'my_prompt') # Use the live version of the prompt live_version = my_prompt.get_live() # Get the candidate versions of the prompt candidate_versions = my_prompt.get_candidates() # Use the live version of the prompt in a completion response = openai.chat.completions.create( model=live_version.get_model(fallback='gpt-4'), # optional fallback temperature=live_version.get_temperature(), max_tokens=live_version.get_max_tokens(), messages=[{'role': 'user', 'content': 'Your prompt here'}], ) ``` ### Logging eval results When running an [online eval](https://docs.statsig.com/ai-evals/online-evals), you can log results back to Statsig for analysis. Provide a score between 0 and 1, along with the grader name and any useful metadata (such as session IDs). You must provide the grader manually. Future releases support automated grading options. ```python from statsig_ai import StatsigUser live_prompt_version = statsig_ai.get_prompt(user, 'my_prompt').get_live() # Create a user object user = StatsigUser(user_id='a-user') # Log the results of the eval statsig_ai.log_eval_grade(user, live_prompt_version, 0.5, 'my_grader', { 'session_id': '1234567890', }) # flush eval grade events to statsig statsig_ai.flush().wait() ``` ### Programmatic evaluation Programmatic evaluation allows you to run evaluations on datasets programmatically, automatically scoring outputs and sending results to Statsig for analysis. With programmatic evaluation, you can: - **Run evaluations on datasets**: Process arrays, iterators, or async generators of input/expected pairs. - **Define custom tasks**: Create functions that generate outputs from inputs (supports both sync and async). - **Score outputs**: Use single or multiple named scorer functions to evaluate outputs (supports boolean, numeric, or metadata-rich scores). - **Use parameters**: Pass dynamic parameters to tasks using Zod schemas (Node) or dictionaries (Python). - **Categorize data**: Group evaluation records by categories for better analysis. - **Compute summary scores**: Aggregate results across all records with custom summary functions. - **Handle errors gracefully**: The SDK catches and reports task and scorer errors without stopping the evaluation. The evaluation automatically sends results to Statsig, where you can view them in the console alongside your other eval data. > **Note:** > > Tasks and scorers can be async functions. You can also provide data as async functions, promises, or async iterators. The `expected` field in data records is optional; scorers can evaluate outputs without expected values. The SDK automatically catches and reports task and scorer errors in the results. ```python from statsig_ai import Eval, EvalScorerArgs, EvalDataRecord, EvalHook # Basic evaluation with a single scorer result = Eval( name='greeting_task', data=[ {'input': 'world', 'expected': 'Hello world'}, {'input': 'test', 'expected': 'Hello test'}, ], task=lambda input: f'Hello {input}', scorer=lambda args: args.output == args.expected, eval_run_name='run-123', ) # Multiple named scorers result2 = Eval( name='multi_scorer_task', data=[ {'input': 'world', 'expected': 'Hello world'}, {'input': 'test', 'expected': 'Hello test'}, ], task=lambda input: f'Hello {input}', scorer={ 'correctness': lambda args: args.output == args.expected, 'starts_with_hello': lambda args: args.output.startswith('Hello'), 'length_check': lambda args: len(args.output) > 5, }, ) # Using parameters def task_with_params(input: str, hook: EvalHook) -> str: prefix = hook.parameters.get('prefix', 'Hello') return f'{prefix} {input}' result3 = Eval( name='parameterized_task', data=[ {'input': 'world', 'expected': 'Hi world'}, ], task=task_with_params, scorer=lambda args: args.output == args.expected, parameters={'prefix': 'Hi', 'suffix': '!', 'number': 123}, ) # Extras: Categories and summary scores def summary_scorer(results): correct = sum(1 for r in results if r.scores.get('correctness', 0.0) == 1.0) return { 'accuracy': correct / len(results) if results else 0.0, 'total': len(results), } result4 = Eval( name='categorized_with_summary', data=[ {'input': 'world', 'expected': 'Hello world', 'category': 'greeting'}, {'input': 'test', 'expected': 'Hello test', 'category': ['greeting', 'test']}, {'input': 'foo', 'expected': 'Goodbye foo', 'category': 'farewell'}, ], task=lambda input: f'Hello {input}', scorer={ 'correctness': lambda args: args.output == args.expected, }, summary_score_fn=summary_scorer, ) # Using EvalDataRecord dataclass result5 = Eval( name='dataclass_records', data=[ EvalDataRecord(input='world', expected='Hello world'), EvalDataRecord(input='test', expected='Hello test'), ], task=lambda input: f'Hello {input}', scorer=lambda args: args.output == args.expected, ) ``` ### OpenTelemetry (OTEL) The Python AI SDK doesn't yet support OTel tracing. Support is coming soon. ### Wrapping OpenAI The Python AI SDK doesn't yet support the OpenAI wrapper. Support is coming soon. ## Using other SDK methods You can access the Statsig instance from the statsig\_ai instance regardless of how you initialized it, and use its methods: ```python # Check a gate value gate = statsig_ai.get_statsig().check_gate(statsig_user, 'my_gate') # Log an event statsig_ai.get_statsig().log_event(statsig_user, 'my_event', value=1) ``` Refer to the [Statsig Python SDK](https://docs.statsig.com/server-core/python-core) docs for more information on Core Statsig SDK methods, advanced setup, and singleton usage. ================================================================================ # Client Persistent Assignment URL: https://docs.statsig.com/client/concepts/persistent_assignment ================================================================================ # Client Persistent Assignment Persistent assignment ensures that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting. ## Persistent storage Persistent storage uses an adapter approach, allowing you to plug in a storage solution of your choice to store assignments. The SDK references stored assignments later to ensure a user stays in the same bucket. You can implement an adapter that uses Local Storage, or one that uses remote storage, to enable persistence across multiple devices. The user persistent storage interface consists of a `load`/`loadAsync`, `save`, and `delete` API for read/write operations. > **Info:** > > Statsig supports Persistent Storage on: > > - The modern [`Javascript,`](https://docs.statsig.com/client/javascript-sdk) [`React`](https://docs.statsig.com/client/React), and [`React Native`](https://docs.statsig.com/client/ReactNative) SDKs, including on-device evaluation > - [`Android, on-device evaluation`](https://docs.statsig.com/client/androidOnDeviceEvaluationSDK) only > - [`iOS, on-device evaluation`](https://docs.statsig.com/client/swiftOnDeviceEvaluationSDK) only > - Go to [Support in iOS and Android SDKs](#support-in-ios-and-android-sdks) for Android and iOS details ### Persistent storage logic - Providing a storage adapter on Statsig initialization gives the SDK access to read & write on your custom storage. - Providing user persisted values to `get_experiment` informs the SDK to - **save** the evaluation of the current user **on first evaluation** - **load** the previously saved evaluation of a persisted user **on subsequent evaluations** - **delete** the previously saved evaluation of a persisted user if the experiment is no longer active - Not providing user persisted values to `get_experiment` **deletes** a previously saved evaluation. ### Example usage #### Javascript ```typescript import { StatsigClient } from '@statsig/js-client'; import { UserPersistentOverrideAdapter } from '@statsig/js-user-persisted-storage'; // Custom storage implementation using localStorage class LocalStorageUserPersistedStorage { load(key) { return JSON.parse(localStorage.getItem(key) ?? '{}'); } save(key, experiment, data) { const values = JSON.parse(localStorage.getItem(key) ?? '{}'); values[experiment] = JSON.parse(data); localStorage.setItem(key, JSON.stringify(values)); } delete(key, experiment) { const data = JSON.parse(localStorage.getItem(key) ?? '{}'); delete data[experiment]; localStorage.setItem(key, JSON.stringify(data)); } } const storage = new LocalStorageUserPersistedStorage(); const adapter = new UserPersistentOverrideAdapter(storage); const client = new StatsigClient('client-key', { overrideAdapter: adapter }); await client.initializeAsync({ userID: "123" }); const user = { userID: "123" }; const userPersistedValues = adapter.loadUserPersistedValues(user, 'userID'); const experiment = client.getExperiment('active_experiment', { userPersistedValues }); console.log(experiment.getGroupName()); // 'Control' // Switch to different user - will maintain same experiment group due to persistence const newUser = { userID: "456" }; const newExperiment = client.getExperiment('active_experiment', { userPersistedValues }); console.log(newExperiment.getGroupName()); // Still 'Control' ``` #### React The syntax for React matches vanilla JavaScript. For a full implementation example, refer to the [Persistent Storage Example](https://github.com/statsig-io/js-client-monorepo/tree/main/samples/next-js/src/app/persisted-user-storage-example) in Next.js. #### Android On-Device Eval #### Synchronous persistent evaluations The `UserPersistentStorageInterface` exposes two methods for synchronous persistent storage, which the SDK calls by default when evaluating an experiment. ```plaintext interface UserPersistentStorageInterface { suspend fun load(key: String): PersistedValues fun save(key: String, experimentName: String, data: String) fun delete(key: String, experiment: String) ... } ``` The `key` string is a combination of ID and ID Type: for example, "123:userID" or "abc:stableID". The SDK constructs this key and calls `get` and `set` on it by default. You can use this interface to persist evaluations synchronously to local storage. If you need an async interface, refer to Asynchronous persistent evaluations. #### Asynchronous persistent evaluations The `UserPersistentStorageInterface` exposes two methods for asynchronous persistent evaluations. Because the `getExperiment` call is synchronous, load the value first and pass it in as `userPersistedValues`. ```kotlin interface UserPersistentStorageInterface { fun loadAsync(key: String, callback: IPersistentStorageCallback) fun save(key: String, experimentName: String, data: String) fun delete(key: String, experiment: String) ... } interface IPersistentStorageCallback { fun onLoaded(values: PersistedValues) } ``` A top-level method loads the value for a given user and ID type: ```kotlin // Asynchronous load values val userPersistedValues = Statsig.client.loadUserPersistedValuesAsync( user: StatsigUser, idType: string, // userID, stableID, customIDxyz, etc callback: IPersistentStorageCallback ); // Synchronous load values val userPersistedvalues = Statsig.client.loadUserPersistedValues( user: StatsigUser, idType: string, // userID, stableID, customIDxyz, etc ) ``` After you implement `UserPersistentStorageInterface` and set it on `StatsigOptions`, the call site looks like this: ```kotlin // Asynchronous val callback = object: IPersistentStorageCallback { @override fun onLoaded(values: PersistedValues) { Statsig.getExperiment(user, "sample_experiment", GetExperimentOptions(userPersistedValues = values)) } } val userValues = Statsig.client.loadUserPersistedValuesAsync(user, "userID", callback) // Synchronous val user = StatsigUser(userID = "user123") val userValues = Statsig.client.loadUserPersistedValues(user, 'userID'); const experiment = statsig.getExperiment({userID: "123"}, 'the_allocated_experiment', { userPersistedValues: userValues }); ``` If you use Java, you can only override the loadAsync function and leave the load function empty. #### JS On-Device Eval ```typescript const storage = new CustomStorageAdapter(); // Need to implement const adapter = new UserPersistentOverrideAdapter(storage); const client = new StatsigOnDeviceEvalClient( 'client-key', { overrideAdapter: adapter } ); await client.initializeAsync(); const userInControl = { userID: "123" } const userInUnknown = { userID: "unknown" } const userPersistedValues = adapter.loadUserPersistedValues(user, 'userID'); let experiment = client.getExperiment('active_experiment', user, { userPersistedValues }); console.log(experiment.getGroupName()) // 'Control' experiment = client.getExperiment('active_experiment', userInUnknown, { userPersistedValues }); console.log(experiment.getGroupName()) // 'Control' ``` For a full implementation example, refer to the [Persistent Storage On-Device Eval Example](https://github.com/statsig-io/js-client-monorepo/tree/main/samples/next-js/src/app/persisted-user-storage-example-on-device) in Next.js. #### JS (legacy) ```typescript await statsig.initialize( 'client-key', { userPersistentStorage: new CustomStorageAdapter() } // Need to implement ); const userInControl = { userID: "123" } const userInUnknown = { userID: "unknown" } const userPersistedValues = await statsig.loadUserPersistedValuesAsync(userInControl, 'userID'); let experiment = statsig.getExperiment(userInControl, 'active_experiment', { userPersistedValues }); console.log(experiment.getGroupName()) // 'Control' experiment = statsig.getExperiment(userInUnknown, 'active_experiment', { userPersistedValues }); console.log(experiment.getGroupName()) // 'Control' ``` ## Support in iOS and Android SDKs Android and iOS SDKs offer a simplified version of Persistent Storage called `keepDeviceValues` that relies on on-device storage. This option is less flexible but requires only a single boolean flag. When you enable it, the SDK checks internally for a previously stored value in the `getExperiment`/`getLayer` call. The SDK uses that stored value even if allocation or targeting has changed. When the experiment ends, the SDK stops persisting values. #### iOS #### Swift ```swift // With an Experiment: let titleExperiment = Statsig.getExperiment("new_user_promo_title", true) // <-- "true" flag sets keep device values // Use the experiment like normal: let promoTitle = titleExperiment.getValue(forKey: "title", defaultValue: "Welcome to Statsig!") // Or a Layer: let layer = Statsig.getLayer("user_promo_experiments", true) // <-- "true" flag sets keep device values // Use the layer like normal: let promoTitle = layer.getValue(forKey: "title", defaultValue: "Welcome to Statsig!") ``` #### Objective C ```objc // With an Experiment: DynamicConfig *expConfig = [Statsig getExperimentForName:@"new_user_promo_title" true]; // <-- "true" flag sets keep device values // Use the experiment like normal: NSString *promoTitle = [expConfig getStringForKey:@"title" defaultValue:@"Welcome to Statsig! Use discount code WELCOME10OFF for 10% off your first purchase!"]; double discount = [expConfig getDoubleForKey:@"discount" defaultValue:0.1]; double price = msrp * (1 - discount); ``` #### Android #### Java ```Java // With an Experiment: DynamicConfig titleExperiment = Statsig.getExperiment("new_user_promo_title", true); // <-- "true" flag sets keep device values // Use the experiment like normal: String promoTitle = titleExperiment.getString("title", "Welcome to Statsig!"); // Or a Layer: Layer layer = Statsig.getLayer("user_promo_experiments", true) // <-- "true" flag sets keep device values // Use the layer like normal: String promoTitle = layer.getString("title", "Welcome to Statsig!"); ``` #### Kotlin ```kotlin // With an Experiment: val titleExperiment = Statsig.getExperiment("new_user_promo_title", true) // <-- "true" flag sets keep device values // Use the experiment like normal: val promoTitle = titleExperiment.getString("title", "Welcome to Statsig!") // Or a Layer: val layer = Statsig.getLayer("user_promo_experiments", true) // <-- "true" flag sets keep device values // Use the layer like normal: val promoTitle = layer.getString("title", "Welcome to Statsig!") ``` ================================================================================ # Server Persistent Assignment URL: https://docs.statsig.com/server/concepts/persistent_assignment ================================================================================ # Server Persistent Assignment Persistent assignment lets you ensure that a user's variant stays consistent while an experiment is running, regardless of changes to allocation or targeting. ## Persistent storage adapter The persistent storage adapter lets you plug in your own storage solution that the Statsig SDK uses to persist user assignments. The storage interface provides a `load` and `save` API for read/write operations. > **Info:** > > Statsig supports this only in `Go`, `Ruby`, `Legacy Node`, `Node Core`, `Java Core`, `Kotlin`, `.Net`, `Python Core`, `PHP Core`, `Rust Core` ### Persistent storage logic - Providing a storage adapter at Statsig initialization gives the SDK access to read and write to your custom storage. - Providing user persisted values to `get_experiment` tells the SDK to: - **save** the current user's evaluation **on first evaluation** (only when the experiment or layer **is active**) - **load** the previously saved evaluation **on subsequent evaluations** - Statsig deletes persisted values when: - You call `getExperiment` with `user_persisted_values=None` - The experiment isn't active ### Persistent assignment options (limited SDK support) - **Enforce Targeting**: `boolean`, default: `false` - Whether to enforce targeting rules before assigning persisted values #### Kotlin ```kotlin val options = GetExperimentOptions( ... persistentAssignmentOptions = PersistentAssignmentOptions( enforceTargeting = true, ) ) ``` #### Node JS ```ts const options: GetExperimentOptions = { ... persistentAssignmentOptions: { enforceTargeting: true, } } ``` ### Example usage #### Ruby ```ruby Statsig.initialize( 'secret-key', StatsigOptions.new( user_persistent_storage: DummyPersistentStorageAdapter.new ) ) persisted_user = StatsigUser.new({ 'userID' => 'test-123' }) exp = Statsig.get_experiment( # User gets saved to persisted storage persisted_user, 'active_experiment', Statsig::GetExperimentOptions.new( user_persisted_values: Statsig.get_user_persisted_values(persisted_user, 'userID') ) ) puts exp.group_name # 'Control' exp = Statsig.get_experiment( # User evaluates using values from persisted storage StatsigUser.new({'userID' => 'unknown'}), 'active_experiment', Statsig::GetExperimentOptions.new( user_persisted_values: Statsig.get_user_persisted_values(persisted_user, 'userID') ) ) puts exp.group_name # 'Control' ``` #### Python (Python Core) ```python from statsig_python_core import Statsig, StatsigUser, StatsigOptions, ExperimentEvaluationOptions, PersistentStorage options = StatsigOptions(persistent_storage = MyPersistentStorage()) statsig = Statsig.initialize(options).wait user = StatsigUser("a-user") exp = statsig.get_experiment(StatsigUser("a-user"), ExperimentEvaluationOptions(user_persisted_values= PersistentStorage.get_user_persisted_value(user, "user_id"))) print(f"{exp.group_name}") # control ``` #### Java Core ```java PersistentStorage persistentStorage = new MyPersistentStorage(); // See /server-core/java-core/#persistent-storage on how to implement it StatsigOptions options = new StatsigOptions.Builder() .setPersistentStorage(persistentStorage) .build(); Statsig statsig = new Statsig("secret-key", options); statsig.initialize().get(); StatsigUser persistedUser = new StatsigUser.Builder().setUserID("test-123").build(); Map<String, StickyValues> persistedValues = persistentStorage.getValuesForUser(persistedUser, "userID"); if (persistedValues == null) { persistedValues = new HashMap<>(); } Experiment exp = statsig.getExperiment( persistedUser, "active_experiment", new GetExperimentOptions(persistedValues) ); System.out.println(exp.getGroupName()); // "Control" StatsigUser unknownUser = new StatsigUser.Builder().setUserID("unknown").build(); Map<String, StickyValues> valuesForPersistedUser = persistentStorage.getValuesForUser(persistedUser, "userID"); Experiment persistedExp = statsig.getExperiment( unknownUser, "active_experiment", new GetExperimentOptions(valuesForPersistedUser) ); System.out.println(persistedExp.getGroupName()); // "Control" ``` #### Node Core ```typescript let persistedStorage = new MyPersistentStorage(); // See /server-core/node-core/#persistent-storage on how to implement it let options = new StatsigOptions((persistentStorage = persistedStorage)); let statsig = new Statsig(secretKye, options); let user = new StatsigUser("a-user"); let exp = statsig.getExperiment( user, ExperimentEvaluationOptions( (userPersistentValues = persistedStorage.getUserPersistedValues( user, "user_id", )), ), ); ``` #### PHP Core ```php $persistent_storage = new MyPersistentStorage(); // See /server-core/php-core/#persistent-storage on how to implement it $options = new StatsigOptions(persistent_storage: $persistent_storage); $statsig = new Statsig("secret-key", $options); $statsig->initialize(); $persisted_user = new StatsigUser("test-123"); $persisted_values = $persistent_storage->getValuesForUser($persisted_user, "userID") ?? []; $exp = $statsig->getExperiment( $persisted_user, "active_experiment", ["user_persisted_values" => $persisted_values], ); echo $exp->groupName; // "Control" $unknown_user = new StatsigUser("unknown"); $values_for_persisted_user = $persistent_storage->getValuesForUser($persisted_user, "userID"); $persisted_exp = $statsig->getExperiment( $unknown_user, "active_experiment", ["user_persisted_values" => $values_for_persisted_user], ); echo $persisted_exp->groupName; // "Control" ``` #### Rust Core ```rust let persistent_storage = Arc::new(MyPersistentStorage::new()); // See /server-core/rust-core/#persistent-storage on how to implement it let options = StatsigOptions::builder() .persistent_storage(Some(persistent_storage.clone())) .build(); let statsig = Statsig::new("secret-key", Some(Arc::new(options))); statsig.initialize().await; let persisted_user = StatsigUser::with_user_id("test-123"); let persisted_values = persistent_storage .get_values_for_user(&persisted_user, "userID") .unwrap_or_default(); let exp = statsig.get_experiment_with_options( &persisted_user, "active_experiment", ExperimentEvaluationOptions { user_persisted_values: Some(persisted_values), ..Default::default() }, ); println!("{}", exp.group_name.as_deref().unwrap_or("")); // "Control" let unknown_user = StatsigUser::with_user_id("unknown"); let values_for_persisted_user = persistent_storage.get_values_for_user(&persisted_user, "userID"); let persisted_exp = statsig.get_experiment_with_options( &unknown_user, "active_experiment", ExperimentEvaluationOptions { user_persisted_values: values_for_persisted_user, ..Default::default() }, ); println!("{}", persisted_exp.group_name.as_deref().unwrap_or("")); // "Control" ``` #### Kotlin ```kotlin runBlocking { Statsig.initialize( "secret-key", StatsigOptions(userPersistentStorage = MyPersistentStorageAdapter()) ) } val persistedUser = StatsigUser("test-123") var exp = Statsig.getExperimentSync( persistedUser, "active_experiment", GetExperimentOptions( userPersistedValues = Statsig.getUserPersistedValues(persistedUser, "userID"), ), ) println(exp.groupName) // "Control" exp = Statsig.getExperimentSync( StatsigUser("unknown"), "active_experiment", GetExperimentOptions( userPersistedValues = Statsig.getUserPersistedValues(persistedUser, "userID"), ), ) println(exp.groupName) // "Control" ``` #### Node JS ```ts await Statsig.initialize("secret-key", { userPersistentStorage: new MyPersistentStorageAdapter(), }); const persistedUser: StatsigUser = { userID: "123" }; let exp = Statsig.getExperimentSync(persistedUser, "active_experiment", { userPersistedValues: Statsig.getUserPersistedValues(user, "userID"), }); console.log(exp.getGroupName()); // "Control" exp = Statsig.getExperimentSync({ userID: "unknown" }, "active_experiment", { userPersistedValues: Statsig.getUserPersistedValues(user, "userID"), }); console.log(exp.getGroupName()); // "Control" ``` #### Go ```go InitializeWithOptions( "secret-key", &Options{ UserPersistentStorage: persistentStorage, } ) persistedUser := User{UserID: "123"} exp := GetExperimentWithOptions( persistedUser, "active_experiment", &GetExperimentOptions{ PersistedValues: GetUserPersistedValues(persistedUser, "userID") } ) fmt.Println(exp.GroupName) // "Control" exp = GetExperimentWithOptions( User{UserID: "unknown"}, "active_experiment", &GetExperimentOptions{ PersistedValues: GetUserPersistedValues(persistedUser, "userID") } ) fmt.Println(exp.GroupName) // "Control" ``` #### .Net ```csharp var options = new StatsigServerOptions(); options.UserPersistentStorage = new MyPersistentStorageAdapter() await StatsigServer.Initialize("server-secret-key", options); var persistedUser = new StatsigUser { UserID = "123" }; var values = await StatsigServer.GetUserPersistedValues(persistedUser, "userID"); var getExpOptions = new StatsigGetExperimentOptions(values); var exp = StatsigServer.GetExperimentSync(persistedUser, "active_experiment", getExpOptions); Console.WriteLine(exp.GroupName); // "Control" var newValues = await StatsigServer.GetUserPersistedValues(persistedUser, "userID"); var newGetExpOptions = StatsigGetExperimentOptions(newValues); var newExp = StatsigServer.GetExperimentSync(new StatsigUser {UserID = "unknown"}, "active_experiment", newGetExpOptions); Console.WriteLine(newExp.GroupName); // "Control" ``` ================================================================================ # Local Eval Adapter URL: https://docs.statsig.com/client/concepts/local-eval-adapter ================================================================================ # Local Eval Adapter ## Local Eval Adapter A common limitation of experimentation systems is the **dependence on an upfront network request to fetch experiment configurations**. [Bootstrapping](https://docs.statsig.com/client/concepts/initialize#2-bootstrap-initialization) and [Synchronous Initialization](https://docs.statsig.com/client/concepts/initialize#4-synchronous-initialization) offer alternatives, but both have limitations. Bootstrapping still requires an upfront request, though you can make it synchronous with other requests. Synchronous initialization can result in configs that are out of date by one session. The Local Eval Adapter removes this dependence by letting you ship experiment configurations inline with your application, so you can run experiments before initialization completes. The adapter expects a ruleset defining your experiments, similar to Statsig's Server SDKs. Refer to the [Example Ruleset below](#example-ruleset-config-spec). ## Limitations Shipping with a ruleset presents security concerns. When you scope the experiment set to only a few experiments that run before any network requests, those concerns are often minimal. Exercise caution when shipping a ruleset in production code and verify that the contents are correct and safe. ## Usage & functionality With proper attention to security and maintenance of the ruleset in your application, the Local Eval Adapter addresses the downsides of other experiment-at-launch strategies. > **Info:** > > The local evaluation adapter is for Enterprise and Pro Tier companies only. If you're trying to follow these instructions but don't meet that criteria, some of the setup steps may not work. The Adapter manifests as a StatsigOptions object seeded with a ruleset payload: #### iOS ```swift Statsig.initialize( sdkKey: "client-sdkkey", user: user, options: StatsigOptions( overrideAdapter: OnDeviceEvalAdapter(stringPayload: onDeviceEvalAdapterRulesetPayload) ) ) { err in // Initialization completed. `err` is `nil` if it was successful } ``` #### Android ```kotlin val adapter = OnDeviceEvalAdapter("...") // dcs payload as string val user = StatsigUser("a-user") Statsig.initializeAsync(application, "client-sdk", user, object : IStatsigCallback { override fun onStatsigInitialize() { println(adapter.getGate(Statsig.getFeatureGate("a_gate"), user)?.details?.reason) // [OnDevice] Bootstrap:Recognized println(Statsig.getFeatureGate("a_gate").details.reason) // Network:Recognized } }) ``` #### JavaScript ```js const adapter = new OnDeviceEvalAdapter(); adapter.setData('...'); // dcs payload as string const client = new StatsigClient( 'client-...', { userID: 'a-user' }, { overrideAdapter: adapter, }, ); // purposely not awaiting this, will use local specs until network is resolved const isReady = client.initializeAsync(); const localEvalGate = client.getFeatureGate('a_gate'); console.log(localEvalGate.details.reason); // [OnDevice] Bootstrap:Recognized await isReady; const networkEvalGate = client.getFeatureGate('a_gate'); console.log(networkEvalGate.details.reason); // Network:Recognized ``` ### Example ruleset "Config Spec" The ruleset is a JSON object that contains the following fields: ```json { "feature_gates": [], "dynamic_configs": [], "layer_configs": [], "time": 1735718400000 } ``` You can retrieve your ruleset by API. Use target apps to scope the ruleset to only the experiments and feature gates needed on startup. For assistance, reach out in your Slack channel or the [community Slack](https://statsig.com/slack). ================================================================================ # Server Data Stores / Data Adapter URL: https://docs.statsig.com/server/concepts/data_store ================================================================================ # Server Data Stores / Data Adapter A common question when configuring Statsig is how to handle potential points of failure. For example, if there is a Statsig API outage, can your integration continue to function? Yes. Your server SDK continues to operate normally, serving the most recent set of known values in response to calls like `checkGate`, `getConfig`, `getExperiment`, and `getLayer`. After the API recovers, your SDK automatically re-fetches the most up-to-date version of your project. Starting a new server or SDK instance while Statsig is down is a different scenario. The `DataAdapter`/`DataStore` addresses this case. ## DataAdapter (or DataStore) DataAdapters let you plug in your own storage solution as a cache that the Statsig Server SDKs use to load your project configurations (all experiments, configs, gates, and their targeting and allocation rules). Key use cases include reducing dependency on Statsig servers for initialization, improving initialization time by loading config from a local data store, and minimizing network I/O. DataAdapters implement a simple API: `initialize`, `get`, `set`, and `shutdown`. ### Recommended implementation In most cases, **your web servers should only implement the read path (`get`)**. Leaving the write path (`set`) empty is the best practice. If every SDK instance writes to the store on every update, this creates unnecessary contention and duplication. Instead, you should have a single source of truth that keeps your datastore up-to-date: - Run a **separate out-of-band service** that implements the SDK and is responsible for writing updates into the datastore using `set`. - Or, use a **cron job / periodic job** to fetch the config from the Statsig CDN endpoint and update your datastore under the correct cache keys (`statsig.cache`, `statsig.id_lists`, and `statsig.id_lists::{list_name}`). The Statsig SDK already handles this refresh logic by default, so separating read and write responsibilities is the cleanest and most reliable pattern. ### Data adapter logic - When you initialize the Statsig SDK with a DataAdapter, it first attempts to load config using `DataAdapter.get`. - If the entry exists, the SDK uses it. - If the entry doesn't exist and you haven't enabled `localMode`, the SDK fetches the config from Statsig servers and (if you have a writer service) persists it using `DataAdapter.set`. - After initialization, the SDK continues to poll Statsig servers for updates and saves them back to your data store when available (if you have implemented `set` and designated a writer service). - If you initialize the SDK client with `localMode=true`, this disables all network fetches from Statsig. - The cache keys used to be: - `statsig.cache` → config specs - `statsig.id_lists` → lookup of id lists - `statsig.id_lists::{list_name}` → actual id list values - but in the latest node and server core sdks, the format has changed: - `statsig|{path}|{format}|{hashedSDKKey}` where `path` is `/v1/download_config_specs` or `/v1/get_id_lists`, format is `plain_text`, and the `djb2` has of the sdk key is the last bit - the SDK handles this for you, reach out if you're trying to recreate this path yourself to double check > **Note:** > > Most DataAdapters handle only the `initialize` path for getting a project definition. > > Only `Node.js`, `Ruby`, `Go`, `Java`, and `.NET` support polling for updates. > If you're interested in using a DataAdapter as the source of truth indefinitely, reach out in the [Slack community](https://statsig.com/slack) and tell Statsig which language this is useful for! For information on your specific SDK language, go to the language-specific docs in the left-hand column. ================================================================================ # Target Apps URL: https://docs.statsig.com/sdks/target-apps ================================================================================ # Target Apps > **Info:** > > Target Apps are an Enterprise-only feature. Reach out to the support team, your sales contact, or through the [Slack community](https://statsig.com/slack) if you want to enable it. ## Overview SDK Keys support two attributes that restrict their access to certain configs: Environments and Target Apps. A Target App is a user-defined abstraction tied to entities in your Statsig project, and you can link it to one or more SDK Keys. Target Apps represent things like your “Android” or “iOS” apps, or more specific services like “Search” and “Feed” that may span both client and server usage. Defining and using Target Apps is a best practice at large scale. The two main benefits are: - Performance: removing unused entities from the SDK payload speeds up initialization time and reduces the data stored in local caches or data stores. - Security: you may not want to expose certain gates, experiments, or configs to client-side code or to a client key that's easily discoverable in your app. Specifying a target app for your client key and linking only client-specific configs to it keeps those configs from being visible. Before using Target Apps, consider whether separate Statsig projects might be a better fit: - If you need to share gates, experiments, or metrics across apps or services, use a Target App. Statsig restricts entities to a single project. - If your services or apps always have distinct gates, experiments, and metrics, a separate Statsig project may be a better solution. For existing Statsig projects with multiple SDK integrations, Statsig suggests entities to tag based on historical checks from each SDK, to help you set up Target Apps. ## Configuring target apps ### Project setup Start by going to **Settings** → [**Target Applications**](https://console.statsig.com/settings/apps). ![Project Settings](https://docs.statsig.com/images/target_apps/settings.png) ![Screenshot 2025-09-04 at 11 48 55 PM](https://github.com/user-attachments/assets/c359c25c-dead-44c4-8c1f-dd8cefb24929) Create a target app, or use one that Statsig suggests based on your current SDK exposure logs. ![Project Settings](https://docs.statsig.com/images/target_apps/add.png) ### Associating a feature gate with a target app To verify suggestions from initial setup or add more entities to a target app, navigate to the entity directly. Navigate to the **Feature Gates** tab and select a specific gate. In the right rail for that gate, view and edit the target apps on it. ![Project Settings](https://docs.statsig.com/images/target_apps/gate.png) Repeat this flow for Dynamic Configs, Experiments, and Layers that this Target App uses. > **Warning:** > > **Target App scope doesn't propagate to gate dependencies.** If a gate has a `passes_gate` or `fails_gate` condition that references another gate, tag that dependency gate with the same Target App independently. Without its own tag, the SDK excludes the dependency gate from its payload, so the condition evaluates silently to `false`. Tag every gate in the dependency chain, not just the entry point. Verify coverage from each gate's right rail. > **Note:** > > **Implicit layers**: When you create an experiment without placing it in an explicit layer, Statsig auto-creates an implicit layer. SDKs never receive implicit layers, so the console doesn't expose a Target App field on them. Tag the experiment entity directly to scope it. If you query your project through the Console REST API, implicit layers appear with `isImplicitLayer: true` and an empty `targetApps` array. This is expected. Tagging the experiment is what scopes it. ### Associating an SDK key with a target app Navigate to **Settings** → [**Keys & Environments**](https://console.statsig.com/api_keys). Select the SDK Key you want to restrict to a Target App. Under **Actions**, open the dropdown menu. ![Project Settings](https://docs.statsig.com/images/target_apps/keys.png) Then select the target app(s) to apply to that key. ![Project Settings](https://docs.statsig.com/images/target_apps/apply.png) > **Note:** > > When [bootstrapping](https://docs.statsig.com/client/concepts/initialize#2-bootstrap-initialization) a client SDK from a server SDK, the server SDK must have access to all gates, experiments, and configs that both the server and the client need. If you have separate target apps for client and server SDKs, apply both target apps to the server key you're using. > > To filter the bootstrapping response to a specific target app, pass a client key with that target app applied to the `getClientInitializeResponse` call. ### Debugging To debug SDK evaluations that your Target App configuration might affect, use the **Diagnostics** tab for any entity. In the Exposure Stream at the bottom, each check shows the Target App associated with the SDK key used. If any exposure doesn't have a matching Target App, Statsig flags it with a warning. ================================================================================ # Deprecation Notices URL: https://docs.statsig.com/server/deprecation-notices ================================================================================ # Deprecation Notices ## Direct initialization API access for server SDKs, October 31, 2025 #### What's changing Until mid-2024, Statsig's Server SDKs downloaded configuration values directly from Statsig servers on startup. Statsig now hosts these configuration files on a secure CDN (Cloudflare), which reduces initialization time and increases reliability. Direct API access is deprecated. It's only available in outdated SDK versions. All customers must stop using these SDK versions and upgrade. #### Change required The only change required is a minor SDK version bump. You don't need any code changes. Bump your SDK version to at least: - **go-sdk** 1.30.3 - **java-server** 1.9.0 - **py-server** 0.28.0 - **ruby-server** 1.29.0 - **statsig-node** 5.25.0 - **.NET** 2.4.1 - **Node-lite** 0.5.0 - **PHP** 3.7.2 Make this change by October 31st, 2025. > **Note:** > > Only a more recent version of the PHP and .NET SDKs supports CDN access, so Statsig won't strictly enforce an upgrade for those 2 SDKs. Upgrade as soon as possible. ## New method for country resolution Starting December 9th, 2024, Statsig uses a more accurate method of resolving IP addresses to country codes in client SDKs, which may result in different gate behavior for some users. For country resolution in both Client and Server SDKs, Statsig uses a [homegrown package](https://github.com/statsig-io/ip3country) that lacks IPv6 support. To resolve countries without increasing SDK size, Statsig uses the cloud provider's country resolution when serving requests to the `/initialize` endpoint. ### Potential changes in client evaluations This may result in different evaluations for some client-side checks. The new method is more accurate and complete. You may see more users passing country rules, because the new method resolves countries for IPv6 users, who now represent a large share of many customers' user base. ### Conflicts with server-side checks If you check some configs on both the client and server side, a small number of users may pass targeting on the client but fail on the server, or vice versa. Server-side country resolution continues to use [IP3Country](https://github.com/statsig-io/ip3country) when a country isn't explicitly set on the `StatsigUser` object. To avoid conflicts, use your cloud provider's country resolution (often available in a load balancer) and set the result as the `country` field on the `StatsigUser` object. This applies to evaluations for gates, configs, experiments, and layers, and also to `getClientInitializeResponse` when generating the payload for a client SDK. ## Async evaluation functions #### Reason Statsig originally designed Server SDKs for maximum backward compatibility. If a Server SDK didn't support an operator or configuration, it fell back to Statsig servers to ensure a valid result, which required asynchronous top-level evaluation functions. In practice, you rarely need this fallback. Newer releases remove the asynchronous functions. #### Example ```java var result = await Statsig.checkGate("my_gate"); // Bad // For node v6.0.0 var result = Statsig.checkGate("my_gate") // Good // For .Net and Java var result = Statsig.checkGateSync("my_gate"); // Good ``` #### SDKs .NET Server - [v1.20.0](https://github.com/statsig-io/dotnet-sdk/releases/tag/v1.20.0) NodeJS Server - [v5.10.0](https://github.com/statsig-io/node-js-server-sdk/releases/tag/v5.10.0) Java/Kotlin Server - [v1.12.0](https://github.com/statsig-io/java-server-sdk/releases/tag/v1.12.0) ================================================================================ # SDK Support Policy URL: https://docs.statsig.com/sdks/support ================================================================================ # SDK Support Policy Statsig provides official support only for SDK versions released within the past **one year**, unless otherwise specified. Some updates may require a different timeline or migration path. ## Supported versions - Statsig provides support (bug reports, issue investigation, and compatibility assistance) for SDK versions released **within the past 12 months**. - Statsig considers versions older than one year **unsupported**. They may continue to function, but Statsig doesn't guarantee their behavior or compatibility with backend services. - Upgrade to the latest version to benefit from new features, performance improvements, and critical fixes. ## Versioning and releases - All SDKs follow [Semantic Versioning (SemVer)](https://semver.org/), using the format `MAJOR.MINOR.PATCH`, **unless otherwise specified**. - **MAJOR**: breaking changes - **MINOR**: backwards-compatible new features - **PATCH**: backwards-compatible bug fixes - Statsig publishes release notes in the GitHub Releases section of each SDK’s repository. These notes contain details on changes, improvements, and upgrade instructions. ## Open source and community contributions - Statsig releases all SDKs as open source under the [ISC License](https://opensource.org/licenses/ISC), allowing developers to freely use, modify, and distribute them. - Statsig welcomes and encourages community contributions. ## Get help For help with upgrading, reviewing release notes, or contributing, refer to the SDK’s GitHub repository or reach out in [Slack](https://statsig.com/slack). ================================================================================ # Enrich SDK users with Forward Proxy URL: https://docs.statsig.com/server/concepts/async-user-enrichment ================================================================================ # Enrich SDK users with Forward Proxy With standard SDK ID list targeting, each application process downloads and stores ID lists in memory. Large lists or many application replicas increase total memory use. Forward Proxy user enrichment stores shared list data in Redis and fetches a user's memberships before local evaluation. Use enrichment to reduce application memory use or share list storage across processes. Building each enriched user requires an asynchronous network request. Use standard SDK targeting when list data fits each process's memory budget and you want to build users without that request. Evaluation remains local with either approach. Both standard SDK targeting and Forward Proxy enrichment require Statsig Support enablement for lists above 10 million IDs. Enrichment doesn't increase the project's ID list allowance or enable a 100-million-ID list automatically. ## How enrichment works Enrichment requires a compatible early-access SDK build and a [Forward Proxy deployment](https://docs.statsig.com/server/concepts/forward-proxy-id-list-enrichment) with synchronized ID list data. For the Rust integration, follow [ID list enrichment in the Rust SDK](https://docs.statsig.com/server-core/rust-core#enrich-users-for-forward-proxy-id-list-evaluation). Enrichment adds an asynchronous network step before evaluation: 1. Your application provides the user's ID and any custom IDs to an enrichment builder. 2. The builder requests memberships from Forward Proxy using the project's server secret key. 3. The proxy returns the matching ID lists for those IDs, limited to the lists available to that key. 4. The builder attaches the memberships to a standard SDK user. Your application passes that user to its usual evaluation methods. Gate, config, experiment, and layer evaluation intentionally stays synchronous and entirely compute-bound. Resolving memberships beforehand avoids network I/O and additional expensive operations across language bindings during evaluation. This separation keeps evaluation performance predictable. Config-spec fetching and event delivery keep their normal SDK lifecycles, separate from enrichment. ## Membership snapshots and freshness An enriched user holds a snapshot of memberships from the enrichment request. Reuse that user across evaluations without another network request. Existing enriched users don't update automatically; build a new enriched user when you need refreshed memberships. ID list changes take time to synchronize. A user newly added to an ID list may still appear as a non-member. A user removed from an ID list may remain a member until synchronization completes. A successful lookup doesn't guarantee that the memberships reflect the latest list changes. ## Handle enrichment failures A successful lookup can return no memberships. An enrichment failure, such as a timeout or unavailable proxy, means the builder couldn't determine memberships and returns no user. Choose your application's response to a failed build explicitly. Substituting empty memberships or an unenriched user can make targeting treat the user as a non-member. Config-spec fallback to the Statsig API doesn't recover enrichment failures. ================================================================================ # Console API Overview URL: https://docs.statsig.com/console-api/introduction ================================================================================ # Console API Overview The Console API is the CRUD API for performing the actions available on console.statsig.com without using the web UI. If you have feature requests, post them in the [Slack channel](https://www.statsig.com/slack). ## Base URL `https://statsigapi.net` ## Authorization All requests must include a Console API key in the `STATSIG-API-KEY` header. Create a key in [Project Settings](https://console.statsig.com/api_keys). ## Rate limiting The Console API rate limits mutation requests (`POST`, `PATCH`, `PUT`, and `DELETE`). Most mutation endpoints share a quota per project across all Console API keys. The default quota is approximately 1,800 request attempts per 15-minute window. Limits can vary by project and endpoint. Segment endpoints use a separate quota. Statsig also applies burst protection. A burst of requests can trigger rate limiting even when your project is below its 15-minute quota. Spread requests over time and limit concurrent requests. The API returns `429 Too Many Requests` when a request exceeds either limit. Attempts rejected by this rate limiter also count toward the quota, so immediate retries can consume additional capacity. When you receive a `429` response: - Reduce request concurrency. - Retry with exponential backoff and jitter: increase the delay after each retry and add a random delay to avoid simultaneous retries. - Limit the number of retries to avoid repeatedly consuming your quota. Contact [Statsig support](https://www.statsig.com/slack) to confirm your project's limits or discuss higher-volume requirements. ## API version Statsig versions the Console API. Statsig guarantees that each version won't break existing usage; each new version introduces breaking changes. There is only one version: `20240601`. Statsig keeps the [OpenAPI spec](https://api.statsig.com/openapi/20240601.json) for this API version up-to-date. Pass the version in the `STATSIG-API-VERSION` field in the header. This field is optional but becomes required in the future. ================================================================================ # Create Topline Alert URL: https://docs.statsig.com/api-reference/alerts/create-topline-alert ================================================================================ # Create Topline Alert ## Create Topline Alert **POST** `/console/v1/alerts` Full URL: `https://statsigapi.net/console/v1/alerts` Create Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Name of the alert (4-100 characters) Constraints: min length: 4, max length: 100 | | message | string | No | — | Alert message shown when the alert fires | | teamID | string | No | — | ID of the team that owns this alert | | formula | string | No | — | Formula expression combining the alert metrics | | definitionMetricsJson | string[] | No | — | JSON-encoded metric definitions evaluated by the alert. Each entry is a stringified ToplineAlertMExDefinitionOrUnresolved. | | groupBys | object[] | No | — | Properties to group the alert metrics by | | groupBys.column | string | Yes | — | Property column to group by | | groupBys.key | string | Yes | — | Property key to group by | | tags | object[] | No | — | Tags to attach to the alert on creation | | tags.id | string | Yes | — | ID of the tag | | tags.name | string | Yes | — | Name of the tag | ## Response (application/json) **201** — Create Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | data.status | string | Yes | — | Current evaluation status of the alert Constraints: nullable Allowed values: alert, setup_incomplete, stable, warn | | data.lastTriggeredTime | number | Yes | — | Timestamp in milliseconds of the last time this alert triggered Constraints: format: double, nullable | | data.activeMuteSchedules | object[] | Yes | — | Active v2 mute schedules for this alert, for use as currentSchedule when remuting | | data.activeMuteSchedules.start | number | Yes | — | Mute schedule start timestamp in seconds | | data.activeMuteSchedules.end | number | Yes | — | Mute schedule end timestamp in seconds (0 means indefinite) | | data.activeMuteSchedules.groupBys | object[] | Yes | — | Group-by values covered by this mute schedule (empty means whole alert) | | data.activeMuteSchedules.groupBys.key | string | Yes | — | Group-by property key | | data.activeMuteSchedules.groupBys.value | string | Yes | — | Group-by value to mute | ```json { "message": "string", "data": { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ], "status": "alert", "lastTriggeredTime": 0, "activeMuteSchedules": [ { "start": 0, "end": 0, "groupBys": [ { "key": "string", "value": "string" } ] } ] } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/alerts" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/alerts", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/alerts", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Topline Alert URL: https://docs.statsig.com/api-reference/alerts/delete-topline-alert ================================================================================ # Delete Topline Alert ## Delete Topline Alert **DELETE** `/console/v1/alerts/{id}` Full URL: `https://statsigapi.net/console/v1/alerts/{id}` Delete Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Alert deleted successfully." } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/alerts/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/alerts/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/alerts/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Topline Alert Events URL: https://docs.statsig.com/api-reference/alerts/list-topline-alert-events ================================================================================ # List Topline Alert Events ## List Topline Alert Events **GET** `/console/v1/alerts/{id}/events` Full URL: `https://statsigapi.net/console/v1/alerts/{id}/events` List Topline Alert Events ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Alert Events success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | ID of the alert event | | data.eventType | string | Yes | — | Type of alert event Allowed values: raise, warn, resolve, no-data | | data.title | string | Yes | — | Title of the alert event | | data.message | string | Yes | — | Message for the alert event | | data.reason | string | Yes | — | Reason the event was created | | data.createdTime | number | Yes | — | Timestamp in milliseconds when the event was created Constraints: format: double | | data.evaluationWindowStartTimestamp | number | No | — | Timestamp in milliseconds for the start of the evaluated alert window Constraints: format: double | | data.evaluationWindowEndTimestamp | number | No | — | Timestamp in milliseconds for the end of the evaluated alert window Constraints: format: double | | data.multiAlertGroupBys | object | Yes | — | Group-by values associated with this event | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "eventType": "raise", "title": "string", "message": "string", "reason": "string", "createdTime": 0, "evaluationWindowStartTimestamp": 0, "evaluationWindowEndTimestamp": 0, "multiAlertGroupBys": {} } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}/events?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Topline Alerts URL: https://docs.statsig.com/api-reference/alerts/list-topline-alerts ================================================================================ # List Topline Alerts ## List Topline Alerts **GET** `/console/v1/alerts` Full URL: `https://statsigapi.net/console/v1/alerts` List Topline Alerts ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Alerts success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ] } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/alerts?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/alerts?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/alerts?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Mute Topline Alert URL: https://docs.statsig.com/api-reference/alerts/mute-topline-alert ================================================================================ # Mute Topline Alert ## Mute Topline Alert **POST** `/console/v1/alerts/{id}/mute` Full URL: `https://statsigapi.net/console/v1/alerts/{id}/mute` Mute Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | indefinite | boolean | No | — | Mute the alert indefinitely until manually unmuted | | durationSeconds | integer | No | — | Mute duration in whole seconds Constraints: format: int64, min: 0 | | groupBys | object[] | No | — | Mute only alert evaluations matching these group-by values. Omit to mute the entire alert. | | groupBys.key | string | Yes | — | Group-by property key | | groupBys.value | string | Yes | — | Group-by value to mute | | currentSchedule | object | No | — | Existing mute schedule to replace. Omit to update a mute that matches groupBys; use GET /alerts/:id activeMuteSchedules to discover values. Constraints: nullable | | currentSchedule.start | number | Yes | — | Start timestamp in seconds for the schedule being replaced (matches GraphQL mute schedule format) Constraints: format: double | | currentSchedule.end | number | Yes | — | End timestamp in seconds for the schedule being replaced (0 means indefinite) Constraints: format: double | | currentSchedule.groupBys | object[] | Yes | — | Group-by values for the schedule being replaced (required to update a grouped mute) | | currentSchedule.groupBys.key | string | Yes | — | Group-by property key | | currentSchedule.groupBys.value | string | Yes | — | Group-by value to mute | ## Response (application/json) **200** — Mute Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | data.status | string | Yes | — | Current evaluation status of the alert Constraints: nullable Allowed values: alert, setup_incomplete, stable, warn | | data.lastTriggeredTime | number | Yes | — | Timestamp in milliseconds of the last time this alert triggered Constraints: format: double, nullable | | data.activeMuteSchedules | object[] | Yes | — | Active v2 mute schedules for this alert, for use as currentSchedule when remuting | | data.activeMuteSchedules.start | number | Yes | — | Mute schedule start timestamp in seconds | | data.activeMuteSchedules.end | number | Yes | — | Mute schedule end timestamp in seconds (0 means indefinite) | | data.activeMuteSchedules.groupBys | object[] | Yes | — | Group-by values covered by this mute schedule (empty means whole alert) | | data.activeMuteSchedules.groupBys.key | string | Yes | — | Group-by property key | | data.activeMuteSchedules.groupBys.value | string | Yes | — | Group-by value to mute | ```json { "message": "string", "data": { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ], "status": "alert", "lastTriggeredTime": 0, "activeMuteSchedules": [ { "start": 0, "end": 0, "groupBys": [ { "key": "string", "value": "string" } ] } ] } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/alerts/{id}/mute" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/alerts/{id}/mute", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}/mute", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}/mute"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/alerts/{id}/mute", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}/mute")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}/mute") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Topline Alert URL: https://docs.statsig.com/api-reference/alerts/read-topline-alert ================================================================================ # Read Topline Alert ## Read Topline Alert **GET** `/console/v1/alerts/{id}` Full URL: `https://statsigapi.net/console/v1/alerts/{id}` Read Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Read Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | data.status | string | Yes | — | Current evaluation status of the alert Constraints: nullable Allowed values: alert, setup_incomplete, stable, warn | | data.lastTriggeredTime | number | Yes | — | Timestamp in milliseconds of the last time this alert triggered Constraints: format: double, nullable | | data.activeMuteSchedules | object[] | Yes | — | Active v2 mute schedules for this alert, for use as currentSchedule when remuting | | data.activeMuteSchedules.start | number | Yes | — | Mute schedule start timestamp in seconds | | data.activeMuteSchedules.end | number | Yes | — | Mute schedule end timestamp in seconds (0 means indefinite) | | data.activeMuteSchedules.groupBys | object[] | Yes | — | Group-by values covered by this mute schedule (empty means whole alert) | | data.activeMuteSchedules.groupBys.key | string | Yes | — | Group-by property key | | data.activeMuteSchedules.groupBys.value | string | Yes | — | Group-by value to mute | ```json { "message": "string", "data": { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ], "status": "alert", "lastTriggeredTime": 0, "activeMuteSchedules": [ { "start": 0, "end": 0, "groupBys": [ { "key": "string", "value": "string" } ] } ] } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/alerts/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/alerts/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/alerts/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Topline Alert Event URL: https://docs.statsig.com/api-reference/alerts/read-topline-alert-event ================================================================================ # Read Topline Alert Event ## Read Topline Alert Event **GET** `/console/v1/alerts/{id}/events/{eventId}` Full URL: `https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}` Read Topline Alert Event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | | eventId (path) | string | Yes | — | alert event id | ## Response (application/json) **200** — Read Alert Event success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert event | | data.eventType | string | Yes | — | Type of alert event Allowed values: raise, warn, resolve, no-data | | data.title | string | Yes | — | Title of the alert event | | data.message | string | Yes | — | Message for the alert event | | data.reason | string | Yes | — | Reason the event was created | | data.createdTime | number | Yes | — | Timestamp in milliseconds when the event was created Constraints: format: double | | data.evaluationWindowStartTimestamp | number | No | — | Timestamp in milliseconds for the start of the evaluated alert window Constraints: format: double | | data.evaluationWindowEndTimestamp | number | No | — | Timestamp in milliseconds for the end of the evaluated alert window Constraints: format: double | | data.multiAlertGroupBys | object | Yes | — | Group-by values associated with this event | ```json { "message": "string", "data": { "id": "string", "eventType": "raise", "title": "string", "message": "string", "reason": "string", "createdTime": 0, "evaluationWindowStartTimestamp": 0, "evaluationWindowEndTimestamp": 0, "multiAlertGroupBys": {} } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}/events/{eventId}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Unmute Topline Alert URL: https://docs.statsig.com/api-reference/alerts/unmute-topline-alert ================================================================================ # Unmute Topline Alert ## Unmute Topline Alert **POST** `/console/v1/alerts/{id}/unmute` Full URL: `https://statsigapi.net/console/v1/alerts/{id}/unmute` Unmute Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | groupBys | object[] | No | — | Unmute only alert evaluations matching these group-by values. Omit to unmute the entire alert. | | groupBys.key | string | Yes | — | Group-by property key | | groupBys.value | string | Yes | — | Group-by value to mute | | currentSchedule | object | No | — | Existing mute schedule to clear. Omit to clear a mute that matches groupBys; use GET /alerts/:id activeMuteSchedules to discover values. Constraints: nullable | | currentSchedule.start | number | Yes | — | Start timestamp in seconds for the schedule being replaced (matches GraphQL mute schedule format) Constraints: format: double | | currentSchedule.end | number | Yes | — | End timestamp in seconds for the schedule being replaced (0 means indefinite) Constraints: format: double | | currentSchedule.groupBys | object[] | Yes | — | Group-by values for the schedule being replaced (required to update a grouped mute) | | currentSchedule.groupBys.key | string | Yes | — | Group-by property key | | currentSchedule.groupBys.value | string | Yes | — | Group-by value to mute | ## Response (application/json) **200** — Unmute Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | data.status | string | Yes | — | Current evaluation status of the alert Constraints: nullable Allowed values: alert, setup_incomplete, stable, warn | | data.lastTriggeredTime | number | Yes | — | Timestamp in milliseconds of the last time this alert triggered Constraints: format: double, nullable | | data.activeMuteSchedules | object[] | Yes | — | Active v2 mute schedules for this alert, for use as currentSchedule when remuting | | data.activeMuteSchedules.start | number | Yes | — | Mute schedule start timestamp in seconds | | data.activeMuteSchedules.end | number | Yes | — | Mute schedule end timestamp in seconds (0 means indefinite) | | data.activeMuteSchedules.groupBys | object[] | Yes | — | Group-by values covered by this mute schedule (empty means whole alert) | | data.activeMuteSchedules.groupBys.key | string | Yes | — | Group-by property key | | data.activeMuteSchedules.groupBys.value | string | Yes | — | Group-by value to mute | ```json { "message": "string", "data": { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ], "status": "alert", "lastTriggeredTime": 0, "activeMuteSchedules": [ { "start": 0, "end": 0, "groupBys": [ { "key": "string", "value": "string" } ] } ] } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/alerts/{id}/unmute" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/alerts/{id}/unmute", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}/unmute", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}/unmute"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/alerts/{id}/unmute", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}/unmute")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}/unmute") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Topline Alert URL: https://docs.statsig.com/api-reference/alerts/update-topline-alert ================================================================================ # Update Topline Alert ## Update Topline Alert **PATCH** `/console/v1/alerts/{id}` Full URL: `https://statsigapi.net/console/v1/alerts/{id}` Update Topline Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Name of the alert (4-100 characters) Constraints: min length: 4, max length: 100 | | message | string | No | — | Alert message shown when the alert fires | | alertThreshold | number | No | — | Threshold value that triggers the alert Constraints: format: double | | warningThreshold | number | No | — | Optional warning threshold value. Pass null to clear. Constraints: format: double, nullable | | formula | string | No | — | Formula expression. Pass null to clear. Constraints: nullable | | windowMs | number | No | — | How far back and how frequently a metric should be checked, in milliseconds. Must be between 60_000 and 30 days. Constraints: format: double, min: 60000, max: 2592000000 | | condition | string | No | — | Condition under which a metric change triggers an alert Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | priority | string | No | — | Alert priority Allowed values: P1, P2, P3, P4 | | renotificationConditions | string[] | No | — | Conditions under which a re-notification is sent. Pass null to clear. Constraints: nullable | | renotificationWindowMs | number | No | — | How long to wait before re-notifying, in ms Constraints: format: double | | evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Pass 0 to clear. Constraints: format: double, min: 0, max: 2592000000 | | renotificationMessage | string | No | — | Re-notification message | | teamID | string | No | — | ID of the team that owns this alert. Pass null to clear. Constraints: nullable | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | definitionMetricsJson | string[] | No | — | JSON-encoded metric definitions evaluated by the alert. Each entry is a stringified ToplineAlertMExDefinitionOrUnresolved. When omitted, existing definitions are preserved. Pass an empty array to clear all metrics. | | groupBys | object[] | No | — | Properties to group the alert metrics by. When omitted, existing group-bys are preserved. Pass an empty array to clear all group-bys. | | groupBys.column | string | Yes | — | Property column to group by | | groupBys.key | string | Yes | — | Property key to group by | | tags | string[] | No | — | Tags to attach to the alert. When omitted, existing tags are preserved. Pass an empty array to clear all tags. | | subscribers | object[] | No | — | Replace typed subscribersV2 targets (Slack/PagerDuty). When omitted, existing typed subscribers are preserved. Pass an empty array to clear. Does not modify the legacy member-subscriber edge. | | subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | ## Response (application/json) **200** — Update Alert success response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID of the alert | | data.name | string | Yes | — | Name of the alert | | data.alertType | string | Yes | — | Type of alert Allowed values: threshold, change, pct_change | | data.metrics | object | Yes | — | List of metrics associated with this alert | | data.metricGroupBys | object | Yes | — | Metric groupbys | | data.formula | string | No | — | Formula for the alert | | data.message | string | Yes | — | Alert message | | data.creatorID | string | No | — | — | | data.companyID | string | Yes | — | — | | data.priority | string | Yes | — | Priority of this alert Allowed values: P0, P1, P2, P3, P4, P5 | | data.alertThreshold | number | Yes | — | Constraints: format: double | | data.warningThreshold | number | No | — | Constraints: format: double | | data.windowMs | number | Yes | — | How far back and how frequently a metric should be checked, in milliseconds Constraints: format: double | | data.evaluationDelayMs | number | No | — | Delay before evaluating metrics, in milliseconds. Use 0 or null to clear. Constraints: format: double, nullable | | data.condition | string | Yes | — | Condition under which a metric change triggers an alert in milliseconds Allowed values: greater, greater_or_equal, less, less_or_equal, equal, not_equal | | data.renotificationConditions | string[] | No | — | Condition under which a re-notification is sent | | data.renotificationWindowMs | number | No | — | How long to wait before re-notifying in milliseconds Constraints: format: double | | data.renotificationMessage | string | No | — | Re-notification message | | data.team | string | No | — | Team associated with this alert Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.tags | string[] | Yes | — | Tags associated with this alert | | data.subscribers | object[] | Yes | — | Typed notification targets (subscribersV2): Slack channels and PagerDuty services used by direct alerty paging. Distinct from the legacy console member-subscriber edge (email/Slack DM), which CAPI does not expose. | | data.subscribers.type | string | Yes | — | Typed integration subscriber kind (entity subscribersV2). pagerDutyService ids come from the company PagerDuty integration. pagerDutyOncall is legacy/inert. type=user here is a typed row only — it is not the legacy member email/Slack-DM subscriber edge. Allowed values: user, slackChannel, pagerDutyOncall, pagerDutyService | | data.subscribers.id | string | Yes | — | Subscriber id (user id, Slack channel id, or PagerDuty service id). For pagerDutyService this is the integration services[].id, not a routing key. | | data.status | string | Yes | — | Current evaluation status of the alert Constraints: nullable Allowed values: alert, setup_incomplete, stable, warn | | data.lastTriggeredTime | number | Yes | — | Timestamp in milliseconds of the last time this alert triggered Constraints: format: double, nullable | | data.activeMuteSchedules | object[] | Yes | — | Active v2 mute schedules for this alert, for use as currentSchedule when remuting | | data.activeMuteSchedules.start | number | Yes | — | Mute schedule start timestamp in seconds | | data.activeMuteSchedules.end | number | Yes | — | Mute schedule end timestamp in seconds (0 means indefinite) | | data.activeMuteSchedules.groupBys | object[] | Yes | — | Group-by values covered by this mute schedule (empty means whole alert) | | data.activeMuteSchedules.groupBys.key | string | Yes | — | Group-by property key | | data.activeMuteSchedules.groupBys.value | string | Yes | — | Group-by value to mute | ```json { "message": "string", "data": { "id": "string", "name": "string", "alertType": "threshold", "metrics": {}, "metricGroupBys": {}, "formula": "string", "message": "string", "creatorID": "string", "companyID": "string", "priority": "P0", "alertThreshold": 0, "warningThreshold": 0, "windowMs": 0, "evaluationDelayMs": 0, "condition": "greater", "renotificationConditions": [ "raise" ], "renotificationWindowMs": 0, "renotificationMessage": "string", "team": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "tags": [ "string" ], "subscribers": [ { "type": "user", "id": "string" } ], "status": "alert", "lastTriggeredTime": 0, "activeMuteSchedules": [ { "start": 0, "end": 0, "groupBys": [ { "key": "string", "value": "string" } ] } ] } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Alert not found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/alerts/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/alerts/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/alerts/{id}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/alerts/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/alerts/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/alerts/{id}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/alerts/{id}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Audit Logs URL: https://docs.statsig.com/api-reference/audit-logs/list-audit-logs ================================================================================ # List Audit Logs ## List Audit Logs **GET** `/console/v1/audit_logs` Full URL: `https://statsigapi.net/console/v1/audit_logs` List Audit Logs ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (query) | string | No | — | — | | sortKey (query) | string | No | — | Allowed values: id, name, changeLog, actionType, date, time, updatedBy, updatedByUserID | | sortOrder (query) | string | No | — | Allowed values: asc, desc | | latestID (query) | string | No | — | — | | tags (query) | oneOf | No | — | Constraints: string, string[] | | actionType (query) | string | No | — | Allowed values: update_shared_control, create_shared_control_treatment, setup_shared_control, mcp_ema_sign_in, delete_sandbox_profile_build, delete_sandbox_profile, save_and_build_sandbox_profile, set_company_api_review_bypass, set_company_mcp_access, delete_scim_group_alias, create_scim_group_alias, create_amplitude_web_experiment, set_amplitude_experiment_config, create_metric_source_import_job, setup_databricks_script_job_integration, stop_partial_pause_experiment, partial_pause_experiment, change_cloud_paired_experiment_hidden_state, cancel_mex_query, bulk_add_remove_configs_from_tag, create_paired_experiment, delete_dashboard_subscription, update_dashboard_subscriptions, add_dashboard_page, generate_dashboard_screenshot_url, delete_echidna_table_config, update_default_company_metrics, rate_sidekick_message, rename_offline_aa_report, rate_investigation_response, set_ai_dataset_global, set_ai_scheduled_runs, load_power_analysis_results_whn, create_offline_aa_report, set_warehouse_metadata_indexing_enabled, update_primary_attached_report, delete_ai_eval, delete_ai_dataset, upsert_traces_tag, create_traces_tag, upsert_traces_metadata, delete_ai_eval_run, create_ai_eval_run, create_ai_eval, refresh_warehouse_explorer_table_info, edit_experiment_scheduled_start, edit_experiment_scheduled_stop, edit_ai_config_agent_version, update_ai_dataset, upload_ai_config_dataset_csv, resalt_experiment, run_eval_from_traces, edit_ai_config_auto_eval_state, edit_ai_config_eval_settings, update_grader_advisor_cache, set_ai_grader_global, edit_ai_playground, save_ai_playground_results, delete_ai_config, set_suggest_cure_covariates, edit_ai_playground_setup, start_ai_config_version_evaluation_job, start_ai_playground_completion_job, stop_ai_config_version_evaluation_job, clone_ai_config, edit_ai_config_version, delete_ai_config_version, delete_ai_config_versions, clone_ai_config_version, ai_config_create, create_ai_config_experiment, ai_playground_create, create_ai_dataset, create_ai_config_version, create_ai_config_agent_version, upsert_ai_config_version, create_ai_config_eval_grader, edit_ai_config_eval_grader, delete_ai_config_eval_grader, set_enable_id_resolution_toggle, dynamic_config_create, dynamic_config_template_create, dynamic_config_update_owners, gate_overrides_update, gate_template_create, gate_create, gate_update, set_user_sampling_rate_for_gate, gate_update_owners, update_store_0_100_exposures, update_gate_analytics_enabled, update_gate_display_name, release_pipeline_create, release_pipeline_update, release_pipeline_delete, update_config_release_pipeline, release_pipeline_trigger_create, release_pipeline_trigger_paused, release_pipeline_trigger_unpaused, release_pipeline_trigger_approved, release_pipeline_trigger_aborted, release_pipeline_trigger_phase_skipped, apply_experiment_review, apply_autotune_review, extend_experiment_pulse_end_date, restart_experiment_pulse, autotune_experiment_create, autotune_experiment_delete, autotune_experiment_snapshot_delete, autotune_experiment_edit, autotune_experiment_update_target_apps, autotune_experiment_update_pulse_paused, autotune_overrides_edit, autotune_reviews_on, autotune_allowed_reviewers_update, autotune_update_owners, autotune_review_create, autotune_review_reject, autotune_review_accept, autotune_review_delete, autotune_review_info_update, autotune_review_update_team, autotune_review_update_owners, experiment_data_report_delete, offline_aa_report_delete, experiment_discussion_post_create, experiment_discussion_post_delete, experiment_abandon, experiment_pause_assignment, experiment_stopped, experiment_review_accept, experiment_review_reject, experiment_template_create, update_template_decision_framework, update_experiment_echidna_assignment_source, remove_template_decision_framework, experiment_create, experiment_review_create, experiment_delete, experiment_review_delete, experiment_review_update_team, experiment_snapshot_delete, experiment_group_disable, experiment_description_edit, experiment_display_name_edit, experiment_edit, experiment_overrides_edit, hypothesis_edit, key_experiment_metrics_edit, experiment_advanced_settings_edit, set_experiment_default_impact_multiplier, experiment_decision_make, experiment_restart, experiment_restart_as_new, experiment_rollout, experiment_schedule_rollout, experiment_reviews_on, experiment_start, schedule_experiment_start, schedule_experiment_stop, set_experiment_schedule, schedule_autotune_start, experiment_follow_toggle, experiment_allowed_reviewers_update, experiment_review_info_update, update_experiment_enabled_non_prod_environments, archive_experiment, unarchive_experiment, experiment_update_owners, update_echidna_subtype, setup_stratified_sampling, experiment_update_target_apps, experiment_update_subdimension_filter, experiment_review_update_overrides, experiment_review_update_owners, experiment_update_decision_note, experiment_update_summary_sections, unattach_experiment_to_power_analysis_report, attach_experiment_to_power_analysis_report, pin_chart_to_summary, set_geotest_design, delete_geotest_design, create_geotest_design, experiment_assigned_to_layer, holdout_create, holdout_delete, holdout_layer_parameter_values_update, holdout_update, holdout_update_owners, metric_edit_definition, metric_edit_description, metric_add_tag, metric_remove_tag, schedule_delete_metric, schedule_archive_metric, update_metric_is_permanent, update_metric_is_verified, metric_reviews_on, metric_disable_reviews_locally, custom_metric_definition_edit, custom_metric_definition_create, custom_metric_definition_delete, custom_metric_update_owners, tag_metrics_bulk, tag_create, tag_delete, tag_edit, segment_create, segment_update_owners, layer_update_owners, layer_review_commit, layer_review_accept, layer_parameter_add, layer_create, layer_review_create, layer_review_delete, layer_delete, layer_snapshot_delete, layer_description_edit, layer_edit, layer_overrides_edit, layer_parameters_edit, layer_review_reject, layer_allowed_reviewers_update, layer_review_info_update, layer_update_target_apps, delete_layer_parameter, update_layer_parameter, config_review_accept, config_review_commit, config_review_create, config_delete, config_review_delete, config_reviews_disable, config_review_reject, config_resalt, config_revert, config_require_reviews, config_state_toggle, config_allowed_reviewers_update, config_conditions_update, config_default_value_update, config_description_update, config_display_name_update, config_environments_update, config_review_info_update, config_review_update, config_review_required_update, config_add_tag, config_edit_tags, config_remove_tag, config_monitoring_metrics_update, config_edit_target_apps, update_config_analytics_enabled, set_self_approvals_blocked, release_pipeline_completed, release_pipeline_waiting_for_review, pin_dashboard_for_company, add_dashboard_widget, create_dashboard, delete_dashboard_widget, edit_dashboard_widget, delete_dashboard, edit_dashboard_description, edit_dashboard_name, restore_dashboard, update_dashboard_widgets_from_generated_tags, dashboard_update_owners, update_dashboard_settings, create_topline_alert, update_topline_alert, delete_topline_alert, topline_alert_update_owners, active_user_definition_update, company_create, company_metric_management_update, metric_allowed_reviewers_update, metric_review_commit, metric_review_create, metric_review_info_update, set_metric_directionality, set_metric_default_impact_multiplier, custom_metric_edit, custom_metric_name_edit, custom_metric_review_accept, custom_metric_review_delete, custom_metric_review_reject, delete_metric, archive_metric, unarchive_metric, cancel_delete_metric, cancel_archive_metric, edit_guardrail_metric_alert, create_guardrail_metric_alert, delete_guardrail_metric_alert, resolve_guardrail_metric_alert, unsnooze_guardrail_metric_alert, update_echidna_metric_loading_window, update_metric_review_required, layer_reviews_on, set_layer_self_approvals_blocked, delete_tag, ID_list_update, update_gate_is_permanent, update_dynamic_config_is_permanent, set_config_auto_archive_state, load_echidna_metric, batch_load_echidna_topline_impact, load_echidna_metric_async_batch, update_server_sdk_configuration_rollback, company_ID_type_add, organization_user_invite, join_org_project, request_join_org_project, join_org_project_scim, company_user_invite, update_echidna_source_review_required, AWS_marketplace_account_delete, batch_cancel_company_invites, company_invite_accept, batch_user_role_update, company_invite_decline, company_basic_info_edit, company_delete, company_email_domain_config_delete, company_environments_edit, add_geo_type, delete_geo_type, company_ID_type_delete, company_ID_type_edit, company_invite_access_update, update_entities_require_teams, update_company_user_store_enabled, company_member_remove, company_metric_delete, company_snapshot_delete, config_id_type_update, config_update_owners, create_customer_app, edit_target_app, delete_target_app, source_allowed_reviewers_update, create_echidna_assignment_source, create_echidna_entity_property_source, create_echidna_metric_source, create_echidna_data_quality_checks, create_echidna_source_review, accept_echidna_source_review, commit_echidna_source_review, reject_echidna_source_review, update_echidna_source_review, delete_echidna_source_review, create_power_analysis_gate_query, create_power_analysis_custom_query, custom_pulse_query_create, custom_pulse_query_delete, custom_pulse_query_name_edit, custom_query_toggle_favorite, custom_sankey_delete, delete_echidna_assignment_source, delete_echidna_entity_property_source, delete_echidna_metric_source, archive_echidna_metric_source, unarchive_echidna_metric_source, delete_payment_method, tag_update_owners, modify_override_config, modify_overrides, remove_override_config, scheduled_custom_pulse_query_create, integration_delete, integration_create, integration_requested, integration_update, scheduled_pulse_custom_query_delete, scheduled_pulse_query_name_edit, user_data_load, organization_member_remove, shared_report_link_upsert, scheduled_pulse_rollups_update, OIDC_configuration_delete, project_review_group_delete, SSO_disable, project_description_edit, project_owner_set, user_role_update, OIDC_configuration_upsert, payment_entitlements_upsert, project_review_group_upsert, project_review_group_remove, update_team_settings, update_team_admins, update_team_name, update_team_description, update_team, shared_report_link_delete, experiment_data_report_rename, experiment_data_report_update_parameters, event_dimension_update, integration_set_enabled, integration_update_disabled_events, integration_update_outgoing_config, integration_update_rate_limits, integration_upsert, ingestion_source_delete, tag_configs_bulk, org_api_key_create, set_personal_api_key_access, sdk_key_create, sdk_key_rotate, sdk_key_deactivate, sdk_key_delete, secret_key_regenerate, sdk_key_update_description, set_api_share_key_access, set_plan_type, generate_integration_webhook_secret, set_default_payment_method, set_user_sampling_rate, sdk_key_update_environments, upsert_trigger_integration, delete_trigger_integration, dismiss_runaway_entity, update_echidna_metric_source, update_echidna_metric_source_name, update_echidna_metric_tag_or_description, update_echidna_assignment_source, update_echidna_assignment_source_name, update_echidna_assignment_source_loading_window, update_echidna_entity_property_source, update_echidna_entity_property_source_name, update_echidna_source_owner, update_precommit_hook, load_echidna_pulse, load_echidna_autotune_pulse, load_echidna_assignment_source, set_echidna_schedule_hour, echidna_drop_tables, upsert_user_role, delete_user_role, sdk_key_update_target_app, set_gate_analytics_enabled_by_default, set_dynamic_config_analytics_enabled_by_default, set_gate_analytics_0_100_exposures_enabled, update_bv3_subscription, upsert_experiment_settings, upsert_gate_settings, sdk_key_update_review_bypass, sdk_key_update_scopes, user_login, param_store_create, param_store_update, set_bv3_plan_type, set_echidna_project_pulse_schedule, set_echidna_project_metric_schedule, set_company_default_user_role, set_company_session_replay_sampling_rate, set_company_session_replay_settings, cancel_echidna_dag, set_require_target_app_for_new_entity, set_default_target_apps_for_new_entity, add_segments_of_interest_property, delete_segments_of_interest_property, add_srm_debugger_custom_dimension, delete_srm_debugger_custom_dimension, param_store_delete, param_store_update_owners, create_statsig_proxy, update_echidna_assignment_source_is_verified, update_echidna_metric_source_is_verified, update_echidna_entity_property_source_is_verified, update_echidna_source_is_verified, set_automated_bot_removals, pulse_results_export, update_company_auto_capture_settings, update_company_experiment_exclusion_segment, set_stop_new_assignment_toggle, set_stop_experiment_enabled, update_company_remove_default_gates_setting, set_whn_results_export_setting, update_experiment_quality_score_settings, update_default_bayesian_prior_settings, update_experiment_salt, update_precommit_webhook_key, set_whn_table_ttls, set_id_resolution_inferred_id, set_id_resolution_labeled_id, add_session_recordings_to_playlist, delete_session_recordings_from_playlist, delete_session_replay_playlist, backfill_metric_results, cancel_metric_backfills, configure_organization_mcp_ema, archive_org_project, update_ai_assistance_enabled, update_ai_business_context, update_experiment_ai_settings, update_experiment_ai_advisor_settings, update_ai_config_ai_advisor_settings, upsert_ai_config_eval_groups, edit_ai_config_targeting_rules, upsert_user_store_client_targeting_properties, set_ai_config_baseline_version, verify_dashboard, set_first_exposure_user_store_default, scheduled_rollout_template_create, scheduled_rollout_template_update, scheduled_rollout_template_delete, set_ai_provider_api_keys, experiment_schedule_allocation_change, experiment_rollout_allocation_change, gate_stale_status_update, dynamic_config_stale_status_update, rollout_plan_create, rollout_plan_update, rollout_plan_delete, experiment_partial_pause_assignment, experiment_stop_partial_pause_assignment, experiment_update_partial_pause_assignment, update_experiment_quality_score_criteria, setup_external_opt_in | | actionTypes (query) | oneOf | No | — | Constraints: string, string[] | | startDate (query) | string | No | 2024-01-01 | Expected valid date in the form of YYYY-MM-DD. Defaults to 90 days before endDate. If both dates are omitted, the endpoint searches the last 90 days. | | endDate (query) | string | No | 2024-01-01 | Expected valid date in the form of YYYY-MM-DD. Defaults to today. If both dates are omitted, the endpoint searches the last 90 days. | | startTime (query) | integer | No | 1736208000000 | Expected Unix timestamp in milliseconds. Searches within the provided date range, or the endpoint default date range when no date range is specified, and further filters to the specified time range. When both startTime and endTime are provided, the time range must be less than 7 days. Useful for identifying changes during a specific period of interest, especially across all configs. Constraints: string (pattern: ^\d+$), integer (min: 0) | | endTime (query) | integer | No | 1736208000000 | Expected Unix timestamp in milliseconds. Searches within the provided date range, or the endpoint default date range when no date range is specified, and further filters to the specified time range. When both startTime and endTime are provided, the time range must be less than 7 days. Useful for identifying changes during a specific period of interest, especially across all configs. Constraints: string (pattern: ^\d+$), integer (min: 0) | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — Audit logs listed successfully. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | abc123 | id of the audit log | | data.name | string | Yes | Gate View | name of the audit log | | data.changeLog | string | Yes | Edited Gate View | change log of the audit log | | data.actionType | string | Yes | gate_update | type of action performed Constraints: nullable | | data.date | string | Yes | — | — | | data.time | string | Yes | — | — | | data.updatedBy | string | Yes | — | — | | data.updatedByUserID | string | Yes | — | — | | data.modifierEmail | string | Yes | user@example.com | email of the user who made the modification Constraints: nullable | | data.changes | object | Yes | — | — | | data.tags | string[] | Yes | — | — | | data.targetAppIDs | string[] | No | — | — | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Audit logs listed successfully.", "data": [ { "id": "25KPZcLjTY7AS1uZdBolPZ", "name": "test_gate_1", "changeLog": "Created Gate", "actionType": "gate_create", "date": "Mon Sep 26 2022", "time": "23:46:14 GMT+0000 (Coordinated Universal Time)", "updatedBy": "Jane Doe", "updatedByUserID": "4eoDlYj7svJixZfDsYSn", "changes": { "rules": { "new": [ { "groupName": "test", "percentagePass": 100, "conditionJSON": [ { "conditionType": 1, "operator": 0, "value": [ "1" ], "extraConfig": {} } ], "returnValueJSON": "true", "id": "BfGswoMDcsZ4y9Le1d9O", "salt": "8df8n90p-d9bj-1l23-c9bl-1m022n9bzps8", "environment": "production", "rollouts": [], "enabledEnvironments": [ "development", "staging", "production" ] } ], "old": [ { "groupName": "test", "percentagePass": 100, "conditionJSON": [ { "conditionType": 1, "operator": 0, "value": [ "1" ], "extraConfig": {} } ], "returnValueJSON": "true", "id": "BfGswoMDcsZ4y9Le1d9O", "salt": "8df8n90p-d9bj-1l23-c9bl-1m022n9bzps8", "environment": "production", "rollouts": [], "enabledEnvironments": [ "development", "staging" ] } ] } } }, { "id": "19LZJaPtCM4GT1sUbWlqVC", "name": "check_employee", "changeLog": "Removed Tag from Config", "actionType": "config_remove_tag", "date": "Mon Sep 26 2022", "time": "21:25:22 GMT+0000 (Coordinated Universal Time)", "updatedBy": "John Doe", "updatedByUserID": "fd7dWH15Ddncvl3xhVLH", "changes": {} }, { "id": "76LGVrItCR9WE1iDfNmpHT", "name": "check_employee", "changeLog": "Removed Tag from Config", "actionType": "config_remove_tag", "date": "Mon Sep 26 2022", "time": "21:25:18 GMT+0000 (Coordinated Universal Time)", "updatedBy": "John Doe", "updatedByUserID": "fd7dWH15Ddncvl3xhVLH", "changes": {} } ], "pagination": { "itemsPerPage": 3, "pageNumber": 2, "totalItems": 829, "nextPage": "statsigapi.net/console/v1/audit_logs?page=3&limit=3", "previousPage": "statsigapi.net/console/v1/audit_logs?page=1&limit=3", "all": "statsigapi.net/console/v1/audit_logs" } } ``` **404** — Audit log not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Audit log not found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/audit_logs?startDate=2024-01-01&endDate=2024-01-01&startTime=1736208000000&endTime=1736208000000&limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Approve Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/approve-autotune-review ================================================================================ # Approve Autotune Review ## Approve Autotune Review **PUT** `/console/v1/autotunes/{id}/reviews/{reviewID}/approve` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve` Approve Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | No | — | Optional comment recorded with the approval. Constraints: max length: 2000 | ## Response (application/json) **200** — The approved autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/approve") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/cancel-autotune-review ================================================================================ # Cancel Autotune Review ## Cancel Autotune Review **DELETE** `/console/v1/autotunes/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}` Cancel Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — Cancel an in-flight autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Autotune review cancelled successfully" } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Commit Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/commit-autotune-review ================================================================================ # Commit Autotune Review ## Commit Autotune Review **PUT** `/console/v1/autotunes/{id}/reviews/{reviewID}/commit` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit` Commit Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — Commit an approved autotune review. Autotunes do not support pre-commit webhooks, so the review is applied immediately. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | — | | status | string | Yes | — | Current review status after the commit attempt. A non-final webhook status means the reviewed change was not applied. Allowed values: committed | ```json { "message": "Autotune review committed successfully", "status": "committed" } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/commit") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Autotune URL: https://docs.statsig.com/api-reference/autotunes/create-autotune ================================================================================ # Create Autotune ## Create Autotune **POST** `/console/v1/autotunes` Full URL: `https://statsigapi.net/console/v1/autotunes` Create Autotune ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | A brief summary of what the autotune is being used for. | | variants | object[] | Yes | — | An array of Variant objects. | | variants.name | string | Yes | — | Variant name | | variants.json | unknown | Yes | — | Variant JSON data | | variants.size | number | No | — | Variant size | | successEvent | string | Yes | — | The event you are trying to optimize for. | | successEventValue | string | No | — | The value that should come with the event for it to be considered successful. | | explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | isContextual | boolean | No | — | Makes this autotune contextual | | metricSourceID | string | No | — | Metric source to pull success event data from | | linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | goalRichText | string | No | — | Autotune goal | | optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | valueColumn | string | No | — | Metric source column to optimize for | | featureList | string[] | No | — | List of features that should be included in the analysis | | excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | name | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | idType | string | No | — | idType of the autotune (userID, stableID, or a customID). Defaults to userID if not provided | ## Response (application/json) **201** — Create Autotune Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.description | string | Yes | — | Detailed description of the configuration’s purpose. | | data.variants | object[] | Yes | — | — | | data.variants.name | string | Yes | — | Variant name | | data.variants.json | unknown | Yes | — | Variant JSON data | | data.variants.size | number | No | — | Variant size | | data.variants.id | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | data.successEvent | string | Yes | — | The event you are trying to optimize for. | | data.successEventValue | string | Yes | — | The value that should come with the event for it to be considered successful. | | data.explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | data.attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | data.attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | data.explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | data.longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | data.winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | data.metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | data.higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | data.isContextual | boolean | No | — | Whether this is a contextual autotune | | data.metricSourceID | string | No | — | Metric source to pull success event data from | | data.linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | data.goalRichText | string | No | — | Autotune goal | | data.optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | data.valueColumn | string | No | — | Metric source column to optimize for | | data.featureList | string[] | No | — | List of features that should be included in the analysis | | data.excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.id | string | Yes | — | ID | | data.name | string | No | — | Optional name for the configuration. | | data.idType | string | Yes | — | Type of ID | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | Yes | — | ID of the user who created the entity. Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | Yes | — | Email of the creator. Constraints: nullable | | data.tags | string[] | No | — | Optional tags for categorization. | | data.targetApps | string[] | No | — | List of target applications associated with this configuration. | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Optional name for the responsible team. Constraints: nullable | | data.teamID | string | No | — | Optional ID of the responsible team. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isStarted | boolean | Yes | — | Is the autotune experiment currently running. | | data.winner | object | Yes | — | Constraints: nullable | | data.winner.id | string | Yes | — | The Statsig ID of the winner group. | | data.winner.name | string | Yes | — | The name of the winner group. | ```json { "message": "Autotune Experiments created successfully.", "data": { "id": "button_color_test", "isStarted": false, "description": "Which color button gets the most clicks.", "lastModifierID": "ajv762klv9nx9hca", "lastModifierName": "CONSOLE API", "inlineTargetingRulesJSON": "{}", "inlineTargetingRules": [], "variants": [ { "name": "red", "json": { "color": "red" } }, { "name": "blue", "json": { "color": "blue" } } ], "successEvent": "click", "successEventValue": "", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/autotunes" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/autotunes", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/autotunes", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/create-autotune-review ================================================================================ # Create Autotune Review ## Create Autotune Review **POST** `/console/v1/autotunes/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews` Create Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | type | string | Yes | — | The kind of autotune change the review proposes. Allowed values: start, scheduled_start, scheduled_start_edit, reallocate, make_decision, delete, disable_reviews_locally | | description | string | No | — | Human-readable description of the proposed change. Optional; recorded empty when omitted. Constraints: max length: 2000 | | reviewer_ids | string[] | No | [] | User IDs to request review from. | | reviewer_group_ids | string[] | No | [] | Reviewer group IDs to request review from. | | reason | string | No | — | Optional reason recorded with the change, applied when committed (e.g. reset / decision reason). Constraints: max length: 2000 | | winning_group_id | string | No | — | For `make_decision`: the group to ship. Required. | | remove_targeting | boolean | No | — | For `make_decision`: drop targeting on ship (default false). | | remove_overrides | boolean | No | — | For `make_decision`: drop overrides on ship (default false). | | start_date | string | No | — | For `start`: optional scheduled start date. | | start_time | integer | No | — | For `scheduled_start`: epoch-ms time to schedule the start. Required. Constraints: format: int64 | | new_time | integer | No | — | For `scheduled_start_edit`: epoch-ms time to reschedule the start to. Required. Constraints: format: int64 | ## Response (application/json) **201** — The created autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/autotunes/{id}/reviews" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/autotunes/{id}/reviews", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/autotunes/{id}/reviews", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete a Single Autotune Override URL: https://docs.statsig.com/api-reference/autotunes/delete-a-single-autotune-override ================================================================================ # Delete a Single Autotune Override ## Delete a Single Autotune Override **DELETE** `/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}` Delete a Single Autotune Override Removes a single gate or segment override from the autotune. Idempotent: returns 200 even when no matching override exists. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Autotune name | | type (path) | string | Yes | — | Override type Allowed values: gate, segment | | name (path) | string | Yes | — | Name of the gate or segment being overridden | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | groupID (query) | string | Yes | — | The autotune variant name the override targets | | environment (query) | string | No | — | Environment the override is scoped to. Omit to target the override that applies to all environments. | ## Response (application/json) **200** — Delete Single Autotune Override Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "overrides": [], "userIDOverrides": [] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune or variant not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides/conditional/{type}/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete a Single Autotune User ID Override URL: https://docs.statsig.com/api-reference/autotunes/delete-a-single-autotune-user-id-override ================================================================================ # Delete a Single Autotune User ID Override ## Delete a Single Autotune User ID Override **DELETE** `/console/v1/autotunes/{id}/overrides/userID/{userID}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}` Delete a Single Autotune User ID Override Removes a single user ID from the matching userID override bucket on the autotune. Idempotent: returns 200 even when the user ID is not currently overridden. Only clears the bucket named by `groupID`, `unitType`, and `environment`; every other override bucket stays in place. The response body carries the full override set for the autotune after the delete. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Autotune name | | userID (path) | string | Yes | — | User ID to remove from the override | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | groupID (query) | string | Yes | Control | The autotune variant name the override targets | | unitType (query) | string | No | — | The unit type of the override. Defaults to the autotune unit type when omitted. | | environment (query) | string | No | — | Environment the override is scoped to. Omit to target the override that applies to all environments. | ## Response (application/json) **200** — Delete Single Autotune User ID Override Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "message": "Autotune Overrides updated successfully.", "data": { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Test", "environment": null } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "user_a" ], "environment": null, "unitType": "userID" }, { "groupID": "Control", "ids": [ "user_b" ], "environment": "staging", "unitType": "userID" }, { "groupID": "Test", "ids": [ "user_c" ], "environment": null, "unitType": "userID" } ] } } ``` **400** — `groupID` is missing. The `errors` array names the parameter that failed validation. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Bad Request Exception" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune or variant not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides/userID/{userID}?groupID=Control") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Autotune URL: https://docs.statsig.com/api-reference/autotunes/delete-autotune ================================================================================ # Delete Autotune ## Delete Autotune **DELETE** `/console/v1/autotunes/{id}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}` Delete Autotune ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Autotune Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Autotune Experiment deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The entity remains intact until the existing review workflow applies the deletion. Returns the review ID and status. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Autotune Experiment not found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/autotunes/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/autotunes/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/autotunes/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Autotune Overrides URL: https://docs.statsig.com/api-reference/autotunes/delete-autotune-overrides ================================================================================ # Delete Autotune Overrides ## Delete Autotune Overrides **DELETE** `/console/v1/autotunes/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides` Delete Autotune Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Update Autotune Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "overrides": [], "userIDOverrides": [] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/autotunes/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/autotunes/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/autotunes/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Edit Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/edit-autotune-review ================================================================================ # Edit Autotune Review ## Edit Autotune Review **PUT** `/console/v1/autotunes/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}` Edit Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | New description. Omit to keep the current value. Constraints: min length: 1, max length: 2000 | | reviewer_ids | string[] | No | — | Replacement reviewer user IDs. Omit to keep the current set. | | reviewer_group_ids | string[] | No | — | Replacement reviewer group IDs. Omit to keep the current set. | ## Response (application/json) **200** — The updated autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Finish Experiment Early URL: https://docs.statsig.com/api-reference/autotunes/finish-experiment-early ================================================================================ # Finish Experiment Early ## Finish Experiment Early **PUT** `/console/v1/autotunes/{id}/make_decision` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/make_decision` Finish Experiment Early ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id | string | Yes | groupid123 | The ID of the group to launch | | decisionReason | string | Yes | Your reason for stopping early | The reason for making the decision to update the experiment status | | removeTargeting | boolean | No | false | Indicates whether to remove targeting from the experiment | | holdout | integer | No | 10 | Integer percentage of users to hold back when shipping with holdback. Must be an integer between 0 and 50 (inclusive): the launched group size is computed as 100 - holdout * 2, so values above 50 would produce a negative-sized launched group. When set, the experiment remains live with a holdback group so long-term impact can be measured before making a final decision. Requires the ship_experiment_with_holdout gate to be enabled for the project. Constraints: format: int64, min: 0, max: 50 | ## Response (application/json) **200** — Finish Experiment Early Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Decision made for Autotune Experiment." } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Autotune experiment has not yet started" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Autotune Experiment not found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/make_decision" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }' ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/make_decision", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/make_decision", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/make_decision"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}") req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/make_decision", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/make_decision")) .method("PUT", HttpRequest.BodyPublishers.ofString("{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/make_decision") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Fully Update Autotune URL: https://docs.statsig.com/api-reference/autotunes/fully-update-autotune ================================================================================ # Fully Update Autotune ## Fully Update Autotune **POST** `/console/v1/autotunes/{id}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}` Fully Update Autotune Update all properties of the experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | A brief summary of what the autotune is being used for. | | variants | object[] | Yes | — | An array of Variant objects. | | variants.name | string | Yes | — | Variant name | | variants.json | unknown | Yes | — | Variant JSON data | | variants.size | number | No | — | Variant size | | successEvent | string | Yes | — | The event you are trying to optimize for. | | successEventValue | string | No | — | The value that should come with the event for it to be considered successful. | | explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | isContextual | boolean | No | — | Whether this is a contextual autotune | | metricSourceID | string | No | — | Metric source to pull success event data from | | linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | goalRichText | string | No | — | Autotune goal | | optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | valueColumn | string | No | — | Metric source column to optimize for | | featureList | string[] | No | — | List of features that should be included in the analysis | | excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | ## Response (application/json) **200** — Fully Update Autotune Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.description | string | Yes | — | Detailed description of the configuration’s purpose. | | data.variants | object[] | Yes | — | — | | data.variants.name | string | Yes | — | Variant name | | data.variants.json | unknown | Yes | — | Variant JSON data | | data.variants.size | number | No | — | Variant size | | data.variants.id | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | data.successEvent | string | Yes | — | The event you are trying to optimize for. | | data.successEventValue | string | Yes | — | The value that should come with the event for it to be considered successful. | | data.explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | data.attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | data.attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | data.explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | data.longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | data.winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | data.metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | data.higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | data.isContextual | boolean | No | — | Whether this is a contextual autotune | | data.metricSourceID | string | No | — | Metric source to pull success event data from | | data.linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | data.goalRichText | string | No | — | Autotune goal | | data.optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | data.valueColumn | string | No | — | Metric source column to optimize for | | data.featureList | string[] | No | — | List of features that should be included in the analysis | | data.excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.id | string | Yes | — | ID | | data.name | string | No | — | Optional name for the configuration. | | data.idType | string | Yes | — | Type of ID | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | Yes | — | ID of the user who created the entity. Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | Yes | — | Email of the creator. Constraints: nullable | | data.tags | string[] | No | — | Optional tags for categorization. | | data.targetApps | string[] | No | — | List of target applications associated with this configuration. | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Optional name for the responsible team. Constraints: nullable | | data.teamID | string | No | — | Optional ID of the responsible team. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isStarted | boolean | Yes | — | Is the autotune experiment currently running. | | data.winner | object | Yes | — | Constraints: nullable | | data.winner.id | string | Yes | — | The Statsig ID of the winner group. | | data.winner.name | string | Yes | — | The name of the winner group. | ```json { "message": "Autotune Experiment read successfully.", "data": { "id": "my_autotunes_are_best", "isStarted": false, "description": "helpful summary of what this Autotune is", "lastModifierID": "jd93DGSnvkauH9FijdGiajh", "lastModifierName": "CONSOLE API", "inlineTargetingRulesJSON": "{}", "inlineTargetingRules": [], "variants": [ { "name": "red", "json": { "color": "red" } }, { "name": "blue", "json": { "color": "blue" } } ], "successEvent": "purchase_item", "successEventValue": "", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/autotunes/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "description": "helpful summary of what this Autotune is", "variants": [ { "name": "red", "json": { "foo": "boo" }, "size": 50 }, { "name": "blue", "json": {}, "size": 50 } ], "successEvent": "purchase_item", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" }' ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/autotunes/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "description": "helpful summary of what this Autotune is", "variants": [ { "name": "red", "json": { "foo": "boo" }, "size": 50 }, { "name": "blue", "json": {}, "size": 50 } ], "successEvent": "purchase_item", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "description": "helpful summary of what this Autotune is", "variants": [ { "name": "red", "json": { "foo": "boo" }, "size": 50 }, { "name": "blue", "json": {}, "size": 50 } ], "successEvent": "purchase_item", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "description": "helpful summary of what this Autotune is", "variants": [ { "name": "red", "json": { "foo": "boo" }, "size": 50 }, { "name": "blue", "json": {}, "size": 50 } ], "successEvent": "purchase_item", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"description\":\"helpful summary of what this Autotune is\",\"variants\":[{\"name\":\"red\",\"json\":{\"foo\":\"boo\"},\"size\":50},{\"name\":\"blue\",\"json\":{},\"size\":50}],\"successEvent\":\"purchase_item\",\"explorationWindow\":\"1hr\",\"attributionWindow\":\"2hrs\",\"winnerThreshold\":\"99%\"}") req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/autotunes/{id}", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}")) .method("POST", HttpRequest.BodyPublishers.ofString("{\"description\":\"helpful summary of what this Autotune is\",\"variants\":[{\"name\":\"red\",\"json\":{\"foo\":\"boo\"},\"size\":50},{\"name\":\"blue\",\"json\":{},\"size\":50}],\"successEvent\":\"purchase_item\",\"explorationWindow\":\"1hr\",\"attributionWindow\":\"2hrs\",\"winnerThreshold\":\"99%\"}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"description\":\"helpful summary of what this Autotune is\",\"variants\":[{\"name\":\"red\",\"json\":{\"foo\":\"boo\"},\"size\":50},{\"name\":\"blue\",\"json\":{},\"size\":50}],\"successEvent\":\"purchase_item\",\"explorationWindow\":\"1hr\",\"attributionWindow\":\"2hrs\",\"winnerThreshold\":\"99%\"}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Autotune Overrides URL: https://docs.statsig.com/api-reference/autotunes/get-autotune-overrides ================================================================================ # Get Autotune Overrides ## Get Autotune Overrides **GET** `/console/v1/autotunes/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides` Get Autotune Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get Autotune Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "message": "Autotune Overrides read successfully.", "data": { "overrides": [ { "groupID": "Control", "id": "a_gate", "type": "gate" }, { "groupID": "Test", "id": "a_segment", "type": "segment" } ], "userIDOverrides": [ { "ids": [ "updated_id_list" ], "groupID": "Control" }, { "ids": [ "updated_id_lists" ], "groupID": "Test" } ] } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/autotunes/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/autotunes/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/autotunes/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/get-autotune-review ================================================================================ # Get Autotune Review ## Get Autotune Review **GET** `/console/v1/autotunes/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}` Get Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — The requested autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Autotune URL: https://docs.statsig.com/api-reference/autotunes/list-autotune ================================================================================ # List Autotune ## List Autotune **GET** `/console/v1/autotunes` Full URL: `https://statsigapi.net/console/v1/autotunes` List Autotune ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — Autotune Experiments listed successfully. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.description | string | Yes | — | Detailed description of the configuration’s purpose. | | data.variants | object[] | Yes | — | — | | data.variants.name | string | Yes | — | Variant name | | data.variants.json | unknown | Yes | — | Variant JSON data | | data.variants.size | number | No | — | Variant size | | data.variants.id | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | data.successEvent | string | Yes | — | The event you are trying to optimize for. | | data.successEventValue | string | Yes | — | The value that should come with the event for it to be considered successful. | | data.explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | data.attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | data.attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | data.explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | data.longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | data.winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | data.metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | data.higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | data.isContextual | boolean | No | — | Whether this is a contextual autotune | | data.metricSourceID | string | No | — | Metric source to pull success event data from | | data.linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | data.goalRichText | string | No | — | Autotune goal | | data.optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | data.valueColumn | string | No | — | Metric source column to optimize for | | data.featureList | string[] | No | — | List of features that should be included in the analysis | | data.excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.id | string | Yes | — | ID | | data.name | string | No | — | Optional name for the configuration. | | data.idType | string | Yes | — | Type of ID | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | Yes | — | ID of the user who created the entity. Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | Yes | — | Email of the creator. Constraints: nullable | | data.tags | string[] | No | — | Optional tags for categorization. | | data.targetApps | string[] | No | — | List of target applications associated with this configuration. | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Optional name for the responsible team. Constraints: nullable | | data.teamID | string | No | — | Optional ID of the responsible team. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isStarted | boolean | Yes | — | Is the autotune experiment currently running. | | data.winner | object | Yes | — | Constraints: nullable | | data.winner.id | string | Yes | — | The Statsig ID of the winner group. | | data.winner.name | string | Yes | — | The name of the winner group. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Autotune Experiments listed successfully.", "data": [ { "id": "test_autotune_exp", "name": "test_autotune_exp", "description": "dsdsdsd test", "idType": "userID", "lastModifierID": "24hiIXz1maFaDwtYEetv2i", "lastModifiedTime": 1716324033128, "lastModifierName": "jairo Garciga", "lastModifierEmail": "jairo@statsig.com", "creatorID": "5sgBiiuoBX4fscrWdCXVma", "createdTime": 1688072516890, "creatorName": "Samuel Kitono", "creatorEmail": "samuel@statsig.com", "targetApps": [], "holdoutIDs": [], "tags": [], "team": null, "isStarted": false, "inlineTargetingRulesJSON": "{}", "inlineTargetingRules": [], "variants": [ { "name": "test_12", "id": "7eOW6aXU7F07KxrggOrAdy", "json": { "user": { "id": 12345, "name": "Jane Doe", "email": "jane.doe@example.com", "isActive": true, "roles": [ "admin", "editor", "subscriber" ] }, "posts": [ { "id": 1, "title": "Introduction to JSON5", "content": "JSON5 is a superset of JSON that aims to be easier for humans to write and maintain.", "tags": [ "json5", "json", "javascript" ], "comments": [ { "id": 101, "author": "John Smith", "content": "Great post! Very informative.", "likes": 5 }, { "id": 102, "author": "Alice Johnson", "content": "I found this very helpful. Thanks!", "likes": 3 } ] }, { "id": 2, "title": "Advanced JSON5 Features", "content": "Explore the advanced features of JSON5, including comments, trailing commas, and more.", "tags": [ "json5", "advanced", "features" ], "comments": [ { "id": 201, "author": "Bob Brown", "content": "I didn't know JSON5 could do this. Amazing!", "likes": 8 } ] } ], "settings": { "theme": "dark", "notificationsEnabled": true, "language": "en-US", "layout": { "header": true, "footer": true, "sidebar": "collapsed" } }, "metadata": { "version": "1.0.0", "author": "Jane Doe", "lastUpdated": "2024-05-21T10:00:00Z" } } }, { "name": "var1", "id": "7eOW6cCWzX9C3WZbRWndwA", "json": {} }, { "name": "control", "id": "7GVLLJOBETDYXLn00FXFuQ", "json": {} } ], "successEvent": "add_to_cart", "successEventValue": "", "explorationWindow": "24hrs", "attributionWindow": "2hrs", "winnerThreshold": "95%", "winner": null } ], "pagination": { "itemsPerPage": 100, "pageNumber": 1, "totalItems": 1, "nextPage": null, "previousPage": null, "all": "/console/v1/autotunes" } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/autotunes?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/autotunes?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/autotunes?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Autotune Reviews URL: https://docs.statsig.com/api-reference/autotunes/list-autotune-reviews ================================================================================ # List Autotune Reviews ## List Autotune Reviews **GET** `/console/v1/autotunes/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews` List Autotune Reviews ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — A page of the autotune reviews, newest first. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Partially Update Autotune URL: https://docs.statsig.com/api-reference/autotunes/partially-update-autotune ================================================================================ # Partially Update Autotune ## Partially Update Autotune **PATCH** `/console/v1/autotunes/{id}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}` Partially Update Autotune Update selected properties of the experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | A brief summary of what the autotune is being used for. | | variants | object[] | No | — | An array of Variant objects. | | variants.name | string | Yes | — | Variant name | | variants.json | unknown | Yes | — | Variant JSON data | | variants.size | number | No | — | Variant size | | successEvent | string | No | — | The event you are trying to optimize for. | | successEventValue | string | No | — | The value that should come with the event for it to be considered successful. | | explorationWindow | string | No | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | attributionWindow | string | No | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | winnerThreshold | string | No | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | isContextual | boolean | No | — | Whether this is a contextual autotune | | metricSourceID | string | No | — | Metric source to pull success event data from | | linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | goalRichText | string | No | — | Autotune goal | | optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | valueColumn | string | No | — | Metric source column to optimize for | | featureList | string[] | No | — | List of features that should be included in the analysis | | excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | ## Response (application/json) **200** — Partially Update Autotune Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.description | string | Yes | — | Detailed description of the configuration’s purpose. | | data.variants | object[] | Yes | — | — | | data.variants.name | string | Yes | — | Variant name | | data.variants.json | unknown | Yes | — | Variant JSON data | | data.variants.size | number | No | — | Variant size | | data.variants.id | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | data.successEvent | string | Yes | — | The event you are trying to optimize for. | | data.successEventValue | string | Yes | — | The value that should come with the event for it to be considered successful. | | data.explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | data.attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | data.attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | data.explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | data.longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | data.winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | data.metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | data.higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | data.isContextual | boolean | No | — | Whether this is a contextual autotune | | data.metricSourceID | string | No | — | Metric source to pull success event data from | | data.linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | data.goalRichText | string | No | — | Autotune goal | | data.optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | data.valueColumn | string | No | — | Metric source column to optimize for | | data.featureList | string[] | No | — | List of features that should be included in the analysis | | data.excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.id | string | Yes | — | ID | | data.name | string | No | — | Optional name for the configuration. | | data.idType | string | Yes | — | Type of ID | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | Yes | — | ID of the user who created the entity. Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | Yes | — | Email of the creator. Constraints: nullable | | data.tags | string[] | No | — | Optional tags for categorization. | | data.targetApps | string[] | No | — | List of target applications associated with this configuration. | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Optional name for the responsible team. Constraints: nullable | | data.teamID | string | No | — | Optional ID of the responsible team. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isStarted | boolean | Yes | — | Is the autotune experiment currently running. | | data.winner | object | Yes | — | Constraints: nullable | | data.winner.id | string | Yes | — | The Statsig ID of the winner group. | | data.winner.name | string | Yes | — | The name of the winner group. | ```json { "message": "Autotune Experiment updated successfully.", "data": { "id": "a_autotune", "isStarted": false, "description": "helpful summary of what this Autotune is", "lastModifierID": "jd93DGSnvkauH9FijdGiajh", "lastModifierName": "CONSOLE API", "inlineTargetingRulesJSON": "{}", "inlineTargetingRules": [], "variants": [ { "name": "red", "json": { "color": "red" } }, { "name": "blue", "json": { "color": "blue" } } ], "successEvent": "purchase_item", "successEventValue": "", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/autotunes/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/autotunes/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/autotunes/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Partially Update Autotune Overrides URL: https://docs.statsig.com/api-reference/autotunes/partially-update-autotune-overrides ================================================================================ # Partially Update Autotune Overrides ## Partially Update Autotune Overrides **PATCH** `/console/v1/autotunes/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides` Partially Update Autotune Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | overrides.type | string | Yes | — | Allowed values: gate, segment | | overrides.id | string | Yes | — | The id of the segment or gate | | overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ## Response (application/json) **200** — Partially Update Autotune Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Control" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "patched_id_list" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/autotunes/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/autotunes/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/autotunes/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Autotune URL: https://docs.statsig.com/api-reference/autotunes/read-autotune ================================================================================ # Read Autotune ## Read Autotune **GET** `/console/v1/autotunes/{id}` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}` Read Autotune ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Read Autotune Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.description | string | Yes | — | Detailed description of the configuration’s purpose. | | data.variants | object[] | Yes | — | — | | data.variants.name | string | Yes | — | Variant name | | data.variants.json | unknown | Yes | — | Variant JSON data | | data.variants.size | number | No | — | Variant size | | data.variants.id | string | Yes | — | The name that was originally given to the autotune on creation but formatted as an ID ("A Autotune" -> "a_autotune"). | | data.successEvent | string | Yes | — | The event you are trying to optimize for. | | data.successEventValue | string | Yes | — | The value that should come with the event for it to be considered successful. | | data.explorationWindow | string | Yes | — | The initial time period where Autotune will equally split the traffic. Allowed values: 1hr, 24hr, 48hr, 168hr, 336hr, 1, 24, 48, 168, 336, 1hrs, 24hrs, 48hrs, 168hrs, 336hrs | | data.attributionWindow | string | Yes | — | The maximum duration between the exposure and success event that counts as a success. Allowed values: 1hr, 2hr, 4hr, 24hr, 1hrs, 2hrs, 4hrs, 24hrs, 1, 2, 4, 24 | | data.attributionWindowUnit | string | No | — | Time unit of attribution window Allowed values: min, hour, day | | data.explorationWindowRate | number | No | — | Exploration window rate Constraints: format: double, min: 0.001, max: 1 | | data.longtermExplorationAllocation | number | No | — | Long term exploration allocation Constraints: format: double, min: 0.001, max: 1 | | data.winnerThreshold | string | Yes | — | The "probability of best" threshold a variant needs to achieve for Autotune to declare it the winner, stop collecting data, and direct all traffic. Allowed values: 80%, 90%, 95%, 98%, 99% | | data.metadataField | string | No | — | Metadata field containing the numeric value to optimize for. If this field is null, autotune optimizes for the existence of a follow-up event. This is only used for contextual autotunes. | | data.higherIsBetter | boolean | No | — | Whether to optimize for an increase or decrease in the metadata field value. Default is true. This is only used for contextual autotunes. | | data.isContextual | boolean | No | — | Whether this is a contextual autotune | | data.metricSourceID | string | No | — | Metric source to pull success event data from | | data.linkedExperimentName | string | No | — | Linked experiment to measure the success of the Autotune | | data.goalRichText | string | No | — | Autotune goal | | data.optimizationParameter | string | No | — | Optimize for event occurrence vs value Allowed values: occurrence, value | | data.valueColumn | string | No | — | Metric source column to optimize for | | data.featureList | string[] | No | — | List of features that should be included in the analysis | | data.excludedFeatureList | string[] | No | — | Features to exclude from contextual Autotune analysis, even if included in `featureList`. Omit to leave unchanged on update, or send `[]` to clear the list. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.id | string | Yes | — | ID | | data.name | string | No | — | Optional name for the configuration. | | data.idType | string | Yes | — | Type of ID | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | Yes | — | ID of the user who created the entity. Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | Yes | — | Email of the creator. Constraints: nullable | | data.tags | string[] | No | — | Optional tags for categorization. | | data.targetApps | string[] | No | — | List of target applications associated with this configuration. | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Optional name for the responsible team. Constraints: nullable | | data.teamID | string | No | — | Optional ID of the responsible team. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isStarted | boolean | Yes | — | Is the autotune experiment currently running. | | data.winner | object | Yes | — | Constraints: nullable | | data.winner.id | string | Yes | — | The Statsig ID of the winner group. | | data.winner.name | string | Yes | — | The name of the winner group. | ```json { "message": "Autotune Experiment read successfully.", "data": { "id": "my_autotunes_are_best", "isStarted": false, "description": "helpful summary of what this Autotune is", "lastModifierID": "jd93DGSnvkauH9FijdGiajh", "lastModifierName": "CONSOLE API", "inlineTargetingRulesJSON": "{}", "inlineTargetingRules": [], "variants": [ { "name": "red", "json": { "foo": "boo" } }, { "name": "blue", "json": {} } ], "successEvent": "purchase_item", "successEventValue": "", "explorationWindow": "1hr", "attributionWindow": "2hrs", "winnerThreshold": "99%" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/autotunes/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/autotunes/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/autotunes/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Reject Autotune Review URL: https://docs.statsig.com/api-reference/autotunes/reject-autotune-review ================================================================================ # Reject Autotune Review ## Reject Autotune Review **PUT** `/console/v1/autotunes/{id}/reviews/{reviewID}/reject` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject` Reject Autotune Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | Yes | — | Required reason for rejecting the review. Constraints: min length: 1, max length: 2000 | ## Response (application/json) **200** — The rejected autotune review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reviews/{reviewID}/reject") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Reset Experiment URL: https://docs.statsig.com/api-reference/autotunes/reset-experiment ================================================================================ # Reset Experiment ## Reset Experiment **PUT** `/console/v1/autotunes/{id}/reset` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/reset` Reset Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Reset Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Autotune Experiment successfully restarted." } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Autotune experiment has not yet started" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Autotune Experiment not found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/reset" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/reset", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/reset", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/reset"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/reset", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/reset")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/reset") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Schedule Autotune Start URL: https://docs.statsig.com/api-reference/autotunes/schedule-autotune-start ================================================================================ # Schedule Autotune Start ## Schedule Autotune Start **POST** `/console/v1/autotunes/{id}/schedule_start` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/schedule_start` Schedule Autotune Start ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | scheduledTime | number | Yes | — | Unix timestamp (in milliseconds) to schedule the experiment to start Constraints: format: double | ## Response (application/json) **200** — Schedule Autotune Start Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Successfully scheduled autotune start" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/autotunes/{id}/schedule_start" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/autotunes/{id}/schedule_start", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/schedule_start", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/schedule_start"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/autotunes/{id}/schedule_start", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/schedule_start")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/schedule_start") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Start Autotune Experiment URL: https://docs.statsig.com/api-reference/autotunes/start-autotune-experiment ================================================================================ # Start Autotune Experiment ## Start Autotune Experiment **PUT** `/console/v1/autotunes/{id}/start` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/start` Start Autotune Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Start Autotune Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Autotune Experiment successfully started." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/autotunes/{id}/start" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/autotunes/{id}/start", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/start", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/start"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/autotunes/{id}/start", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/start")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/start") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Autotune Overrides URL: https://docs.statsig.com/api-reference/autotunes/update-autotune-overrides ================================================================================ # Update Autotune Overrides ## Update Autotune Overrides **POST** `/console/v1/autotunes/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/autotunes/{id}/overrides` Update Autotune Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | overrides.type | string | Yes | — | Allowed values: gate, segment | | overrides.id | string | Yes | — | The id of the segment or gate | | overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ## Response (application/json) **200** — Update Autotune Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of autotune overrides, each specifying type, ID, and variant ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The autotune variant which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into autotune variants. | | data.userIDOverrides.groupID | string | Yes | — | The autotune variant the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified autotune variant. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the autotune. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the autotune, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "segment", "id": "a_segment", "groupID": "Control" }, { "type": "gate", "id": "a_gate", "groupID": "Test" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "updated_control_id_list" ] }, { "groupID": "Test", "ids": [ "updated_test_id_list" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Autotune not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/autotunes/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/autotunes/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/autotunes/{id}/overrides", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/autotunes/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/autotunes/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/autotunes/{id}/overrides")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/autotunes/{id}/overrides") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Change Validation URL: https://docs.statsig.com/api-reference/change-validation/change-validation ================================================================================ # Change Validation ## Change Validation **POST** `/console/v1/change_validation` Full URL: `https://statsigapi.net/console/v1/change_validation` Change Validation See how change validation works [here](https://docs.statsig.com/guides/pre-commit-webhooks) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reviewID | string | Yes | — | — | | creationValidationAttemptID | string | No | — | — | | validated | boolean | Yes | — | — | | message | string | No | — | — | | debugLinks | object[] | No | — | — | | debugLinks.title | string | Yes | — | — | | debugLinks.url | string | Yes | — | — | | releasePipelineIDForCommit | string | No | — | Constraints: nullable | ## Response (application/json) **200** — Change Validation Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Validation status updated successfully" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/change_validation" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/change_validation", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/change_validation", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/change_validation"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/change_validation", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/change_validation")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/change_validation") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update change validation message URL: https://docs.statsig.com/api-reference/change-validation/update-change-validation-message ================================================================================ # Update change validation message ## Update change validation message **PATCH** `/console/v1/change_validation/message` Full URL: `https://statsigapi.net/console/v1/change_validation/message` Update change validation message ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reviewID | string | Yes | — | — | | creationValidationAttemptID | string | No | — | — | | message | string | No | — | — | ## Response (application/json) **200** — Update Change Validation Message Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Validation message updated successfully" } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/change_validation/message" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/change_validation/message", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/change_validation/message", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/change_validation/message"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/change_validation/message", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/change_validation/message")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/change_validation/message") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Company Info URL: https://docs.statsig.com/api-reference/company/get-company-info ================================================================================ # Get Company Info ## Get Company Info **GET** `/console/v1/company` Full URL: `https://statsigapi.net/console/v1/company` Get Company Info ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Response (application/json) **200** — Get company info response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.companyID | string | Yes | — | — | | data.companyName | string | Yes | — | — | | data.isWarehouseNative | boolean | Yes | — | — | | data.orgID | string | Yes | — | Constraints: nullable | | data.orgName | string | Yes | — | Constraints: nullable | | data.resultsUpTo | number | No | — | Constraints: format: double | ```json { "message": "string", "data": { "companyID": "string", "companyName": "string", "isWarehouseNative": true, "orgID": "string", "orgName": "string", "resultsUpTo": 0 } } ``` **403** — Forbidden resource | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | number | Yes | — | Allowed values: 403 | | message | string | Yes | — | Allowed values: Forbidden resource | ```json { "status": 403, "message": "Forbidden resource" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/company" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/company", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/company", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/company"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/company", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/company")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/company") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Exposure Event Count URL: https://docs.statsig.com/api-reference/configs/read-exposure-event-count ================================================================================ # Read Exposure Event Count ## Read Exposure Event Count **GET** `/console/v1/exposure_count` Full URL: `https://statsigapi.net/console/v1/exposure_count` Read Exposure Event Count Get the count of exposure events recently received by Statsig. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | experiments (query) | oneOf | No | — | Constraints: string, string[] | | gates (query) | oneOf | No | — | Constraints: string, string[] | | dynamicConfigs (query) | oneOf | No | — | Constraints: string, string[] | ## Response (application/json) **200** — Get Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.gates | object[] | Yes | — | ids of gates to query (max 25) | | data.gates.id | string | Yes | — | — | | data.gates.pastDay | number | Yes | — | — | | data.gates.past7Days | number | Yes | — | — | | data.experiments | object[] | Yes | — | ids of experiments to query (max 25) | | data.experiments.id | string | Yes | — | — | | data.experiments.pastDay | number | Yes | — | — | | data.experiments.past7Days | number | Yes | — | — | | data.dynamicConfigs | object[] | Yes | — | ids of dynamic configs to query (max 25) | | data.dynamicConfigs.id | string | Yes | — | — | | data.dynamicConfigs.pastDay | number | Yes | — | — | | data.dynamicConfigs.past7Days | number | Yes | — | — | ```json { "message": "Exposure count fetched successfully.", "data": { "gates": [ { "id": "a_gate", "pastDay": 0, "past7Days": 98 } ], "experiments": [ { "id": "my_experiment", "pastDay": 102, "past7Days": 558 }, { "id": "another_experiment", "pastDay": 5904, "past7Days": 2078 } ], "dynamicConfigs": [ { "id": "dc_limit", "pastDay": 240830, "past7Days": 1329945 } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Data is not available" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/exposure_count" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/exposure_count", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/exposure_count", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/exposure_count"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/exposure_count", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/exposure_count")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/exposure_count") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Add Widgets to Dashboard URL: https://docs.statsig.com/api-reference/dashboards/add-widgets-to-dashboard ================================================================================ # Add Widgets to Dashboard ## Add Widgets to Dashboard **POST** `/console/v1/dashboards/{id}/widgets` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}/widgets` Add Widgets to Dashboard Append typed widget definitions. Supported definitions from an editable read can be copied; supplied widget IDs do not retain existing widgets. Include a revision to reject an append after concurrent dashboard changes. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | widgets | oneOf[] | Yes | — | — | | widgets.type | string | Yes | — | Allowed values: text, header, timeseries, drilldown, funnel | | widgets.title | string | Yes | — | — | | widgets.content | string | No | — | — | | widgets.width | integer | No | — | Constraints: min: 0, max: 12 | | widgets.height | integer | No | — | Constraints: min: 0 | | widgets.id | string | No | — | — | | widgets.description | string | No | — | — | | widgets.color | string | No | — | Constraints: nullable | | widgets.layout | object | No | — | — | | widgets.layout.row | integer | Yes | — | Constraints: min: 0 | | widgets.layout.column | integer | Yes | — | Constraints: min: 0, max: 11 | | widgets.date_range | object | No | — | Constraints: nullable | | widgets.date_range.start_ds | string | No | — | Constraints: nullable | | widgets.date_range.end_ds | string | No | — | Constraints: nullable | | widgets.date_range.start_offset_days | number | No | — | Constraints: nullable | | widgets.date_range.end_offset_days | number | No | — | Constraints: nullable | | widgets.query | object | No | — | — | | widgets.query.source | object | No | — | — | | widgets.query.source.type | string | Yes | — | Allowed values: event | | widgets.query.source.event_name | string | Yes | — | — | | widgets.query.source.filters | object[] | No | — | — | | widgets.query.source.filters.property | object | Yes | — | — | | widgets.query.source.filters.property.key | string | Yes | — | — | | widgets.query.source.filters.property.column | unknown | Yes | — | — | | widgets.query.source.filters.operator | unknown | Yes | — | — | | widgets.query.source.filters.values | string[] | No | [] | — | | widgets.query.sources | object[] | No | — | — | | widgets.query.sources.type | string | Yes | — | Allowed values: event | | widgets.query.sources.event_name | string | Yes | — | — | | widgets.query.sources.filters | object[] | No | — | — | | widgets.query.sources.filters.property | object | Yes | — | — | | widgets.query.sources.filters.property.key | string | Yes | — | — | | widgets.query.sources.filters.property.column | unknown | Yes | — | — | | widgets.query.sources.filters.operator | unknown | Yes | — | — | | widgets.query.sources.filters.values | string[] | No | [] | — | | widgets.query.aggregation | object or string | No | — | Allowed values: daily, overall | | widgets.query.aggregation.type | unknown | Yes | — | — | | widgets.query.aggregation.property | object | No | — | — | | widgets.query.aggregation.property.key | string | Yes | — | — | | widgets.query.aggregation.property.column | unknown | Yes | — | — | | widgets.query.unit_type | string | No | — | — | | widgets.query.group_bys | object[] | No | — | — | | widgets.query.group_bys.key | string | Yes | — | — | | widgets.query.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.group_bys.metric_source_column | string | No | — | — | | widgets.query.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.viz | object | No | — | — | | widgets.query.viz.chart_type | string | Yes | — | Allowed values: line, timeseries-bar, horizontal-bar, grouped-bar, pie, geo-map, samples, stacked-line, single-value, conversion-rate, conversions, table | | widgets.query.viz.date | object | No | — | — | | widgets.query.viz.date.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.viz.date.window_size | number | No | — | — | | widgets.query.viz.date.offset_days | number | No | — | — | | widgets.query.viz.date.label | string | Yes | — | — | | widgets.query.viz.date.start_ms | number | No | — | — | | widgets.query.viz.date.end_ms | number | No | — | — | | widgets.query.viz.date.excluded_dates_ms | number[] | No | — | — | | widgets.query.viz.date.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.viz.time_range | object | No | — | — | | widgets.query.viz.time_range.start_ms | number | Yes | — | — | | widgets.query.viz.time_range.end_ms | number | Yes | — | — | | widgets.query.viz.time_range.label | string | Yes | — | — | | widgets.query.viz.time_range.is_relative_to_now | boolean | No | — | — | | widgets.query.viz.granularity | string | No | — | Allowed values: month, week, day, hour, 5m, 30m, 1m, auto | | widgets.query.viz.time_comparison | number | No | — | — | | widgets.query.viz.time_comparison_hours | number | No | — | — | | widgets.query.viz.rollup_type | string | No | — | Allowed values: none, avg, sum, cumulative_sum | | widgets.query.viz.rollup_days | number | No | — | — | | widgets.query.viz.y_axis_type | string | No | — | Allowed values: numbers, monetary, percentage, time, time_ns, time_us, time_ms, decimal_bytes, binary_bytes, bits, time_s, percentage_ratio | | widgets.query.viz.cum_sum_rollup | string | No | — | Allowed values: unique, all | | widgets.query.viz.single_value_type | string | No | — | Allowed values: latest, overall | | widgets.query.viz.usage_interval_number_of_days | number | No | — | — | | widgets.query.viz.show_delta_comparison_view | boolean | No | — | — | | widgets.query.viz.is_time_comparison_last_period | boolean | No | — | — | | widgets.query.viz.show_grouped_percentage_breakdown | boolean | No | — | — | | widgets.query.viz.chart_view | string | No | — | Allowed values: chart, legend, chart_legend | | widgets.query.viz.show_percent_difference_compare_option | boolean | No | — | — | | widgets.query.viz.use_widget_granularity_in_dashboard | boolean | No | — | — | | widgets.query.filters | object[] | No | — | — | | widgets.query.filters.property | object | Yes | — | — | | widgets.query.filters.property.key | string | Yes | — | — | | widgets.query.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.filters.property.metric_source_column | string | No | — | — | | widgets.query.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.filters.values | string[] | No | [] | — | | widgets.query.filters.label | string | No | — | — | | widgets.query.cohorts | object[] | No | — | — | | widgets.query.cohorts.id | string | No | — | Constraints: min length: 1 | | widgets.query.cohorts.name | string | No | — | — | | widgets.query.cohorts.unit_type | string | No | — | — | | widgets.query.cohorts.events | object[] | No | — | — | | widgets.query.cohorts.events.event | object | Yes | — | — | | widgets.query.cohorts.events.event.event_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters | object[] | Yes | — | — | | widgets.query.cohorts.events.event.filters.property | object | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.key | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.cohorts.events.event.filters.property.metric_source_column | string | No | — | — | | widgets.query.cohorts.events.event.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.cohorts.events.event.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.cohorts.events.event.filters.values | string[] | No | [] | — | | widgets.query.cohorts.events.event.filters.label | string | No | — | — | | widgets.query.cohorts.events.event.alias | string | No | — | — | | widgets.query.cohorts.events.event.is_first_time | boolean | No | — | — | | widgets.query.cohorts.events.event.metric_type | string | No | — | — | | widgets.query.cohorts.events.event.metric_source_id | string | No | — | — | | widgets.query.cohorts.events.event.event_name_column | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.cohorts.events.operator | string | Yes | — | Allowed values: >, <, >=, <=, = | | widgets.query.cohorts.events.threshold | number | Yes | — | — | | widgets.query.cohorts.events.date_range | object | Yes | — | — | | widgets.query.cohorts.events.date_range.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.cohorts.events.date_range.window_size | number | No | — | — | | widgets.query.cohorts.events.date_range.offset_days | number | No | — | — | | widgets.query.cohorts.events.date_range.label | string | Yes | — | — | | widgets.query.cohorts.events.date_range.start_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.end_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.excluded_dates_ms | number[] | No | — | — | | widgets.query.cohorts.events.date_range.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.cohorts.any_event | boolean | No | — | — | | widgets.query.cohorts.is_verified | boolean | No | — | — | | widgets.query.options | object | No | — | — | | widgets.query.options.exposure_query_mode | string | No | — | Allowed values: all, daily_first, first, fresh | | widgets.query.options.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.group_by_query_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.separate_chart_per_metric | boolean | No | — | — | | widgets.query.options.force_start_y_at_zero | boolean | No | — | — | | widgets.query.options.include_annotations | boolean | No | — | — | | widgets.query.options.show_all_annotations | boolean | No | — | — | | widgets.query.options.annotation_filters | object | No | — | — | | widgets.query.options.annotation_filters.filter_entity_type | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag | object | No | — | — | | widgets.query.options.annotation_filters.filter_tag.ids | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag.operator | string | No | — | — | | widgets.query.options.annotation_filters.filter_target_app | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_environment | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_team | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_creator | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_gate_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_dynamic_config_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_experiment_name | string[] | No | — | — | | widgets.query.options.sorting | object | No | — | — | | widgets.query.options.sorting.metric_metadata | object | No | — | — | | widgets.query.options.sorting.metric_metadata.name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.options.sorting.metric_metadata.property | object | No | — | — | | widgets.query.options.sorting.metric_metadata.property.key | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.options.sorting.metric_metadata.property.metric_source_column | string | No | — | — | | widgets.query.options.sorting.metric_metadata.property.source | object | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.options.sorting.metric_metadata.property.source.experiment_name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_symbol | string | No | — | — | | widgets.query.options.sorting.sort_ascending | boolean | No | — | — | | widgets.query.options.sampling_enabled | boolean | No | — | — | | widgets.query.options.include_test_events | boolean | No | — | — | | widgets.query.options.filter_bot_data | boolean | No | — | — | | widgets.query.options.enable_id_resolution | boolean | No | — | — | | widgets.query.options.is_precomputed_only | boolean | No | — | — | | widgets.query.options.default_id_type | string | No | — | Constraints: nullable | | widgets.query.options.show_table_only | boolean | No | — | — | | widgets.query.series | object[] | No | — | — | | widgets.query.series.id | string | No | — | — | | widgets.query.series.source | oneOf | Yes | — | Constraints: object | | widgets.query.series.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.series.source.event_name | string | No | — | — | | widgets.query.series.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.series.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.series.source.name | string | No | — | — | | widgets.query.series.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.definition | object | No | — | — | | widgets.query.series.definition.events | object[] | Yes | — | — | | widgets.query.series.definition.events.event_name | string | Yes | — | — | | widgets.query.series.definition.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.events.filters.label | string | No | — | — | | widgets.query.series.definition.events.alias | string | No | — | — | | widgets.query.series.definition.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.events.metric_type | string | No | — | — | | widgets.query.series.definition.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.aggregation | object | Yes | — | — | | widgets.query.series.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.aggregation.property | object | No | — | — | | widgets.query.series.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite | object | No | — | — | | widgets.query.series.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.series.definition.composite.numerator | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite.denominator | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.series.unit_type | string | No | — | — | | widgets.query.series.filters | object[] | No | — | — | | widgets.query.series.filters.property | object | Yes | — | — | | widgets.query.series.filters.property.key | string | Yes | — | — | | widgets.query.series.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.filters.values | string[] | No | [] | — | | widgets.query.series.filters.label | string | No | — | — | | widgets.query.series.group_bys | object[] | No | — | — | | widgets.query.series.group_bys.key | string | Yes | — | — | | widgets.query.series.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.group_bys.metric_source_column | string | No | — | — | | widgets.query.series.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.series.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.alias | string | No | — | — | | widgets.query.series.hidden | boolean | No | — | — | | widgets.query.formulas | object[] | No | — | — | | widgets.query.formulas.id | string | No | — | — | | widgets.query.formulas.formula | string | Yes | — | — | | widgets.query.formulas.name | string | No | — | — | | widgets.query.formulas.hidden | boolean | No | — | — | | widgets.query.formulas.coalesce_nulls_as_zeroes | boolean | No | — | — | | widgets.query.formulas.highlight_as | string | No | — | Allowed values: error, warning | | widgets.query.steps | oneOf[] | No | — | — | | widgets.query.steps.event_name | string | No | — | — | | widgets.query.steps.filters | object[] | No | — | — | | widgets.query.steps.filters.property | object | Yes | — | — | | widgets.query.steps.filters.property.key | string | Yes | — | — | | widgets.query.steps.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.filters.values | string[] | No | [] | — | | widgets.query.steps.filters.label | string | No | — | — | | widgets.query.steps.events | object[] | No | — | — | | widgets.query.steps.events.event_name | string | Yes | — | — | | widgets.query.steps.events.filters | object[] | Yes | — | — | | widgets.query.steps.events.filters.property | object | Yes | — | — | | widgets.query.steps.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.events.filters.values | string[] | No | [] | — | | widgets.query.steps.events.filters.label | string | No | — | — | | widgets.query.steps.events.alias | string | No | — | — | | widgets.query.steps.events.is_first_time | boolean | No | — | — | | widgets.query.steps.events.metric_type | string | No | — | — | | widgets.query.steps.events.metric_source_id | string | No | — | — | | widgets.query.steps.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric | object | No | — | — | | widgets.query.steps.metric.id | string | No | — | — | | widgets.query.steps.metric.source | oneOf | Yes | — | Constraints: object | | widgets.query.steps.metric.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.steps.metric.source.event_name | string | No | — | — | | widgets.query.steps.metric.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.steps.metric.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.steps.metric.source.name | string | No | — | — | | widgets.query.steps.metric.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.definition | object | No | — | — | | widgets.query.steps.metric.definition.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite | object | No | — | — | | widgets.query.steps.metric.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.steps.metric.definition.composite.numerator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite.denominator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.steps.metric.unit_type | string | No | — | — | | widgets.query.steps.metric.filters | object[] | No | — | — | | widgets.query.steps.metric.filters.property | object | Yes | — | — | | widgets.query.steps.metric.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.filters.label | string | No | — | — | | widgets.query.steps.metric.group_bys | object[] | No | — | — | | widgets.query.steps.metric.group_bys.key | string | Yes | — | — | | widgets.query.steps.metric.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.group_bys.metric_source_column | string | No | — | — | | widgets.query.steps.metric.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.alias | string | No | — | — | | widgets.query.steps.metric.hidden | boolean | No | — | — | | widgets.query.steps.alias | string | No | — | — | | widgets.query.steps.is_metric_expanded | boolean | No | — | — | | widgets.query.steps.is_optional | boolean | No | — | — | | widgets.query.steps.should_compare_events | boolean | No | — | — | | widgets.query.conversion_window | object | No | — | — | | widgets.query.conversion_window.value | integer | Yes | — | Constraints: min: 0 | | widgets.query.conversion_window.unit | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.chart_type | string | No | — | Allowed values: conversion-rate, conversions | | widgets.query.measurement | string | No | — | Allowed values: conversion_rate, conversion_rate_over_time, time_to_convert | | widgets.query.is_sequential | boolean | No | — | — | | widgets.query.use_uniques_units | boolean | No | — | — | | widgets.query.use_persistent_group_bys | boolean | No | — | — | | widgets.query.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.sort_by_conversion_rate | boolean | No | — | — | | widgets.query.sort_order_is_descending | boolean | No | — | — | | widgets.query.time_to_convert_buckets | object | No | — | — | | widgets.query.time_to_convert_buckets.range_min | number | Yes | — | — | | widgets.query.time_to_convert_buckets.range_max | number | Yes | — | — | | widgets.query.time_to_convert_buckets.interval_size | number | Yes | — | Constraints: min: 0 | | widgets.query.time_to_convert_buckets.bucket_units_min_max | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_buckets.bucket_units_bucket_size | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_unit | string | No | — | Allowed values: second, minute, hour, day | | widgets.query.show_sum_property_value_last_step | boolean | No | — | — | | widgets.query.property_value_to_sum | string | No | — | — | | widgets.query.exclude_units_who_did_event | object | No | — | — | | widgets.query.exclude_units_who_did_event.events | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.event_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property | object | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.key | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.exclude_units_who_did_event.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.exclude_units_who_did_event.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.exclude_units_who_did_event.events.filters.values | string[] | No | [] | — | | widgets.query.exclude_units_who_did_event.events.filters.label | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.alias | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.is_first_time | boolean | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_type | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_source_id | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.exclude_units_who_did_event.between_steps | object | No | — | — | | widgets.query.exclude_units_who_did_event.between_steps.start | integer | Yes | — | Constraints: min: 0 | | widgets.query.exclude_units_who_did_event.between_steps.end | integer | Yes | — | Constraints: min: 0 | | revision | string | No | — | Reject the append if this revision no longer matches the dashboard. | | defaults | object | No | — | Constraints: nullable | | defaults.date | oneOf | No | — | Constraints: object | | defaults.date.value | integer or number | No | — | Constraints: min: 0 | | defaults.date.unit | string | No | — | Allowed values: day, week, month, minute, hour | | defaults.date.mode | string | No | — | Allowed values: chart_default, since, relative | | defaults.date.since_ms | number | No | — | — | | defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | | max_cols | integer | No | — | Constraints: format: int64, min: 0 | ## Response (application/json) **200** — Add dashboard widgets response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.ids | string[] | Yes | — | — | | data.revision | string | Yes | — | — | ```json { "message": "Dashboard Widgets Added Successfully", "data": { "ids": [ "widget_id" ], "revision": "d1.revision" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **412** — The supplied revision no longer matches the dashboard. ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/dashboards/{id}/widgets" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/dashboards/{id}/widgets", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}/widgets", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}/widgets"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/dashboards/{id}/widgets", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}/widgets")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}/widgets") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Dashboard URL: https://docs.statsig.com/api-reference/dashboards/create-dashboard ================================================================================ # Create Dashboard ## Create Dashboard **POST** `/console/v1/dashboards` Full URL: `https://statsigapi.net/console/v1/dashboards` Create Dashboard Create a dashboard from typed widget definitions. Use Console API metric IDs for catalog metrics and metric-source IDs for warehouse sources. Supplied widget IDs are ignored when copying supported definitions. Raw serialized state is unsupported. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Constraints: min length: 1, max length: 200 | | description | string | No | — | Constraints: max length: 10000 | | defaults | object | No | — | Constraints: nullable | | defaults.date | oneOf | No | — | Constraints: object | | defaults.date.value | integer or number | No | — | Constraints: min: 0 | | defaults.date.unit | string | No | — | Allowed values: day, week, month, minute, hour | | defaults.date.mode | string | No | — | Allowed values: chart_default, since, relative | | defaults.date.since_ms | number | No | — | — | | defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | | widgets | oneOf[] | No | — | — | | widgets.type | string | Yes | — | Allowed values: text, header, timeseries, drilldown, funnel | | widgets.title | string | Yes | — | — | | widgets.content | string | No | — | — | | widgets.width | integer | No | — | Constraints: min: 0, max: 12 | | widgets.height | integer | No | — | Constraints: min: 0 | | widgets.id | string | No | — | — | | widgets.description | string | No | — | — | | widgets.color | string | No | — | Constraints: nullable | | widgets.layout | object | No | — | — | | widgets.layout.row | integer | Yes | — | Constraints: min: 0 | | widgets.layout.column | integer | Yes | — | Constraints: min: 0, max: 11 | | widgets.date_range | object | No | — | Constraints: nullable | | widgets.date_range.start_ds | string | No | — | Constraints: nullable | | widgets.date_range.end_ds | string | No | — | Constraints: nullable | | widgets.date_range.start_offset_days | number | No | — | Constraints: nullable | | widgets.date_range.end_offset_days | number | No | — | Constraints: nullable | | widgets.query | object | No | — | — | | widgets.query.source | object | No | — | — | | widgets.query.source.type | string | Yes | — | Allowed values: event | | widgets.query.source.event_name | string | Yes | — | — | | widgets.query.source.filters | object[] | No | — | — | | widgets.query.source.filters.property | object | Yes | — | — | | widgets.query.source.filters.property.key | string | Yes | — | — | | widgets.query.source.filters.property.column | unknown | Yes | — | — | | widgets.query.source.filters.operator | unknown | Yes | — | — | | widgets.query.source.filters.values | string[] | No | [] | — | | widgets.query.sources | object[] | No | — | — | | widgets.query.sources.type | string | Yes | — | Allowed values: event | | widgets.query.sources.event_name | string | Yes | — | — | | widgets.query.sources.filters | object[] | No | — | — | | widgets.query.sources.filters.property | object | Yes | — | — | | widgets.query.sources.filters.property.key | string | Yes | — | — | | widgets.query.sources.filters.property.column | unknown | Yes | — | — | | widgets.query.sources.filters.operator | unknown | Yes | — | — | | widgets.query.sources.filters.values | string[] | No | [] | — | | widgets.query.aggregation | object or string | No | — | Allowed values: daily, overall | | widgets.query.aggregation.type | unknown | Yes | — | — | | widgets.query.aggregation.property | object | No | — | — | | widgets.query.aggregation.property.key | string | Yes | — | — | | widgets.query.aggregation.property.column | unknown | Yes | — | — | | widgets.query.unit_type | string | No | — | — | | widgets.query.group_bys | object[] | No | — | — | | widgets.query.group_bys.key | string | Yes | — | — | | widgets.query.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.group_bys.metric_source_column | string | No | — | — | | widgets.query.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.viz | object | No | — | — | | widgets.query.viz.chart_type | string | Yes | — | Allowed values: line, timeseries-bar, horizontal-bar, grouped-bar, pie, geo-map, samples, stacked-line, single-value, conversion-rate, conversions, table | | widgets.query.viz.date | object | No | — | — | | widgets.query.viz.date.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.viz.date.window_size | number | No | — | — | | widgets.query.viz.date.offset_days | number | No | — | — | | widgets.query.viz.date.label | string | Yes | — | — | | widgets.query.viz.date.start_ms | number | No | — | — | | widgets.query.viz.date.end_ms | number | No | — | — | | widgets.query.viz.date.excluded_dates_ms | number[] | No | — | — | | widgets.query.viz.date.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.viz.time_range | object | No | — | — | | widgets.query.viz.time_range.start_ms | number | Yes | — | — | | widgets.query.viz.time_range.end_ms | number | Yes | — | — | | widgets.query.viz.time_range.label | string | Yes | — | — | | widgets.query.viz.time_range.is_relative_to_now | boolean | No | — | — | | widgets.query.viz.granularity | string | No | — | Allowed values: month, week, day, hour, 5m, 30m, 1m, auto | | widgets.query.viz.time_comparison | number | No | — | — | | widgets.query.viz.time_comparison_hours | number | No | — | — | | widgets.query.viz.rollup_type | string | No | — | Allowed values: none, avg, sum, cumulative_sum | | widgets.query.viz.rollup_days | number | No | — | — | | widgets.query.viz.y_axis_type | string | No | — | Allowed values: numbers, monetary, percentage, time, time_ns, time_us, time_ms, decimal_bytes, binary_bytes, bits, time_s, percentage_ratio | | widgets.query.viz.cum_sum_rollup | string | No | — | Allowed values: unique, all | | widgets.query.viz.single_value_type | string | No | — | Allowed values: latest, overall | | widgets.query.viz.usage_interval_number_of_days | number | No | — | — | | widgets.query.viz.show_delta_comparison_view | boolean | No | — | — | | widgets.query.viz.is_time_comparison_last_period | boolean | No | — | — | | widgets.query.viz.show_grouped_percentage_breakdown | boolean | No | — | — | | widgets.query.viz.chart_view | string | No | — | Allowed values: chart, legend, chart_legend | | widgets.query.viz.show_percent_difference_compare_option | boolean | No | — | — | | widgets.query.viz.use_widget_granularity_in_dashboard | boolean | No | — | — | | widgets.query.filters | object[] | No | — | — | | widgets.query.filters.property | object | Yes | — | — | | widgets.query.filters.property.key | string | Yes | — | — | | widgets.query.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.filters.property.metric_source_column | string | No | — | — | | widgets.query.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.filters.values | string[] | No | [] | — | | widgets.query.filters.label | string | No | — | — | | widgets.query.cohorts | object[] | No | — | — | | widgets.query.cohorts.id | string | No | — | Constraints: min length: 1 | | widgets.query.cohorts.name | string | No | — | — | | widgets.query.cohorts.unit_type | string | No | — | — | | widgets.query.cohorts.events | object[] | No | — | — | | widgets.query.cohorts.events.event | object | Yes | — | — | | widgets.query.cohorts.events.event.event_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters | object[] | Yes | — | — | | widgets.query.cohorts.events.event.filters.property | object | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.key | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.cohorts.events.event.filters.property.metric_source_column | string | No | — | — | | widgets.query.cohorts.events.event.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.cohorts.events.event.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.cohorts.events.event.filters.values | string[] | No | [] | — | | widgets.query.cohorts.events.event.filters.label | string | No | — | — | | widgets.query.cohorts.events.event.alias | string | No | — | — | | widgets.query.cohorts.events.event.is_first_time | boolean | No | — | — | | widgets.query.cohorts.events.event.metric_type | string | No | — | — | | widgets.query.cohorts.events.event.metric_source_id | string | No | — | — | | widgets.query.cohorts.events.event.event_name_column | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.cohorts.events.operator | string | Yes | — | Allowed values: >, <, >=, <=, = | | widgets.query.cohorts.events.threshold | number | Yes | — | — | | widgets.query.cohorts.events.date_range | object | Yes | — | — | | widgets.query.cohorts.events.date_range.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.cohorts.events.date_range.window_size | number | No | — | — | | widgets.query.cohorts.events.date_range.offset_days | number | No | — | — | | widgets.query.cohorts.events.date_range.label | string | Yes | — | — | | widgets.query.cohorts.events.date_range.start_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.end_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.excluded_dates_ms | number[] | No | — | — | | widgets.query.cohorts.events.date_range.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.cohorts.any_event | boolean | No | — | — | | widgets.query.cohorts.is_verified | boolean | No | — | — | | widgets.query.options | object | No | — | — | | widgets.query.options.exposure_query_mode | string | No | — | Allowed values: all, daily_first, first, fresh | | widgets.query.options.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.group_by_query_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.separate_chart_per_metric | boolean | No | — | — | | widgets.query.options.force_start_y_at_zero | boolean | No | — | — | | widgets.query.options.include_annotations | boolean | No | — | — | | widgets.query.options.show_all_annotations | boolean | No | — | — | | widgets.query.options.annotation_filters | object | No | — | — | | widgets.query.options.annotation_filters.filter_entity_type | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag | object | No | — | — | | widgets.query.options.annotation_filters.filter_tag.ids | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag.operator | string | No | — | — | | widgets.query.options.annotation_filters.filter_target_app | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_environment | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_team | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_creator | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_gate_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_dynamic_config_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_experiment_name | string[] | No | — | — | | widgets.query.options.sorting | object | No | — | — | | widgets.query.options.sorting.metric_metadata | object | No | — | — | | widgets.query.options.sorting.metric_metadata.name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.options.sorting.metric_metadata.property | object | No | — | — | | widgets.query.options.sorting.metric_metadata.property.key | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.options.sorting.metric_metadata.property.metric_source_column | string | No | — | — | | widgets.query.options.sorting.metric_metadata.property.source | object | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.options.sorting.metric_metadata.property.source.experiment_name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_symbol | string | No | — | — | | widgets.query.options.sorting.sort_ascending | boolean | No | — | — | | widgets.query.options.sampling_enabled | boolean | No | — | — | | widgets.query.options.include_test_events | boolean | No | — | — | | widgets.query.options.filter_bot_data | boolean | No | — | — | | widgets.query.options.enable_id_resolution | boolean | No | — | — | | widgets.query.options.is_precomputed_only | boolean | No | — | — | | widgets.query.options.default_id_type | string | No | — | Constraints: nullable | | widgets.query.options.show_table_only | boolean | No | — | — | | widgets.query.series | object[] | No | — | — | | widgets.query.series.id | string | No | — | — | | widgets.query.series.source | oneOf | Yes | — | Constraints: object | | widgets.query.series.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.series.source.event_name | string | No | — | — | | widgets.query.series.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.series.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.series.source.name | string | No | — | — | | widgets.query.series.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.definition | object | No | — | — | | widgets.query.series.definition.events | object[] | Yes | — | — | | widgets.query.series.definition.events.event_name | string | Yes | — | — | | widgets.query.series.definition.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.events.filters.label | string | No | — | — | | widgets.query.series.definition.events.alias | string | No | — | — | | widgets.query.series.definition.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.events.metric_type | string | No | — | — | | widgets.query.series.definition.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.aggregation | object | Yes | — | — | | widgets.query.series.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.aggregation.property | object | No | — | — | | widgets.query.series.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite | object | No | — | — | | widgets.query.series.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.series.definition.composite.numerator | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite.denominator | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.series.unit_type | string | No | — | — | | widgets.query.series.filters | object[] | No | — | — | | widgets.query.series.filters.property | object | Yes | — | — | | widgets.query.series.filters.property.key | string | Yes | — | — | | widgets.query.series.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.filters.values | string[] | No | [] | — | | widgets.query.series.filters.label | string | No | — | — | | widgets.query.series.group_bys | object[] | No | — | — | | widgets.query.series.group_bys.key | string | Yes | — | — | | widgets.query.series.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.group_bys.metric_source_column | string | No | — | — | | widgets.query.series.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.series.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.alias | string | No | — | — | | widgets.query.series.hidden | boolean | No | — | — | | widgets.query.formulas | object[] | No | — | — | | widgets.query.formulas.id | string | No | — | — | | widgets.query.formulas.formula | string | Yes | — | — | | widgets.query.formulas.name | string | No | — | — | | widgets.query.formulas.hidden | boolean | No | — | — | | widgets.query.formulas.coalesce_nulls_as_zeroes | boolean | No | — | — | | widgets.query.formulas.highlight_as | string | No | — | Allowed values: error, warning | | widgets.query.steps | oneOf[] | No | — | — | | widgets.query.steps.event_name | string | No | — | — | | widgets.query.steps.filters | object[] | No | — | — | | widgets.query.steps.filters.property | object | Yes | — | — | | widgets.query.steps.filters.property.key | string | Yes | — | — | | widgets.query.steps.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.filters.values | string[] | No | [] | — | | widgets.query.steps.filters.label | string | No | — | — | | widgets.query.steps.events | object[] | No | — | — | | widgets.query.steps.events.event_name | string | Yes | — | — | | widgets.query.steps.events.filters | object[] | Yes | — | — | | widgets.query.steps.events.filters.property | object | Yes | — | — | | widgets.query.steps.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.events.filters.values | string[] | No | [] | — | | widgets.query.steps.events.filters.label | string | No | — | — | | widgets.query.steps.events.alias | string | No | — | — | | widgets.query.steps.events.is_first_time | boolean | No | — | — | | widgets.query.steps.events.metric_type | string | No | — | — | | widgets.query.steps.events.metric_source_id | string | No | — | — | | widgets.query.steps.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric | object | No | — | — | | widgets.query.steps.metric.id | string | No | — | — | | widgets.query.steps.metric.source | oneOf | Yes | — | Constraints: object | | widgets.query.steps.metric.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.steps.metric.source.event_name | string | No | — | — | | widgets.query.steps.metric.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.steps.metric.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.steps.metric.source.name | string | No | — | — | | widgets.query.steps.metric.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.definition | object | No | — | — | | widgets.query.steps.metric.definition.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite | object | No | — | — | | widgets.query.steps.metric.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.steps.metric.definition.composite.numerator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite.denominator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.steps.metric.unit_type | string | No | — | — | | widgets.query.steps.metric.filters | object[] | No | — | — | | widgets.query.steps.metric.filters.property | object | Yes | — | — | | widgets.query.steps.metric.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.filters.label | string | No | — | — | | widgets.query.steps.metric.group_bys | object[] | No | — | — | | widgets.query.steps.metric.group_bys.key | string | Yes | — | — | | widgets.query.steps.metric.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.group_bys.metric_source_column | string | No | — | — | | widgets.query.steps.metric.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.alias | string | No | — | — | | widgets.query.steps.metric.hidden | boolean | No | — | — | | widgets.query.steps.alias | string | No | — | — | | widgets.query.steps.is_metric_expanded | boolean | No | — | — | | widgets.query.steps.is_optional | boolean | No | — | — | | widgets.query.steps.should_compare_events | boolean | No | — | — | | widgets.query.conversion_window | object | No | — | — | | widgets.query.conversion_window.value | integer | Yes | — | Constraints: min: 0 | | widgets.query.conversion_window.unit | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.chart_type | string | No | — | Allowed values: conversion-rate, conversions | | widgets.query.measurement | string | No | — | Allowed values: conversion_rate, conversion_rate_over_time, time_to_convert | | widgets.query.is_sequential | boolean | No | — | — | | widgets.query.use_uniques_units | boolean | No | — | — | | widgets.query.use_persistent_group_bys | boolean | No | — | — | | widgets.query.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.sort_by_conversion_rate | boolean | No | — | — | | widgets.query.sort_order_is_descending | boolean | No | — | — | | widgets.query.time_to_convert_buckets | object | No | — | — | | widgets.query.time_to_convert_buckets.range_min | number | Yes | — | — | | widgets.query.time_to_convert_buckets.range_max | number | Yes | — | — | | widgets.query.time_to_convert_buckets.interval_size | number | Yes | — | Constraints: min: 0 | | widgets.query.time_to_convert_buckets.bucket_units_min_max | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_buckets.bucket_units_bucket_size | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_unit | string | No | — | Allowed values: second, minute, hour, day | | widgets.query.show_sum_property_value_last_step | boolean | No | — | — | | widgets.query.property_value_to_sum | string | No | — | — | | widgets.query.exclude_units_who_did_event | object | No | — | — | | widgets.query.exclude_units_who_did_event.events | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.event_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property | object | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.key | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.exclude_units_who_did_event.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.exclude_units_who_did_event.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.exclude_units_who_did_event.events.filters.values | string[] | No | [] | — | | widgets.query.exclude_units_who_did_event.events.filters.label | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.alias | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.is_first_time | boolean | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_type | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_source_id | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.exclude_units_who_did_event.between_steps | object | No | — | — | | widgets.query.exclude_units_who_did_event.between_steps.start | integer | Yes | — | Constraints: min: 0 | | widgets.query.exclude_units_who_did_event.between_steps.end | integer | Yes | — | Constraints: min: 0 | ## Response (application/json) **200** — Create dashboard response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.dashboard_url | string | Yes | — | — | | data.revision | string | Yes | — | — | ```json { "message": "Dashboard Created Successfully", "data": { "id": "dashboard_id", "dashboard_url": "https://console.statsig.com/company_id/dashboards/dashboard_id", "revision": "d1.revision" } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/dashboards" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/dashboards", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/dashboards", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Dashboard Widget URL: https://docs.statsig.com/api-reference/dashboards/delete-dashboard-widget ================================================================================ # Delete Dashboard Widget ## Delete Dashboard Widget **DELETE** `/console/v1/dashboards/{id}/widgets/{widgetId}` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}` Delete Dashboard Widget Delete one widget permanently. Include the dashboard revision from an editable or references read. A revision conflict requires a fresh read; do not retry deletion automatically. MCP requires explicit destructive-operation confirmation. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | dashboard id | | widgetId (path) | string | Yes | — | widget id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | revision (query) | string | Yes | — | Include the `revision` returned by an editable or references read. Read the dashboard again after a revision conflict. | ## Response (application/json) **200** — Deleted widget identity and updated dashboard revision. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.revision | string | Yes | — | — | ```json { "message": "string", "data": { "id": "string", "revision": "string" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **412** — The revision changed. Read the dashboard again before deleting. ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Dashboards URL: https://docs.statsig.com/api-reference/dashboards/list-dashboards ================================================================================ # List Dashboards ## List Dashboards **GET** `/console/v1/dashboards` Full URL: `https://statsigapi.net/console/v1/dashboards` List Dashboards ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | | search (query) | string | No | growth | Filter dashboards by name using a partial match. Constraints: min length: 1 | ## Response (application/json) **200** — List dashboards response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.description | string | Yes | — | — | | data.defaults | object | No | — | — | | data.defaults.date | object | No | — | — | | data.defaults.date.value | integer | Yes | — | Constraints: format: int64, min: 0 | | data.defaults.date.unit | string | Yes | — | Allowed values: day, week, month | | data.defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | | data.created_time | number | Yes | — | Constraints: format: double | | data.modified_time | number | Yes | — | Constraints: format: double | | data.widget_count | integer | Yes | — | Constraints: format: int64, min: 0 | | data.is_verified | boolean | No | — | Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Dashboards Listed Successfully", "data": [ { "id": "dashboard_id", "name": "My Dashboard", "description": "desc", "defaults": { "date": { "value": 14, "unit": "day" }, "granularity": "daily" }, "created_time": 1736208000, "modified_time": 1736294400, "widget_count": 1, "is_verified": true } ], "pagination": { "itemsPerPage": 20, "pageNumber": 1, "nextPage": null, "previousPage": null, "totalItems": 1, "all": "/console/v1/dashboards" } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards?limit=10&page=1&search=growth") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Dashboard URL: https://docs.statsig.com/api-reference/dashboards/read-dashboard ================================================================================ # Read Dashboard ## Read Dashboard **GET** `/console/v1/dashboards/{id}` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}` Read Dashboard Read dashboard widget definitions. Use `view=editable` for complete typed definitions and a `revision`, or `view=references` for bounded widget references. Pin reference pages and `widget_id` detail reads with `revision`. The default legacy view is unchanged. Send supported definitions back to create, add, replace, or edit widgets. Preserve unsupported widgets by ID. Include the read revision for replacement, edits and deletions. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | view (query) | string | No | — | Allowed values: legacy, editable, references | | widget_id (query) | string | No | — | — | | revision (query) | string | No | — | — | | cursor (query) | string | No | — | — | | limit (query) | integer | No | — | Constraints: min: 0, max: 100 | ## Response (application/json) **200** — Read dashboard response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | Constraints: min length: 1, max length: 200 | | data.description | string | No | — | Constraints: max length: 10000 | | data.defaults | object | No | — | — | | data.defaults.date | object | No | — | — | | data.defaults.date.value | integer or number | No | — | Constraints: format: int64, min: 0 | | data.defaults.date.unit | string | No | — | Allowed values: day, week, month, minute, hour | | data.defaults.date.mode | string | No | — | Allowed values: chart_default, since, relative | | data.defaults.date.since_ms | number | No | — | — | | data.defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | | data.widgets | object[] | No | — | — | | data.widgets.type | string | Yes | — | Allowed values: text, header, timeseries, funnel, unsupported, drilldown | | data.widgets.title | string | Yes | — | — | | data.widgets.content | string | No | — | — | | data.widgets.width | integer | No | — | Constraints: min: 0, max: 12 | | data.widgets.height | integer | No | — | Constraints: min: 0 | | data.widgets.id | string | Yes | — | — | | data.widgets.color | string | No | — | Constraints: nullable | | data.widgets.description | string | No | — | — | | data.widgets.query | object | No | — | — | | data.widgets.query.source | object | No | — | — | | data.widgets.query.source.type | string | Yes | — | Allowed values: event | | data.widgets.query.source.event_name | string | Yes | — | — | | data.widgets.query.source.filters | object[] | No | — | — | | data.widgets.query.source.filters.property | object | Yes | — | — | | data.widgets.query.source.filters.property.key | string | Yes | — | — | | data.widgets.query.source.filters.property.column | unknown | Yes | — | — | | data.widgets.query.source.filters.operator | unknown | Yes | — | — | | data.widgets.query.source.filters.values | string[] | No | [] | — | | data.widgets.query.sources | object[] | No | — | — | | data.widgets.query.sources.type | string | Yes | — | Allowed values: event | | data.widgets.query.sources.event_name | string | Yes | — | — | | data.widgets.query.sources.filters | object[] | No | — | — | | data.widgets.query.sources.filters.property | object | Yes | — | — | | data.widgets.query.sources.filters.property.key | string | Yes | — | — | | data.widgets.query.sources.filters.property.column | unknown | Yes | — | — | | data.widgets.query.sources.filters.operator | unknown | Yes | — | — | | data.widgets.query.sources.filters.values | string[] | No | [] | — | | data.widgets.query.aggregation | object | No | — | Allowed values: daily, overall | | data.widgets.query.aggregation.type | unknown | Yes | — | — | | data.widgets.query.aggregation.property | object | No | — | — | | data.widgets.query.aggregation.property.key | string | Yes | — | — | | data.widgets.query.aggregation.property.column | unknown | Yes | — | — | | data.widgets.query.unit_type | string | No | — | — | | data.widgets.query.group_bys | object[] | No | — | — | | data.widgets.query.group_bys.key | string | Yes | — | — | | data.widgets.query.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.group_bys.metric_source_column | string | No | — | — | | data.widgets.query.group_bys.source | object | No | — | Constraints: nullable | | data.widgets.query.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.group_bys.source.experiment_name | string | Yes | — | — | | data.widgets.query.group_bys.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.viz | object | No | — | — | | data.widgets.query.viz.chart_type | string | Yes | — | Allowed values: line, timeseries-bar, horizontal-bar, grouped-bar, pie, geo-map, samples, stacked-line, single-value, conversion-rate, conversions, table | | data.widgets.query.viz.date | object | No | — | — | | data.widgets.query.viz.date.type | string | Yes | — | Allowed values: relative, fixed | | data.widgets.query.viz.date.window_size | number | No | — | — | | data.widgets.query.viz.date.offset_days | number | No | — | — | | data.widgets.query.viz.date.label | string | Yes | — | — | | data.widgets.query.viz.date.start_ms | number | No | — | — | | data.widgets.query.viz.date.end_ms | number | No | — | — | | data.widgets.query.viz.date.excluded_dates_ms | number[] | No | — | — | | data.widgets.query.viz.date.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | data.widgets.query.viz.time_range | object | No | — | — | | data.widgets.query.viz.time_range.start_ms | number | Yes | — | — | | data.widgets.query.viz.time_range.end_ms | number | Yes | — | — | | data.widgets.query.viz.time_range.label | string | Yes | — | — | | data.widgets.query.viz.time_range.is_relative_to_now | boolean | No | — | — | | data.widgets.query.viz.granularity | string | No | — | Allowed values: month, week, day, hour, 5m, 30m, 1m, auto | | data.widgets.query.viz.time_comparison | number | No | — | — | | data.widgets.query.viz.time_comparison_hours | number | No | — | — | | data.widgets.query.viz.rollup_type | string | No | — | Allowed values: none, avg, sum, cumulative_sum | | data.widgets.query.viz.rollup_days | number | No | — | — | | data.widgets.query.viz.y_axis_type | string | No | — | Allowed values: numbers, monetary, percentage, time, time_ns, time_us, time_ms, decimal_bytes, binary_bytes, bits, time_s, percentage_ratio | | data.widgets.query.viz.cum_sum_rollup | string | No | — | Allowed values: unique, all | | data.widgets.query.viz.single_value_type | string | No | — | Allowed values: latest, overall | | data.widgets.query.viz.usage_interval_number_of_days | number | No | — | — | | data.widgets.query.viz.show_delta_comparison_view | boolean | No | — | — | | data.widgets.query.viz.is_time_comparison_last_period | boolean | No | — | — | | data.widgets.query.viz.show_grouped_percentage_breakdown | boolean | No | — | — | | data.widgets.query.viz.chart_view | string | No | — | Allowed values: chart, legend, chart_legend | | data.widgets.query.viz.show_percent_difference_compare_option | boolean | No | — | — | | data.widgets.query.viz.use_widget_granularity_in_dashboard | boolean | No | — | — | | data.widgets.query.steps | object[] | No | — | — | | data.widgets.query.steps.event_name | string | No | — | — | | data.widgets.query.steps.filters | object[] | No | — | — | | data.widgets.query.steps.filters.property | object | Yes | — | — | | data.widgets.query.steps.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.filters.values | string[] | No | [] | — | | data.widgets.query.steps.filters.label | string | No | — | — | | data.widgets.query.steps.events | object[] | No | — | — | | data.widgets.query.steps.events.event_name | string | Yes | — | — | | data.widgets.query.steps.events.filters | object[] | Yes | — | — | | data.widgets.query.steps.events.filters.property | object | Yes | — | — | | data.widgets.query.steps.events.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.events.filters.values | string[] | No | [] | — | | data.widgets.query.steps.events.filters.label | string | No | — | — | | data.widgets.query.steps.events.alias | string | No | — | — | | data.widgets.query.steps.events.is_first_time | boolean | No | — | — | | data.widgets.query.steps.events.metric_type | string | No | — | — | | data.widgets.query.steps.events.metric_source_id | string | No | — | — | | data.widgets.query.steps.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.steps.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.steps.metric | object | No | — | — | | data.widgets.query.steps.metric.id | string | No | — | — | | data.widgets.query.steps.metric.source | oneOf | Yes | — | Constraints: object | | data.widgets.query.steps.metric.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | data.widgets.query.steps.metric.source.event_name | string | No | — | — | | data.widgets.query.steps.metric.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | data.widgets.query.steps.metric.source.metric_source_id | string | No | — | Constraints: min length: 1 | | data.widgets.query.steps.metric.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | data.widgets.query.steps.metric.source.name | string | No | — | — | | data.widgets.query.steps.metric.source.table_config_id | string | No | — | Constraints: min length: 1 | | data.widgets.query.steps.metric.definition | object | No | — | — | | data.widgets.query.steps.metric.definition.events | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.events.event_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.events.filters | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.events.filters.property | object | Yes | — | — | | data.widgets.query.steps.metric.definition.events.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.metric.definition.events.filters.values | string[] | No | [] | — | | data.widgets.query.steps.metric.definition.events.filters.label | string | No | — | — | | data.widgets.query.steps.metric.definition.events.alias | string | No | — | — | | data.widgets.query.steps.metric.definition.events.is_first_time | boolean | No | — | — | | data.widgets.query.steps.metric.definition.events.metric_type | string | No | — | — | | data.widgets.query.steps.metric.definition.events.metric_source_id | string | No | — | — | | data.widgets.query.steps.metric.definition.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.steps.metric.definition.aggregation | object | Yes | — | — | | data.widgets.query.steps.metric.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.steps.metric.definition.aggregation.property | object | No | — | — | | data.widgets.query.steps.metric.definition.aggregation.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.steps.metric.definition.composite | object | No | — | — | | data.widgets.query.steps.metric.definition.composite.type | string | Yes | — | Allowed values: ratio | | data.widgets.query.steps.metric.definition.composite.numerator | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.event_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.filters.label | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.alias | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.metric_type | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.metric_source_id | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property | object | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.steps.metric.definition.composite.denominator | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.event_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters | object[] | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.filters.label | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.alias | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.metric_type | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.metric_source_id | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation | object | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property | object | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.steps.metric.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | data.widgets.query.steps.metric.unit_type | string | No | — | — | | data.widgets.query.steps.metric.filters | object[] | No | — | — | | data.widgets.query.steps.metric.filters.property | object | Yes | — | — | | data.widgets.query.steps.metric.filters.property.key | string | Yes | — | — | | data.widgets.query.steps.metric.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.steps.metric.filters.values | string[] | No | [] | — | | data.widgets.query.steps.metric.filters.label | string | No | — | — | | data.widgets.query.steps.metric.group_bys | object[] | No | — | — | | data.widgets.query.steps.metric.group_bys.key | string | Yes | — | — | | data.widgets.query.steps.metric.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.steps.metric.group_bys.metric_source_column | string | No | — | — | | data.widgets.query.steps.metric.group_bys.source | object | No | — | Constraints: nullable | | data.widgets.query.steps.metric.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.steps.metric.group_bys.source.experiment_name | string | Yes | — | — | | data.widgets.query.steps.metric.group_bys.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.steps.metric.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.steps.metric.alias | string | No | — | — | | data.widgets.query.steps.metric.hidden | boolean | No | — | — | | data.widgets.query.steps.alias | string | No | — | — | | data.widgets.query.steps.is_metric_expanded | boolean | No | — | — | | data.widgets.query.steps.is_optional | boolean | No | — | — | | data.widgets.query.steps.should_compare_events | boolean | No | — | — | | data.widgets.query.conversion_window | object | No | — | — | | data.widgets.query.conversion_window.value | integer | Yes | — | Constraints: min: 0 | | data.widgets.query.conversion_window.unit | string | Yes | — | Allowed values: second, minute, hour, day | | data.widgets.query.chart_type | string | No | — | Allowed values: conversion-rate, conversions | | data.widgets.query.cohorts | object[] | No | — | — | | data.widgets.query.cohorts.id | string | No | — | Constraints: min length: 1 | | data.widgets.query.cohorts.name | string | No | — | — | | data.widgets.query.cohorts.unit_type | string | No | — | — | | data.widgets.query.cohorts.events | object[] | No | — | — | | data.widgets.query.cohorts.events.event | object | Yes | — | — | | data.widgets.query.cohorts.events.event.event_name | string | Yes | — | — | | data.widgets.query.cohorts.events.event.filters | object[] | Yes | — | — | | data.widgets.query.cohorts.events.event.filters.property | object | Yes | — | — | | data.widgets.query.cohorts.events.event.filters.property.key | string | Yes | — | — | | data.widgets.query.cohorts.events.event.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.cohorts.events.event.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.cohorts.events.event.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.cohorts.events.event.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.cohorts.events.event.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.cohorts.events.event.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.cohorts.events.event.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.cohorts.events.event.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.cohorts.events.event.filters.values | string[] | No | [] | — | | data.widgets.query.cohorts.events.event.filters.label | string | No | — | — | | data.widgets.query.cohorts.events.event.alias | string | No | — | — | | data.widgets.query.cohorts.events.event.is_first_time | boolean | No | — | — | | data.widgets.query.cohorts.events.event.metric_type | string | No | — | — | | data.widgets.query.cohorts.events.event.metric_source_id | string | No | — | — | | data.widgets.query.cohorts.events.event.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.cohorts.events.event.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.cohorts.events.operator | string | Yes | — | Allowed values: >, <, >=, <=, = | | data.widgets.query.cohorts.events.threshold | number | Yes | — | — | | data.widgets.query.cohorts.events.date_range | object | Yes | — | — | | data.widgets.query.cohorts.events.date_range.type | string | Yes | — | Allowed values: relative, fixed | | data.widgets.query.cohorts.events.date_range.window_size | number | No | — | — | | data.widgets.query.cohorts.events.date_range.offset_days | number | No | — | — | | data.widgets.query.cohorts.events.date_range.label | string | Yes | — | — | | data.widgets.query.cohorts.events.date_range.start_ms | number | No | — | — | | data.widgets.query.cohorts.events.date_range.end_ms | number | No | — | — | | data.widgets.query.cohorts.events.date_range.excluded_dates_ms | number[] | No | — | — | | data.widgets.query.cohorts.events.date_range.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | data.widgets.query.cohorts.any_event | boolean | No | — | — | | data.widgets.query.cohorts.is_verified | boolean | No | — | — | | data.widgets.query.filters | object[] | No | — | — | | data.widgets.query.filters.property | object | Yes | — | — | | data.widgets.query.filters.property.key | string | Yes | — | — | | data.widgets.query.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.filters.values | string[] | No | [] | — | | data.widgets.query.filters.label | string | No | — | — | | data.widgets.query.options | object | No | — | — | | data.widgets.query.options.exposure_query_mode | string | No | — | Allowed values: all, daily_first, first, fresh | | data.widgets.query.options.group_by_limit | integer | No | — | Constraints: min: 0 | | data.widgets.query.options.group_by_query_limit | integer | No | — | Constraints: min: 0 | | data.widgets.query.options.separate_chart_per_metric | boolean | No | — | — | | data.widgets.query.options.force_start_y_at_zero | boolean | No | — | — | | data.widgets.query.options.include_annotations | boolean | No | — | — | | data.widgets.query.options.show_all_annotations | boolean | No | — | — | | data.widgets.query.options.annotation_filters | object | No | — | — | | data.widgets.query.options.annotation_filters.filter_entity_type | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_tag | object | No | — | — | | data.widgets.query.options.annotation_filters.filter_tag.ids | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_tag.operator | string | No | — | — | | data.widgets.query.options.annotation_filters.filter_target_app | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_environment | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_team | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_creator | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_gate_name | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_dynamic_config_name | string[] | No | — | — | | data.widgets.query.options.annotation_filters.filter_experiment_name | string[] | No | — | — | | data.widgets.query.options.sorting | object | No | — | — | | data.widgets.query.options.sorting.metric_metadata | object | No | — | — | | data.widgets.query.options.sorting.metric_metadata.name | string | Yes | — | — | | data.widgets.query.options.sorting.metric_metadata.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.options.sorting.metric_metadata.property | object | No | — | — | | data.widgets.query.options.sorting.metric_metadata.property.key | string | Yes | — | — | | data.widgets.query.options.sorting.metric_metadata.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.options.sorting.metric_metadata.property.metric_source_column | string | No | — | — | | data.widgets.query.options.sorting.metric_metadata.property.source | object | No | — | Constraints: nullable | | data.widgets.query.options.sorting.metric_metadata.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.options.sorting.metric_metadata.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.options.sorting.metric_metadata.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.options.sorting.metric_metadata.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.options.sorting.metric_symbol | string | No | — | — | | data.widgets.query.options.sorting.sort_ascending | boolean | No | — | — | | data.widgets.query.options.sampling_enabled | boolean | No | — | — | | data.widgets.query.options.include_test_events | boolean | No | — | — | | data.widgets.query.options.filter_bot_data | boolean | No | — | — | | data.widgets.query.options.enable_id_resolution | boolean | No | — | — | | data.widgets.query.options.is_precomputed_only | boolean | No | — | — | | data.widgets.query.options.default_id_type | string | No | — | Constraints: nullable | | data.widgets.query.options.show_table_only | boolean | No | — | — | | data.widgets.query.series | object[] | No | — | — | | data.widgets.query.series.id | string | No | — | — | | data.widgets.query.series.source | oneOf | Yes | — | Constraints: object | | data.widgets.query.series.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | data.widgets.query.series.source.event_name | string | No | — | — | | data.widgets.query.series.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | data.widgets.query.series.source.metric_source_id | string | No | — | Constraints: min length: 1 | | data.widgets.query.series.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | data.widgets.query.series.source.name | string | No | — | — | | data.widgets.query.series.source.table_config_id | string | No | — | Constraints: min length: 1 | | data.widgets.query.series.definition | object | No | — | — | | data.widgets.query.series.definition.events | object[] | Yes | — | — | | data.widgets.query.series.definition.events.event_name | string | Yes | — | — | | data.widgets.query.series.definition.events.filters | object[] | Yes | — | — | | data.widgets.query.series.definition.events.filters.property | object | Yes | — | — | | data.widgets.query.series.definition.events.filters.property.key | string | Yes | — | — | | data.widgets.query.series.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.series.definition.events.filters.values | string[] | No | [] | — | | data.widgets.query.series.definition.events.filters.label | string | No | — | — | | data.widgets.query.series.definition.events.alias | string | No | — | — | | data.widgets.query.series.definition.events.is_first_time | boolean | No | — | — | | data.widgets.query.series.definition.events.metric_type | string | No | — | — | | data.widgets.query.series.definition.events.metric_source_id | string | No | — | — | | data.widgets.query.series.definition.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.series.definition.aggregation | object | Yes | — | — | | data.widgets.query.series.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.series.definition.aggregation.property | object | No | — | — | | data.widgets.query.series.definition.aggregation.property.key | string | Yes | — | — | | data.widgets.query.series.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.series.definition.composite | object | No | — | — | | data.widgets.query.series.definition.composite.type | string | Yes | — | Allowed values: ratio | | data.widgets.query.series.definition.composite.numerator | object | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events | object[] | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.event_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters | object[] | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters.property | object | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.series.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | data.widgets.query.series.definition.composite.numerator.events.filters.label | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.alias | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.metric_type | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.metric_source_id | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.series.definition.composite.numerator.aggregation | object | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.series.definition.composite.numerator.aggregation.property | object | No | — | — | | data.widgets.query.series.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.series.definition.composite.denominator | object | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events | object[] | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.event_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters | object[] | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters.property | object | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.series.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | data.widgets.query.series.definition.composite.denominator.events.filters.label | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.alias | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.metric_type | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.metric_source_id | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.series.definition.composite.denominator.aggregation | object | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | data.widgets.query.series.definition.composite.denominator.aggregation.property | object | No | — | — | | data.widgets.query.series.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | data.widgets.query.series.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | data.widgets.query.series.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | data.widgets.query.series.unit_type | string | No | — | — | | data.widgets.query.series.filters | object[] | No | — | — | | data.widgets.query.series.filters.property | object | Yes | — | — | | data.widgets.query.series.filters.property.key | string | Yes | — | — | | data.widgets.query.series.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.series.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.series.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.series.filters.values | string[] | No | [] | — | | data.widgets.query.series.filters.label | string | No | — | — | | data.widgets.query.series.group_bys | object[] | No | — | — | | data.widgets.query.series.group_bys.key | string | Yes | — | — | | data.widgets.query.series.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.series.group_bys.metric_source_column | string | No | — | — | | data.widgets.query.series.group_bys.source | object | No | — | Constraints: nullable | | data.widgets.query.series.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.series.group_bys.source.experiment_name | string | Yes | — | — | | data.widgets.query.series.group_bys.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.series.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.series.alias | string | No | — | — | | data.widgets.query.series.hidden | boolean | No | — | — | | data.widgets.query.formulas | object[] | No | — | — | | data.widgets.query.formulas.id | string | No | — | — | | data.widgets.query.formulas.formula | string | Yes | — | — | | data.widgets.query.formulas.name | string | No | — | — | | data.widgets.query.formulas.hidden | boolean | No | — | — | | data.widgets.query.formulas.coalesce_nulls_as_zeroes | boolean | No | — | — | | data.widgets.query.formulas.highlight_as | string | No | — | Allowed values: error, warning | | data.widgets.query.measurement | string | No | — | Allowed values: conversion_rate, conversion_rate_over_time, time_to_convert | | data.widgets.query.is_sequential | boolean | No | — | — | | data.widgets.query.use_uniques_units | boolean | No | — | — | | data.widgets.query.use_persistent_group_bys | boolean | No | — | — | | data.widgets.query.group_by_limit | integer | No | — | Constraints: min: 0 | | data.widgets.query.sort_by_conversion_rate | boolean | No | — | — | | data.widgets.query.sort_order_is_descending | boolean | No | — | — | | data.widgets.query.time_to_convert_buckets | object | No | — | — | | data.widgets.query.time_to_convert_buckets.range_min | number | Yes | — | — | | data.widgets.query.time_to_convert_buckets.range_max | number | Yes | — | — | | data.widgets.query.time_to_convert_buckets.interval_size | number | Yes | — | Constraints: min: 0 | | data.widgets.query.time_to_convert_buckets.bucket_units_min_max | string | Yes | — | Allowed values: second, minute, hour, day | | data.widgets.query.time_to_convert_buckets.bucket_units_bucket_size | string | Yes | — | Allowed values: second, minute, hour, day | | data.widgets.query.time_to_convert_unit | string | No | — | Allowed values: second, minute, hour, day | | data.widgets.query.show_sum_property_value_last_step | boolean | No | — | — | | data.widgets.query.property_value_to_sum | string | No | — | — | | data.widgets.query.exclude_units_who_did_event | object | No | — | — | | data.widgets.query.exclude_units_who_did_event.events | object[] | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.event_name | string | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters | object[] | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters.property | object | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters.property.key | string | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | data.widgets.query.exclude_units_who_did_event.events.filters.property.metric_source_column | string | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters.property.source | object | No | — | Constraints: nullable | | data.widgets.query.exclude_units_who_did_event.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | data.widgets.query.exclude_units_who_did_event.events.filters.property.source.experiment_name | string | Yes | — | — | | data.widgets.query.exclude_units_who_did_event.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | data.widgets.query.exclude_units_who_did_event.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | data.widgets.query.exclude_units_who_did_event.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | data.widgets.query.exclude_units_who_did_event.events.filters.values | string[] | No | [] | — | | data.widgets.query.exclude_units_who_did_event.events.filters.label | string | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.alias | string | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.is_first_time | boolean | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.metric_type | string | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.metric_source_id | string | No | — | — | | data.widgets.query.exclude_units_who_did_event.events.event_name_column | string | No | — | Constraints: nullable | | data.widgets.query.exclude_units_who_did_event.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | data.widgets.query.exclude_units_who_did_event.between_steps | object | No | — | — | | data.widgets.query.exclude_units_who_did_event.between_steps.start | integer | Yes | — | Constraints: min: 0 | | data.widgets.query.exclude_units_who_did_event.between_steps.end | integer | Yes | — | Constraints: min: 0 | | data.widgets.reason | string | No | — | — | | data.widgets.layout | object | No | — | — | | data.widgets.layout.row | integer | Yes | — | Constraints: min: 0 | | data.widgets.layout.column | integer | Yes | — | Constraints: min: 0, max: 11 | | data.widgets.date_range | object | No | — | Constraints: nullable | | data.widgets.date_range.start_ds | string | No | — | Constraints: nullable | | data.widgets.date_range.end_ds | string | No | — | Constraints: nullable | | data.widgets.date_range.start_offset_days | number | No | — | Constraints: nullable | | data.widgets.date_range.end_offset_days | number | No | — | Constraints: nullable | | data.widgets.widget_type | string | No | — | — | | data.widgets.query_type | string | No | — | — | | data.widgets.chart_type | string | No | — | — | | data.revision | string | No | — | — | | data.widget_count | number | No | — | Constraints: format: double | | data.widget_refs | object[] | No | — | — | | data.widget_refs.id | string | Yes | — | — | | data.widget_refs.widget_type | string | Yes | — | — | | data.widget_refs.title_preview | string | Yes | — | — | | data.pagination | object | No | — | — | | data.pagination.next_cursor | string | Yes | — | Constraints: nullable | ```json { "message": "Dashboard Read Successfully", "data": { "id": "dashboard_id", "name": "My Dashboard", "description": "desc", "defaults": { "date": { "value": 14, "unit": "day" }, "granularity": "daily" }, "widgets": [ { "id": "widget_id", "type": "header", "title": "Overview", "width": 12, "height": 1 } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **412** — The dashboard revision changed. Read the dashboard again before continuing. ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dashboards/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dashboards/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dashboards/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Dashboard Widget Results URL: https://docs.statsig.com/api-reference/dashboards/read-dashboard-widget-results ================================================================================ # Read Dashboard Widget Results ## Read Dashboard Widget Results **GET** `/console/v1/dashboards/{id}/widgets/{widgetId}/results` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results` Read Dashboard Widget Results Read drilldown line, bar, pie, table, geo-map and number results, or funnel step, conversion-over-time and time-to-convert results. Results use dashboard date and granularity defaults. Dashboard global filters and variables are not applied. Hidden input series participate in formulas but their own datasets are omitted. Samples results require a separate loader and are unsupported. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | dashboard id | | widgetId (path) | string | Yes | — | widget id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | sampling_enabled (query) | boolean | No | true | Whether sampling should be enabled for this results query. Defaults to true. | ## Response (application/json) **200** — Read dashboard results as `funnel`, `timeseries`, `categorical`, or `single_value`. Drilldown tables and geo-maps return categorical data. Funnel rates over time use percentages; time-to-convert histograms include counts, numeric bucket boundaries and their shared denominator. Results use the dashboard's date range and granularity, resolved in the company's timezone. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.type | string | Yes | — | Selects the matching result payload: `funnel`, `timeseries`, `categorical`, or `single_value`. Categorical results include table and geo-map charts. Funnel measurements over time return `timeseries`; time-to-convert measurements return `categorical`. Allowed values: funnel, timeseries, categorical, single_value | | data.funnel | object | No | — | — | | data.funnel.datasets | object[] | Yes | — | — | | data.funnel.datasets.key | string | Yes | — | — | | data.funnel.datasets.label | string | No | — | Constraints: nullable | | data.funnel.datasets.group | string | No | — | Constraints: nullable | | data.funnel.datasets.cohort | string | No | — | Constraints: nullable | | data.funnel.datasets.excludes_optional_steps | boolean | No | — | — | | data.funnel.datasets.steps | object[] | Yes | — | — | | data.funnel.datasets.steps.rank | integer | Yes | — | Constraints: min: 0 | | data.funnel.datasets.steps.name | string | Yes | — | — | | data.funnel.datasets.steps.count | number | Yes | — | — | | data.funnel.datasets.steps.conversion_rate | number | No | — | Constraints: nullable | | data.funnel.datasets.steps.previous_step_conversion_rate | number | No | — | Constraints: nullable | | data.funnel.datasets.steps.time_to_convert | number | No | — | Constraints: nullable | | data.funnel.datasets.steps.cumulative_time_to_convert | number | No | — | Constraints: nullable | | data.funnel.datasets.steps.total_prop_sum | number | No | — | Constraints: nullable | | data.timeseries | object | No | — | — | | data.timeseries.chart_type | string | Yes | — | — | | data.timeseries.granularity | string | Yes | — | — | | data.timeseries.measurement | string | No | — | Allowed values: conversion_rate_over_time | | data.timeseries.value_unit | string | No | — | Funnel rates use a 0–100 scale. A zero start count produces a `null` value. Allowed values: percent | | data.timeseries.datasets | object[] | Yes | — | — | | data.timeseries.datasets.key | string | Yes | — | — | | data.timeseries.datasets.label | string | Yes | — | — | | data.timeseries.datasets.metric_name | string | No | — | Constraints: nullable | | data.timeseries.datasets.group | string | No | — | Constraints: nullable | | data.timeseries.datasets.group_values | string[] | No | — | — | | data.timeseries.datasets.is_time_comparison | boolean | No | — | — | | data.timeseries.datasets.cohort | string | No | — | Constraints: nullable | | data.timeseries.datasets.excludes_optional_steps | boolean | No | — | — | | data.timeseries.datasets.points | object[] | Yes | — | — | | data.timeseries.datasets.points.time | string | Yes | 2026-10-19T00:00:00.000Z | ISO-8601 start of the time bucket. | | data.timeseries.datasets.points.value | number | Yes | — | Constraints: nullable | | data.timeseries.datasets.points.started_count | number | No | — | Units that start the funnel in this bucket. Present for conversion rates over time. | | data.timeseries.datasets.points.completed_count | number | No | — | Started units that complete the funnel within its conversion window. | | data.timeseries.datasets.points.partial | boolean | No | — | Present and true when the bucket is still in progress, so its value is incomplete. | | data.categorical | object | No | — | — | | data.categorical.chart_type | string | Yes | — | — | | data.categorical.measurement | string | No | — | Allowed values: time_to_convert | | data.categorical.value_unit | string | No | — | Allowed values: percent | | data.categorical.normalization | string | No | — | Histogram percentages use one denominator across all returned groups and cohorts. Allowed values: all_returned_conversion_rows | | data.categorical.normalization_count | number | No | — | Total conversion rows in the histogram denominator. Empty results return `0`. Constraints: format: double | | data.categorical.datasets | object[] | Yes | — | — | | data.categorical.datasets.key | string | Yes | — | — | | data.categorical.datasets.label | string | Yes | — | — | | data.categorical.datasets.metric_name | string | No | — | Constraints: nullable | | data.categorical.datasets.group | string | No | — | Constraints: nullable | | data.categorical.datasets.group_values | string[] | No | — | — | | data.categorical.datasets.is_time_comparison | boolean | No | — | — | | data.categorical.datasets.cohort | string | No | — | Constraints: nullable | | data.categorical.datasets.excludes_optional_steps | boolean | No | — | — | | data.categorical.datasets.values | object[] | Yes | — | — | | data.categorical.datasets.values.label | string | Yes | — | — | | data.categorical.datasets.values.value | number | Yes | — | Constraints: nullable | | data.categorical.datasets.values.count | number | No | — | Conversion rows in this time-to-convert bucket. | | data.categorical.datasets.values.bucket | object | No | — | — | | data.categorical.datasets.values.bucket.lower_seconds | number | Yes | — | Lower elapsed-time boundary in seconds, or `null` for underflow. Constraints: nullable | | data.categorical.datasets.values.bucket.upper_seconds | number | Yes | — | Upper elapsed-time boundary in seconds, or `null` for overflow. Constraints: nullable | | data.categorical.datasets.values.bucket.lower_inclusive | boolean | Yes | — | Whether the bucket includes its lower boundary. | | data.categorical.datasets.values.bucket.upper_inclusive | boolean | Yes | — | Whether the bucket includes its upper boundary. | | data.single_value | object | No | — | — | | data.single_value.value_type | string | Yes | — | `latest` is the most recent day; `overall` is the value over the whole date range. Allowed values: latest, overall | | data.single_value.comparison_days | number | Yes | — | Days back that `delta` compares against, or null when the chart has no time comparison. Constraints: format: double, nullable | | data.single_value.values | object[] | Yes | — | — | | data.single_value.values.key | string | Yes | — | — | | data.single_value.values.label | string | Yes | — | — | | data.single_value.values.group | string | Yes | — | Constraints: nullable | | data.single_value.values.group_values | string[] | No | — | — | | data.single_value.values.value | number | Yes | — | — | | data.single_value.values.delta | number | No | — | Change from the comparison period. Present only when the chart compares to a previous period. Constraints: nullable | | data.single_value.values.directionality | string | No | — | Constraints: nullable Allowed values: increase, decrease | ```json { "message": "Dashboard Read Successfully", "data": { "id": "widget_id", "type": "funnel", "funnel": { "datasets": [ { "key": "default", "steps": [ { "rank": 0, "name": "signup", "count": 100, "conversion_rate": 1, "previous_step_conversion_rate": 1 }, { "rank": 1, "name": "purchase", "count": 42, "conversion_rate": 0.42, "previous_step_conversion_rate": 0.42 } ] } ] } } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}/results?sampling_enabled=true") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Replace Widgets on Dashboard URL: https://docs.statsig.com/api-reference/dashboards/replace-widgets-on-dashboard ================================================================================ # Replace Widgets on Dashboard ## Replace Widgets on Dashboard **PUT** `/console/v1/dashboards/{id}/widgets` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}/widgets` Replace Widgets on Dashboard Reconcile the complete widget list by ID. Read view=editable or view=references first and include its revision. Preserve widgets with {id}; list exactly the omitted widget IDs in delete_widget_ids to confirm deletion. A revision conflict requires a fresh read and reapplication of the intended edit. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | revision | string | Yes | — | Include the `revision` returned by an editable or references read. Read the dashboard again after a revision conflict. | | widgets | oneOf[] | Yes | — | Provide the complete final list. Use `{ "id": "widget_id" }` to preserve a widget without resending its definition. | | widgets.type | string | No | — | Allowed values: text, header, timeseries, drilldown, funnel, unsupported | | widgets.title | string | No | — | — | | widgets.content | string | No | — | — | | widgets.width | integer | No | — | Constraints: min: 0, max: 12 | | widgets.height | integer | No | — | Constraints: min: 0 | | widgets.id | string | No | — | Constraints: min length: 1 | | widgets.description | string | No | — | — | | widgets.color | string | No | — | Constraints: nullable | | widgets.layout | object | No | — | — | | widgets.layout.row | integer | Yes | — | Constraints: min: 0 | | widgets.layout.column | integer | Yes | — | Constraints: min: 0, max: 11 | | widgets.date_range | object | No | — | Constraints: nullable | | widgets.date_range.start_ds | string | No | — | Constraints: nullable | | widgets.date_range.end_ds | string | No | — | Constraints: nullable | | widgets.date_range.start_offset_days | number | No | — | Constraints: nullable | | widgets.date_range.end_offset_days | number | No | — | Constraints: nullable | | widgets.query | object | No | — | — | | widgets.query.source | object | No | — | — | | widgets.query.source.type | string | Yes | — | Allowed values: event | | widgets.query.source.event_name | string | Yes | — | — | | widgets.query.source.filters | object[] | No | — | — | | widgets.query.source.filters.property | object | Yes | — | — | | widgets.query.source.filters.property.key | string | Yes | — | — | | widgets.query.source.filters.property.column | unknown | Yes | — | — | | widgets.query.source.filters.operator | unknown | Yes | — | — | | widgets.query.source.filters.values | string[] | No | [] | — | | widgets.query.sources | object[] | No | — | — | | widgets.query.sources.type | string | Yes | — | Allowed values: event | | widgets.query.sources.event_name | string | Yes | — | — | | widgets.query.sources.filters | object[] | No | — | — | | widgets.query.sources.filters.property | object | Yes | — | — | | widgets.query.sources.filters.property.key | string | Yes | — | — | | widgets.query.sources.filters.property.column | unknown | Yes | — | — | | widgets.query.sources.filters.operator | unknown | Yes | — | — | | widgets.query.sources.filters.values | string[] | No | [] | — | | widgets.query.aggregation | object or string | No | — | Allowed values: daily, overall | | widgets.query.aggregation.type | unknown | Yes | — | — | | widgets.query.aggregation.property | object | No | — | — | | widgets.query.aggregation.property.key | string | Yes | — | — | | widgets.query.aggregation.property.column | unknown | Yes | — | — | | widgets.query.unit_type | string | No | — | — | | widgets.query.group_bys | object[] | No | — | — | | widgets.query.group_bys.key | string | Yes | — | — | | widgets.query.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.group_bys.metric_source_column | string | No | — | — | | widgets.query.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.viz | object | No | — | — | | widgets.query.viz.chart_type | string | Yes | — | Allowed values: line, timeseries-bar, horizontal-bar, grouped-bar, pie, geo-map, samples, stacked-line, single-value, conversion-rate, conversions, table | | widgets.query.viz.date | object | No | — | — | | widgets.query.viz.date.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.viz.date.window_size | number | No | — | — | | widgets.query.viz.date.offset_days | number | No | — | — | | widgets.query.viz.date.label | string | Yes | — | — | | widgets.query.viz.date.start_ms | number | No | — | — | | widgets.query.viz.date.end_ms | number | No | — | — | | widgets.query.viz.date.excluded_dates_ms | number[] | No | — | — | | widgets.query.viz.date.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.viz.time_range | object | No | — | — | | widgets.query.viz.time_range.start_ms | number | Yes | — | — | | widgets.query.viz.time_range.end_ms | number | Yes | — | — | | widgets.query.viz.time_range.label | string | Yes | — | — | | widgets.query.viz.time_range.is_relative_to_now | boolean | No | — | — | | widgets.query.viz.granularity | string | No | — | Allowed values: month, week, day, hour, 5m, 30m, 1m, auto | | widgets.query.viz.time_comparison | number | No | — | — | | widgets.query.viz.time_comparison_hours | number | No | — | — | | widgets.query.viz.rollup_type | string | No | — | Allowed values: none, avg, sum, cumulative_sum | | widgets.query.viz.rollup_days | number | No | — | — | | widgets.query.viz.y_axis_type | string | No | — | Allowed values: numbers, monetary, percentage, time, time_ns, time_us, time_ms, decimal_bytes, binary_bytes, bits, time_s, percentage_ratio | | widgets.query.viz.cum_sum_rollup | string | No | — | Allowed values: unique, all | | widgets.query.viz.single_value_type | string | No | — | Allowed values: latest, overall | | widgets.query.viz.usage_interval_number_of_days | number | No | — | — | | widgets.query.viz.show_delta_comparison_view | boolean | No | — | — | | widgets.query.viz.is_time_comparison_last_period | boolean | No | — | — | | widgets.query.viz.show_grouped_percentage_breakdown | boolean | No | — | — | | widgets.query.viz.chart_view | string | No | — | Allowed values: chart, legend, chart_legend | | widgets.query.viz.show_percent_difference_compare_option | boolean | No | — | — | | widgets.query.viz.use_widget_granularity_in_dashboard | boolean | No | — | — | | widgets.query.filters | object[] | No | — | — | | widgets.query.filters.property | object | Yes | — | — | | widgets.query.filters.property.key | string | Yes | — | — | | widgets.query.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.filters.property.metric_source_column | string | No | — | — | | widgets.query.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.filters.values | string[] | No | [] | — | | widgets.query.filters.label | string | No | — | — | | widgets.query.cohorts | object[] | No | — | — | | widgets.query.cohorts.id | string | No | — | Constraints: min length: 1 | | widgets.query.cohorts.name | string | No | — | — | | widgets.query.cohorts.unit_type | string | No | — | — | | widgets.query.cohorts.events | object[] | No | — | — | | widgets.query.cohorts.events.event | object | Yes | — | — | | widgets.query.cohorts.events.event.event_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters | object[] | Yes | — | — | | widgets.query.cohorts.events.event.filters.property | object | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.key | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.cohorts.events.event.filters.property.metric_source_column | string | No | — | — | | widgets.query.cohorts.events.event.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.cohorts.events.event.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.cohorts.events.event.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.cohorts.events.event.filters.values | string[] | No | [] | — | | widgets.query.cohorts.events.event.filters.label | string | No | — | — | | widgets.query.cohorts.events.event.alias | string | No | — | — | | widgets.query.cohorts.events.event.is_first_time | boolean | No | — | — | | widgets.query.cohorts.events.event.metric_type | string | No | — | — | | widgets.query.cohorts.events.event.metric_source_id | string | No | — | — | | widgets.query.cohorts.events.event.event_name_column | string | No | — | Constraints: nullable | | widgets.query.cohorts.events.event.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.cohorts.events.operator | string | Yes | — | Allowed values: >, <, >=, <=, = | | widgets.query.cohorts.events.threshold | number | Yes | — | — | | widgets.query.cohorts.events.date_range | object | Yes | — | — | | widgets.query.cohorts.events.date_range.type | string | Yes | — | Allowed values: relative, fixed | | widgets.query.cohorts.events.date_range.window_size | number | No | — | — | | widgets.query.cohorts.events.date_range.offset_days | number | No | — | — | | widgets.query.cohorts.events.date_range.label | string | Yes | — | — | | widgets.query.cohorts.events.date_range.start_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.end_ms | number | No | — | — | | widgets.query.cohorts.events.date_range.excluded_dates_ms | number[] | No | — | — | | widgets.query.cohorts.events.date_range.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widgets.query.cohorts.any_event | boolean | No | — | — | | widgets.query.cohorts.is_verified | boolean | No | — | — | | widgets.query.options | object | No | — | — | | widgets.query.options.exposure_query_mode | string | No | — | Allowed values: all, daily_first, first, fresh | | widgets.query.options.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.group_by_query_limit | integer | No | — | Constraints: min: 0 | | widgets.query.options.separate_chart_per_metric | boolean | No | — | — | | widgets.query.options.force_start_y_at_zero | boolean | No | — | — | | widgets.query.options.include_annotations | boolean | No | — | — | | widgets.query.options.show_all_annotations | boolean | No | — | — | | widgets.query.options.annotation_filters | object | No | — | — | | widgets.query.options.annotation_filters.filter_entity_type | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag | object | No | — | — | | widgets.query.options.annotation_filters.filter_tag.ids | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_tag.operator | string | No | — | — | | widgets.query.options.annotation_filters.filter_target_app | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_environment | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_team | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_creator | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_gate_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_dynamic_config_name | string[] | No | — | — | | widgets.query.options.annotation_filters.filter_experiment_name | string[] | No | — | — | | widgets.query.options.sorting | object | No | — | — | | widgets.query.options.sorting.metric_metadata | object | No | — | — | | widgets.query.options.sorting.metric_metadata.name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.options.sorting.metric_metadata.property | object | No | — | — | | widgets.query.options.sorting.metric_metadata.property.key | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.options.sorting.metric_metadata.property.metric_source_column | string | No | — | — | | widgets.query.options.sorting.metric_metadata.property.source | object | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.options.sorting.metric_metadata.property.source.experiment_name | string | Yes | — | — | | widgets.query.options.sorting.metric_metadata.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_metadata.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.options.sorting.metric_symbol | string | No | — | — | | widgets.query.options.sorting.sort_ascending | boolean | No | — | — | | widgets.query.options.sampling_enabled | boolean | No | — | — | | widgets.query.options.include_test_events | boolean | No | — | — | | widgets.query.options.filter_bot_data | boolean | No | — | — | | widgets.query.options.enable_id_resolution | boolean | No | — | — | | widgets.query.options.is_precomputed_only | boolean | No | — | — | | widgets.query.options.default_id_type | string | No | — | Constraints: nullable | | widgets.query.options.show_table_only | boolean | No | — | — | | widgets.query.series | object[] | No | — | — | | widgets.query.series.id | string | No | — | — | | widgets.query.series.source | oneOf | Yes | — | Constraints: object | | widgets.query.series.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.series.source.event_name | string | No | — | — | | widgets.query.series.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.series.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.series.source.name | string | No | — | — | | widgets.query.series.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.series.definition | object | No | — | — | | widgets.query.series.definition.events | object[] | Yes | — | — | | widgets.query.series.definition.events.event_name | string | Yes | — | — | | widgets.query.series.definition.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.events.filters.label | string | No | — | — | | widgets.query.series.definition.events.alias | string | No | — | — | | widgets.query.series.definition.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.events.metric_type | string | No | — | — | | widgets.query.series.definition.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.aggregation | object | Yes | — | — | | widgets.query.series.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.aggregation.property | object | No | — | — | | widgets.query.series.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite | object | No | — | — | | widgets.query.series.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.series.definition.composite.numerator | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.composite.denominator | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.series.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.series.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.series.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.series.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.series.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.series.unit_type | string | No | — | — | | widgets.query.series.filters | object[] | No | — | — | | widgets.query.series.filters.property | object | Yes | — | — | | widgets.query.series.filters.property.key | string | Yes | — | — | | widgets.query.series.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.filters.property.metric_source_column | string | No | — | — | | widgets.query.series.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.series.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.series.filters.values | string[] | No | [] | — | | widgets.query.series.filters.label | string | No | — | — | | widgets.query.series.group_bys | object[] | No | — | — | | widgets.query.series.group_bys.key | string | Yes | — | — | | widgets.query.series.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.series.group_bys.metric_source_column | string | No | — | — | | widgets.query.series.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.series.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.series.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.series.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.series.alias | string | No | — | — | | widgets.query.series.hidden | boolean | No | — | — | | widgets.query.formulas | object[] | No | — | — | | widgets.query.formulas.id | string | No | — | — | | widgets.query.formulas.formula | string | Yes | — | — | | widgets.query.formulas.name | string | No | — | — | | widgets.query.formulas.hidden | boolean | No | — | — | | widgets.query.formulas.coalesce_nulls_as_zeroes | boolean | No | — | — | | widgets.query.formulas.highlight_as | string | No | — | Allowed values: error, warning | | widgets.query.steps | oneOf[] | No | — | — | | widgets.query.steps.event_name | string | No | — | — | | widgets.query.steps.filters | object[] | No | — | — | | widgets.query.steps.filters.property | object | Yes | — | — | | widgets.query.steps.filters.property.key | string | Yes | — | — | | widgets.query.steps.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.filters.values | string[] | No | [] | — | | widgets.query.steps.filters.label | string | No | — | — | | widgets.query.steps.events | object[] | No | — | — | | widgets.query.steps.events.event_name | string | Yes | — | — | | widgets.query.steps.events.filters | object[] | Yes | — | — | | widgets.query.steps.events.filters.property | object | Yes | — | — | | widgets.query.steps.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.events.filters.values | string[] | No | [] | — | | widgets.query.steps.events.filters.label | string | No | — | — | | widgets.query.steps.events.alias | string | No | — | — | | widgets.query.steps.events.is_first_time | boolean | No | — | — | | widgets.query.steps.events.metric_type | string | No | — | — | | widgets.query.steps.events.metric_source_id | string | No | — | — | | widgets.query.steps.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric | object | No | — | — | | widgets.query.steps.metric.id | string | No | — | — | | widgets.query.steps.metric.source | oneOf | Yes | — | Constraints: object | | widgets.query.steps.metric.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widgets.query.steps.metric.source.event_name | string | No | — | — | | widgets.query.steps.metric.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widgets.query.steps.metric.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widgets.query.steps.metric.source.name | string | No | — | — | | widgets.query.steps.metric.source.table_config_id | string | No | — | Constraints: min length: 1 | | widgets.query.steps.metric.definition | object | No | — | — | | widgets.query.steps.metric.definition.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite | object | No | — | — | | widgets.query.steps.metric.definition.composite.type | string | Yes | — | Allowed values: ratio | | widgets.query.steps.metric.definition.composite.numerator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.numerator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.numerator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.composite.denominator | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.definition.composite.denominator.events.filters.label | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.alias | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_type | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.steps.metric.definition.composite.denominator.aggregation | object | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property | object | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widgets.query.steps.metric.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widgets.query.steps.metric.unit_type | string | No | — | — | | widgets.query.steps.metric.filters | object[] | No | — | — | | widgets.query.steps.metric.filters.property | object | Yes | — | — | | widgets.query.steps.metric.filters.property.key | string | Yes | — | — | | widgets.query.steps.metric.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.filters.property.metric_source_column | string | No | — | — | | widgets.query.steps.metric.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.steps.metric.filters.values | string[] | No | [] | — | | widgets.query.steps.metric.filters.label | string | No | — | — | | widgets.query.steps.metric.group_bys | object[] | No | — | — | | widgets.query.steps.metric.group_bys.key | string | Yes | — | — | | widgets.query.steps.metric.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.steps.metric.group_bys.metric_source_column | string | No | — | — | | widgets.query.steps.metric.group_bys.source | object | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.steps.metric.group_bys.source.experiment_name | string | Yes | — | — | | widgets.query.steps.metric.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.steps.metric.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.steps.metric.alias | string | No | — | — | | widgets.query.steps.metric.hidden | boolean | No | — | — | | widgets.query.steps.alias | string | No | — | — | | widgets.query.steps.is_metric_expanded | boolean | No | — | — | | widgets.query.steps.is_optional | boolean | No | — | — | | widgets.query.steps.should_compare_events | boolean | No | — | — | | widgets.query.conversion_window | object | No | — | — | | widgets.query.conversion_window.value | integer | Yes | — | Constraints: min: 0 | | widgets.query.conversion_window.unit | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.chart_type | string | No | — | Allowed values: conversion-rate, conversions | | widgets.query.measurement | string | No | — | Allowed values: conversion_rate, conversion_rate_over_time, time_to_convert | | widgets.query.is_sequential | boolean | No | — | — | | widgets.query.use_uniques_units | boolean | No | — | — | | widgets.query.use_persistent_group_bys | boolean | No | — | — | | widgets.query.group_by_limit | integer | No | — | Constraints: min: 0 | | widgets.query.sort_by_conversion_rate | boolean | No | — | — | | widgets.query.sort_order_is_descending | boolean | No | — | — | | widgets.query.time_to_convert_buckets | object | No | — | — | | widgets.query.time_to_convert_buckets.range_min | number | Yes | — | — | | widgets.query.time_to_convert_buckets.range_max | number | Yes | — | — | | widgets.query.time_to_convert_buckets.interval_size | number | Yes | — | Constraints: min: 0 | | widgets.query.time_to_convert_buckets.bucket_units_min_max | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_buckets.bucket_units_bucket_size | string | Yes | — | Allowed values: second, minute, hour, day | | widgets.query.time_to_convert_unit | string | No | — | Allowed values: second, minute, hour, day | | widgets.query.show_sum_property_value_last_step | boolean | No | — | — | | widgets.query.property_value_to_sum | string | No | — | — | | widgets.query.exclude_units_who_did_event | object | No | — | — | | widgets.query.exclude_units_who_did_event.events | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.event_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters | object[] | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property | object | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.key | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widgets.query.exclude_units_who_did_event.events.filters.property.metric_source_column | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source | object | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widgets.query.exclude_units_who_did_event.events.filters.property.source.experiment_name | string | Yes | — | — | | widgets.query.exclude_units_who_did_event.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widgets.query.exclude_units_who_did_event.events.filters.values | string[] | No | [] | — | | widgets.query.exclude_units_who_did_event.events.filters.label | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.alias | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.is_first_time | boolean | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_type | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.metric_source_id | string | No | — | — | | widgets.query.exclude_units_who_did_event.events.event_name_column | string | No | — | Constraints: nullable | | widgets.query.exclude_units_who_did_event.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widgets.query.exclude_units_who_did_event.between_steps | object | No | — | — | | widgets.query.exclude_units_who_did_event.between_steps.start | integer | Yes | — | Constraints: min: 0 | | widgets.query.exclude_units_who_did_event.between_steps.end | integer | Yes | — | Constraints: min: 0 | | widgets.reason | string | No | — | — | | widgets.widget_type | string | No | — | — | | widgets.query_type | string | No | — | — | | widgets.chart_type | string | No | — | — | | delete_widget_ids | string[] | No | — | List exactly the existing widget IDs omitted from `widgets`. Omission alone never confirms deletion. | | defaults | object | No | — | Constraints: nullable | | defaults.date | oneOf | No | — | Constraints: object | | defaults.date.value | integer or number | No | — | Constraints: min: 0 | | defaults.date.unit | string | No | — | Allowed values: day, week, month, minute, hour | | defaults.date.mode | string | No | — | Allowed values: chart_default, since, relative | | defaults.date.since_ms | number | No | — | — | | defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | | max_cols | integer | No | — | Constraints: format: int64, min: 0 | ## Response (application/json) **200** — Replace dashboard widgets response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.ids | string[] | Yes | — | — | | data.revision | string | Yes | — | — | | data.deleted_ids | string[] | Yes | — | — | ```json { "message": "Dashboard Widgets Replaced Successfully", "data": { "ids": [ "widget_id" ], "revision": "d1.revision", "deleted_ids": [] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **409** — Confirm the exact omitted widget IDs before deletion. **412** — The revision changed. Read the dashboard again before replacing widgets. ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dashboards/{id}/widgets" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dashboards/{id}/widgets", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}/widgets", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}/widgets"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dashboards/{id}/widgets", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}/widgets")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}/widgets") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Dashboard URL: https://docs.statsig.com/api-reference/dashboards/update-dashboard ================================================================================ # Update Dashboard ## Update Dashboard **PATCH** `/console/v1/dashboards/{id}` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}` Update Dashboard Update dashboard name, description, or defaults. Include the revision from an editable or references read. Omitted fields remain unchanged; an empty description clears it and defaults:null resets dashboard defaults. Read again after a revision conflict. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | revision | string | Yes | — | Include the `revision` returned by an editable or references read. Read the dashboard again after a revision conflict. | | name | string | No | — | Constraints: min length: 1, max length: 200 | | description | string | No | — | Set an empty string to clear the dashboard description. Constraints: max length: 10000 | | defaults | object | No | — | Update only the supplied defaults. Set `null` to reset to 30 days and daily granularity. Constraints: nullable | | defaults.date | oneOf | No | — | Constraints: object | | defaults.date.value | integer or number | No | — | Constraints: min: 0 | | defaults.date.unit | string | No | — | Allowed values: day, week, month, minute, hour | | defaults.date.mode | string | No | — | Allowed values: chart_default, since, relative | | defaults.date.since_ms | number | No | — | — | | defaults.granularity | string | No | — | Allowed values: auto, daily, weekly, monthly | ## Response (application/json) **200** — Updated dashboard identity and revision. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.revision | string | Yes | — | — | ```json { "message": "string", "data": { "id": "string", "revision": "string" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **412** — The revision changed. Read the dashboard again and reapply the edit. ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/dashboards/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/dashboards/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/dashboards/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Dashboard Widget URL: https://docs.statsig.com/api-reference/dashboards/update-dashboard-widget ================================================================================ # Update Dashboard Widget ## Update Dashboard Widget **PATCH** `/console/v1/dashboards/{id}/widgets/{widgetId}` Full URL: `https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}` Update Dashboard Widget Edit one widget using a full supported definition or sparse metadata/layout/query patch and the dashboard revision. Query and arrays replace their complete previous values. Omitted fields remain unchanged. Unsupported widgets allow layout-only edits. Read again after a revision conflict. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | dashboard id | | widgetId (path) | string | Yes | — | widget id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | revision | string | Yes | — | Include the `revision` returned by an editable or references read. Read the dashboard again after a revision conflict. | | widget | oneOf | Yes | — | Constraints: oneOf (oneOf (object), object), object | | widget.type | string | No | — | Allowed values: text, header, timeseries, drilldown, funnel, unsupported | | widget.title | string | No | — | — | | widget.content | string | No | — | — | | widget.width | integer | No | — | Constraints: min: 0, max: 12 | | widget.height | integer | No | — | Constraints: min: 0 | | widget.id | string | No | — | — | | widget.description | string | No | — | — | | widget.color | string | No | — | Constraints: nullable | | widget.layout | object | No | — | — | | widget.layout.row | integer | Yes | — | Constraints: min: 0 | | widget.layout.column | integer | Yes | — | Constraints: min: 0, max: 11 | | widget.date_range | object | No | — | Constraints: nullable | | widget.date_range.start_ds | string | No | — | Constraints: nullable | | widget.date_range.end_ds | string | No | — | Constraints: nullable | | widget.date_range.start_offset_days | number | No | — | Constraints: nullable | | widget.date_range.end_offset_days | number | No | — | Constraints: nullable | | widget.query | object | No | — | Replace the complete query. Arrays replace existing arrays rather than merging by position. | | widget.query.source | object | No | — | — | | widget.query.source.type | string | Yes | — | Allowed values: event | | widget.query.source.event_name | string | Yes | — | — | | widget.query.source.filters | object[] | No | — | — | | widget.query.source.filters.property | object | Yes | — | — | | widget.query.source.filters.property.key | string | Yes | — | — | | widget.query.source.filters.property.column | unknown | Yes | — | — | | widget.query.source.filters.operator | unknown | Yes | — | — | | widget.query.source.filters.values | string[] | No | [] | — | | widget.query.sources | object[] | No | — | — | | widget.query.sources.type | string | Yes | — | Allowed values: event | | widget.query.sources.event_name | string | Yes | — | — | | widget.query.sources.filters | object[] | No | — | — | | widget.query.sources.filters.property | object | Yes | — | — | | widget.query.sources.filters.property.key | string | Yes | — | — | | widget.query.sources.filters.property.column | unknown | Yes | — | — | | widget.query.sources.filters.operator | unknown | Yes | — | — | | widget.query.sources.filters.values | string[] | No | [] | — | | widget.query.aggregation | object or string | No | — | Allowed values: daily, overall | | widget.query.aggregation.type | unknown | Yes | — | — | | widget.query.aggregation.property | object | No | — | — | | widget.query.aggregation.property.key | string | Yes | — | — | | widget.query.aggregation.property.column | unknown | Yes | — | — | | widget.query.unit_type | string | No | — | — | | widget.query.group_bys | object[] | No | — | — | | widget.query.group_bys.key | string | Yes | — | — | | widget.query.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.group_bys.metric_source_column | string | No | — | — | | widget.query.group_bys.source | object | No | — | Constraints: nullable | | widget.query.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.group_bys.source.experiment_name | string | Yes | — | — | | widget.query.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widget.query.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.viz | object | No | — | — | | widget.query.viz.chart_type | string | Yes | — | Allowed values: line, timeseries-bar, horizontal-bar, grouped-bar, pie, geo-map, samples, stacked-line, single-value, conversion-rate, conversions, table | | widget.query.viz.date | object | No | — | — | | widget.query.viz.date.type | string | Yes | — | Allowed values: relative, fixed | | widget.query.viz.date.window_size | number | No | — | — | | widget.query.viz.date.offset_days | number | No | — | — | | widget.query.viz.date.label | string | Yes | — | — | | widget.query.viz.date.start_ms | number | No | — | — | | widget.query.viz.date.end_ms | number | No | — | — | | widget.query.viz.date.excluded_dates_ms | number[] | No | — | — | | widget.query.viz.date.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widget.query.viz.time_range | object | No | — | — | | widget.query.viz.time_range.start_ms | number | Yes | — | — | | widget.query.viz.time_range.end_ms | number | Yes | — | — | | widget.query.viz.time_range.label | string | Yes | — | — | | widget.query.viz.time_range.is_relative_to_now | boolean | No | — | — | | widget.query.viz.granularity | string | No | — | Allowed values: month, week, day, hour, 5m, 30m, 1m, auto | | widget.query.viz.time_comparison | number | No | — | — | | widget.query.viz.time_comparison_hours | number | No | — | — | | widget.query.viz.rollup_type | string | No | — | Allowed values: none, avg, sum, cumulative_sum | | widget.query.viz.rollup_days | number | No | — | — | | widget.query.viz.y_axis_type | string | No | — | Allowed values: numbers, monetary, percentage, time, time_ns, time_us, time_ms, decimal_bytes, binary_bytes, bits, time_s, percentage_ratio | | widget.query.viz.cum_sum_rollup | string | No | — | Allowed values: unique, all | | widget.query.viz.single_value_type | string | No | — | Allowed values: latest, overall | | widget.query.viz.usage_interval_number_of_days | number | No | — | — | | widget.query.viz.show_delta_comparison_view | boolean | No | — | — | | widget.query.viz.is_time_comparison_last_period | boolean | No | — | — | | widget.query.viz.show_grouped_percentage_breakdown | boolean | No | — | — | | widget.query.viz.chart_view | string | No | — | Allowed values: chart, legend, chart_legend | | widget.query.viz.show_percent_difference_compare_option | boolean | No | — | — | | widget.query.viz.use_widget_granularity_in_dashboard | boolean | No | — | — | | widget.query.filters | object[] | No | — | — | | widget.query.filters.property | object | Yes | — | — | | widget.query.filters.property.key | string | Yes | — | — | | widget.query.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.filters.property.metric_source_column | string | No | — | — | | widget.query.filters.property.source | object | No | — | Constraints: nullable | | widget.query.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.filters.values | string[] | No | [] | — | | widget.query.filters.label | string | No | — | — | | widget.query.cohorts | object[] | No | — | — | | widget.query.cohorts.id | string | No | — | Constraints: min length: 1 | | widget.query.cohorts.name | string | No | — | — | | widget.query.cohorts.unit_type | string | No | — | — | | widget.query.cohorts.events | object[] | No | — | — | | widget.query.cohorts.events.event | object | Yes | — | — | | widget.query.cohorts.events.event.event_name | string | Yes | — | — | | widget.query.cohorts.events.event.filters | object[] | Yes | — | — | | widget.query.cohorts.events.event.filters.property | object | Yes | — | — | | widget.query.cohorts.events.event.filters.property.key | string | Yes | — | — | | widget.query.cohorts.events.event.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.cohorts.events.event.filters.property.metric_source_column | string | No | — | — | | widget.query.cohorts.events.event.filters.property.source | object | No | — | Constraints: nullable | | widget.query.cohorts.events.event.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.cohorts.events.event.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.cohorts.events.event.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.cohorts.events.event.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.cohorts.events.event.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.cohorts.events.event.filters.values | string[] | No | [] | — | | widget.query.cohorts.events.event.filters.label | string | No | — | — | | widget.query.cohorts.events.event.alias | string | No | — | — | | widget.query.cohorts.events.event.is_first_time | boolean | No | — | — | | widget.query.cohorts.events.event.metric_type | string | No | — | — | | widget.query.cohorts.events.event.metric_source_id | string | No | — | — | | widget.query.cohorts.events.event.event_name_column | string | No | — | Constraints: nullable | | widget.query.cohorts.events.event.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.cohorts.events.operator | string | Yes | — | Allowed values: >, <, >=, <=, = | | widget.query.cohorts.events.threshold | number | Yes | — | — | | widget.query.cohorts.events.date_range | object | Yes | — | — | | widget.query.cohorts.events.date_range.type | string | Yes | — | Allowed values: relative, fixed | | widget.query.cohorts.events.date_range.window_size | number | No | — | — | | widget.query.cohorts.events.date_range.offset_days | number | No | — | — | | widget.query.cohorts.events.date_range.label | string | Yes | — | — | | widget.query.cohorts.events.date_range.start_ms | number | No | — | — | | widget.query.cohorts.events.date_range.end_ms | number | No | — | — | | widget.query.cohorts.events.date_range.excluded_dates_ms | number[] | No | — | — | | widget.query.cohorts.events.date_range.is_relative_to_now | boolean | No | — | When `true`, the Console uses a recognized relative `label` to refresh the saved date bounds when it loads the chart. | | widget.query.cohorts.any_event | boolean | No | — | — | | widget.query.cohorts.is_verified | boolean | No | — | — | | widget.query.options | object | No | — | — | | widget.query.options.exposure_query_mode | string | No | — | Allowed values: all, daily_first, first, fresh | | widget.query.options.group_by_limit | integer | No | — | Constraints: min: 0 | | widget.query.options.group_by_query_limit | integer | No | — | Constraints: min: 0 | | widget.query.options.separate_chart_per_metric | boolean | No | — | — | | widget.query.options.force_start_y_at_zero | boolean | No | — | — | | widget.query.options.include_annotations | boolean | No | — | — | | widget.query.options.show_all_annotations | boolean | No | — | — | | widget.query.options.annotation_filters | object | No | — | — | | widget.query.options.annotation_filters.filter_entity_type | string[] | No | — | — | | widget.query.options.annotation_filters.filter_tag | object | No | — | — | | widget.query.options.annotation_filters.filter_tag.ids | string[] | No | — | — | | widget.query.options.annotation_filters.filter_tag.operator | string | No | — | — | | widget.query.options.annotation_filters.filter_target_app | string[] | No | — | — | | widget.query.options.annotation_filters.filter_environment | string[] | No | — | — | | widget.query.options.annotation_filters.filter_team | string[] | No | — | — | | widget.query.options.annotation_filters.filter_creator | string[] | No | — | — | | widget.query.options.annotation_filters.filter_gate_name | string[] | No | — | — | | widget.query.options.annotation_filters.filter_dynamic_config_name | string[] | No | — | — | | widget.query.options.annotation_filters.filter_experiment_name | string[] | No | — | — | | widget.query.options.sorting | object | No | — | — | | widget.query.options.sorting.metric_metadata | object | No | — | — | | widget.query.options.sorting.metric_metadata.name | string | Yes | — | — | | widget.query.options.sorting.metric_metadata.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.options.sorting.metric_metadata.property | object | No | — | — | | widget.query.options.sorting.metric_metadata.property.key | string | Yes | — | — | | widget.query.options.sorting.metric_metadata.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.options.sorting.metric_metadata.property.metric_source_column | string | No | — | — | | widget.query.options.sorting.metric_metadata.property.source | object | No | — | Constraints: nullable | | widget.query.options.sorting.metric_metadata.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.options.sorting.metric_metadata.property.source.experiment_name | string | Yes | — | — | | widget.query.options.sorting.metric_metadata.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.options.sorting.metric_metadata.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.options.sorting.metric_symbol | string | No | — | — | | widget.query.options.sorting.sort_ascending | boolean | No | — | — | | widget.query.options.sampling_enabled | boolean | No | — | — | | widget.query.options.include_test_events | boolean | No | — | — | | widget.query.options.filter_bot_data | boolean | No | — | — | | widget.query.options.enable_id_resolution | boolean | No | — | — | | widget.query.options.is_precomputed_only | boolean | No | — | — | | widget.query.options.default_id_type | string | No | — | Constraints: nullable | | widget.query.options.show_table_only | boolean | No | — | — | | widget.query.series | object[] | No | — | — | | widget.query.series.id | string | No | — | — | | widget.query.series.source | object | Yes | — | — | | widget.query.series.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widget.query.series.source.event_name | string | No | — | — | | widget.query.series.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widget.query.series.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widget.query.series.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widget.query.series.source.name | string | No | — | — | | widget.query.series.source.table_config_id | string | No | — | Constraints: min length: 1 | | widget.query.series.definition | object | No | — | — | | widget.query.series.definition.events | object[] | Yes | — | — | | widget.query.series.definition.events.event_name | string | Yes | — | — | | widget.query.series.definition.events.filters | object[] | Yes | — | — | | widget.query.series.definition.events.filters.property | object | Yes | — | — | | widget.query.series.definition.events.filters.property.key | string | Yes | — | — | | widget.query.series.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.events.filters.property.metric_source_column | string | No | — | — | | widget.query.series.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.series.definition.events.filters.values | string[] | No | [] | — | | widget.query.series.definition.events.filters.label | string | No | — | — | | widget.query.series.definition.events.alias | string | No | — | — | | widget.query.series.definition.events.is_first_time | boolean | No | — | — | | widget.query.series.definition.events.metric_type | string | No | — | — | | widget.query.series.definition.events.metric_source_id | string | No | — | — | | widget.query.series.definition.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.series.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.series.definition.aggregation | object | Yes | — | — | | widget.query.series.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.series.definition.aggregation.property | object | No | — | — | | widget.query.series.definition.aggregation.property.key | string | Yes | — | — | | widget.query.series.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.aggregation.property.metric_source_column | string | No | — | — | | widget.query.series.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.series.definition.composite | object | No | — | — | | widget.query.series.definition.composite.type | string | Yes | — | Allowed values: ratio | | widget.query.series.definition.composite.numerator | object | Yes | — | — | | widget.query.series.definition.composite.numerator.events | object[] | Yes | — | — | | widget.query.series.definition.composite.numerator.events.event_name | string | Yes | — | — | | widget.query.series.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widget.query.series.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widget.query.series.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widget.query.series.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widget.query.series.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.series.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widget.query.series.definition.composite.numerator.events.filters.label | string | No | — | — | | widget.query.series.definition.composite.numerator.events.alias | string | No | — | — | | widget.query.series.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widget.query.series.definition.composite.numerator.events.metric_type | string | No | — | — | | widget.query.series.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widget.query.series.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.series.definition.composite.numerator.aggregation | object | Yes | — | — | | widget.query.series.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.series.definition.composite.numerator.aggregation.property | object | No | — | — | | widget.query.series.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widget.query.series.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widget.query.series.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.series.definition.composite.denominator | object | Yes | — | — | | widget.query.series.definition.composite.denominator.events | object[] | Yes | — | — | | widget.query.series.definition.composite.denominator.events.event_name | string | Yes | — | — | | widget.query.series.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widget.query.series.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widget.query.series.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widget.query.series.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widget.query.series.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.series.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widget.query.series.definition.composite.denominator.events.filters.label | string | No | — | — | | widget.query.series.definition.composite.denominator.events.alias | string | No | — | — | | widget.query.series.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widget.query.series.definition.composite.denominator.events.metric_type | string | No | — | — | | widget.query.series.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widget.query.series.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.series.definition.composite.denominator.aggregation | object | Yes | — | — | | widget.query.series.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.series.definition.composite.denominator.aggregation.property | object | No | — | — | | widget.query.series.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widget.query.series.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widget.query.series.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.series.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.series.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widget.query.series.unit_type | string | No | — | — | | widget.query.series.filters | object[] | No | — | — | | widget.query.series.filters.property | object | Yes | — | — | | widget.query.series.filters.property.key | string | Yes | — | — | | widget.query.series.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.filters.property.metric_source_column | string | No | — | — | | widget.query.series.filters.property.source | object | No | — | Constraints: nullable | | widget.query.series.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.series.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.series.filters.values | string[] | No | [] | — | | widget.query.series.filters.label | string | No | — | — | | widget.query.series.group_bys | object[] | No | — | — | | widget.query.series.group_bys.key | string | Yes | — | — | | widget.query.series.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.series.group_bys.metric_source_column | string | No | — | — | | widget.query.series.group_bys.source | object | No | — | Constraints: nullable | | widget.query.series.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.series.group_bys.source.experiment_name | string | Yes | — | — | | widget.query.series.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widget.query.series.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.series.alias | string | No | — | — | | widget.query.series.hidden | boolean | No | — | — | | widget.query.formulas | object[] | No | — | — | | widget.query.formulas.id | string | No | — | — | | widget.query.formulas.formula | string | Yes | — | — | | widget.query.formulas.name | string | No | — | — | | widget.query.formulas.hidden | boolean | No | — | — | | widget.query.formulas.coalesce_nulls_as_zeroes | boolean | No | — | — | | widget.query.formulas.highlight_as | string | No | — | Allowed values: error, warning | | widget.query.steps | object[] | No | — | — | | widget.query.steps.event_name | string | No | — | — | | widget.query.steps.filters | object[] | No | — | — | | widget.query.steps.filters.property | object | Yes | — | — | | widget.query.steps.filters.property.key | string | Yes | — | — | | widget.query.steps.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.filters.values | string[] | No | [] | — | | widget.query.steps.filters.label | string | No | — | — | | widget.query.steps.events | object[] | No | — | — | | widget.query.steps.events.event_name | string | Yes | — | — | | widget.query.steps.events.filters | object[] | Yes | — | — | | widget.query.steps.events.filters.property | object | Yes | — | — | | widget.query.steps.events.filters.property.key | string | Yes | — | — | | widget.query.steps.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.events.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.events.filters.values | string[] | No | [] | — | | widget.query.steps.events.filters.label | string | No | — | — | | widget.query.steps.events.alias | string | No | — | — | | widget.query.steps.events.is_first_time | boolean | No | — | — | | widget.query.steps.events.metric_type | string | No | — | — | | widget.query.steps.events.metric_source_id | string | No | — | — | | widget.query.steps.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.steps.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.steps.metric | object | No | — | — | | widget.query.steps.metric.id | string | No | — | — | | widget.query.steps.metric.source | object | Yes | — | — | | widget.query.steps.metric.source.type | string | Yes | — | Allowed values: event, metric, metric_source, exposure, table_config | | widget.query.steps.metric.source.event_name | string | No | — | — | | widget.query.steps.metric.source.metric_id | string | No | — | Constraints: pattern: ^.+::[^:]+$ | | widget.query.steps.metric.source.metric_source_id | string | No | — | Constraints: min length: 1 | | widget.query.steps.metric.source.kind | string | No | — | Allowed values: experiment, gate, config, layer | | widget.query.steps.metric.source.name | string | No | — | — | | widget.query.steps.metric.source.table_config_id | string | No | — | Constraints: min length: 1 | | widget.query.steps.metric.definition | object | No | — | — | | widget.query.steps.metric.definition.events | object[] | Yes | — | — | | widget.query.steps.metric.definition.events.event_name | string | Yes | — | — | | widget.query.steps.metric.definition.events.filters | object[] | Yes | — | — | | widget.query.steps.metric.definition.events.filters.property | object | Yes | — | — | | widget.query.steps.metric.definition.events.filters.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.events.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.metric.definition.events.filters.values | string[] | No | [] | — | | widget.query.steps.metric.definition.events.filters.label | string | No | — | — | | widget.query.steps.metric.definition.events.alias | string | No | — | — | | widget.query.steps.metric.definition.events.is_first_time | boolean | No | — | — | | widget.query.steps.metric.definition.events.metric_type | string | No | — | — | | widget.query.steps.metric.definition.events.metric_source_id | string | No | — | — | | widget.query.steps.metric.definition.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.steps.metric.definition.aggregation | object | Yes | — | — | | widget.query.steps.metric.definition.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.steps.metric.definition.aggregation.property | object | No | — | — | | widget.query.steps.metric.definition.aggregation.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.aggregation.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.steps.metric.definition.composite | object | No | — | — | | widget.query.steps.metric.definition.composite.type | string | Yes | — | Allowed values: ratio | | widget.query.steps.metric.definition.composite.numerator | object | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events | object[] | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.event_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters | object[] | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.property | object | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.metric.definition.composite.numerator.events.filters.values | string[] | No | [] | — | | widget.query.steps.metric.definition.composite.numerator.events.filters.label | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.alias | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.is_first_time | boolean | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.metric_type | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.metric_source_id | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.steps.metric.definition.composite.numerator.aggregation | object | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.steps.metric.definition.composite.numerator.aggregation.property | object | No | — | — | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.numerator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.steps.metric.definition.composite.denominator | object | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events | object[] | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.event_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters | object[] | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.property | object | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.metric.definition.composite.denominator.events.filters.values | string[] | No | [] | — | | widget.query.steps.metric.definition.composite.denominator.events.filters.label | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.alias | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.is_first_time | boolean | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.metric_type | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.metric_source_id | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.steps.metric.definition.composite.denominator.aggregation | object | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.aggregation.type | string | Yes | — | Allowed values: COUNT, COUNT_DISTINCT, COUNT_DISTINCT_VALUE, COUNT_DISTINCT_VALUE_PER_USER, AVG_COUNT_PER_USER, MAX_COUNT_PER_USER, MIN_COUNT_PER_USER, P50_COUNT_PER_USER, P75_COUNT_PER_USER, P90_COUNT_PER_USER, P95_COUNT_PER_USER, P99_COUNT_PER_USER, SUM, AVG, CONVERSION_RATE, FUNNEL, P50, P75, P90, P95, P99, MAX, MIN, OTEL_COUNTER__SUM, OTEL_COUNTER__AVG, OTEL_COUNTER__MIN, OTEL_COUNTER__MAX, OTEL_HISTOGRAM__COUNT, OTEL_HISTOGRAM__SUM, OTEL_HISTOGRAM__AVG, OTEL_HISTOGRAM__P50, OTEL_HISTOGRAM__P75, OTEL_HISTOGRAM__P90, OTEL_HISTOGRAM__P95, OTEL_HISTOGRAM__P99, OTEL_GAUGE__AVG, OTEL_GAUGE__SUM, OTEL_GAUGE__MIN, OTEL_GAUGE__MAX | | widget.query.steps.metric.definition.composite.denominator.aggregation.property | object | No | — | — | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.key | string | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.aggregation.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.definition.composite.denominator.uniques_window | string | No | — | Allowed values: daily, weekly, monthly, default | | widget.query.steps.metric.definition.null_handling | string | No | — | Allowed values: skip, treat_as_zero | | widget.query.steps.metric.unit_type | string | No | — | — | | widget.query.steps.metric.filters | object[] | No | — | — | | widget.query.steps.metric.filters.property | object | Yes | — | — | | widget.query.steps.metric.filters.property.key | string | Yes | — | — | | widget.query.steps.metric.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.filters.property.metric_source_column | string | No | — | — | | widget.query.steps.metric.filters.property.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.steps.metric.filters.values | string[] | No | [] | — | | widget.query.steps.metric.filters.label | string | No | — | — | | widget.query.steps.metric.group_bys | object[] | No | — | — | | widget.query.steps.metric.group_bys.key | string | Yes | — | — | | widget.query.steps.metric.group_bys.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.steps.metric.group_bys.metric_source_column | string | No | — | — | | widget.query.steps.metric.group_bys.source | object | No | — | Constraints: nullable | | widget.query.steps.metric.group_bys.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.steps.metric.group_bys.source.experiment_name | string | Yes | — | — | | widget.query.steps.metric.group_bys.source.rule_id | string | No | — | Constraints: nullable | | widget.query.steps.metric.group_bys.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.steps.metric.alias | string | No | — | — | | widget.query.steps.metric.hidden | boolean | No | — | — | | widget.query.steps.alias | string | No | — | — | | widget.query.steps.is_metric_expanded | boolean | No | — | — | | widget.query.steps.is_optional | boolean | No | — | — | | widget.query.steps.should_compare_events | boolean | No | — | — | | widget.query.conversion_window | object | No | — | — | | widget.query.conversion_window.value | integer | Yes | — | Constraints: min: 0 | | widget.query.conversion_window.unit | string | Yes | — | Allowed values: second, minute, hour, day | | widget.query.chart_type | string | No | — | Allowed values: conversion-rate, conversions | | widget.query.measurement | string | No | — | Allowed values: conversion_rate, conversion_rate_over_time, time_to_convert | | widget.query.is_sequential | boolean | No | — | — | | widget.query.use_uniques_units | boolean | No | — | — | | widget.query.use_persistent_group_bys | boolean | No | — | — | | widget.query.group_by_limit | integer | No | — | Constraints: min: 0 | | widget.query.sort_by_conversion_rate | boolean | No | — | — | | widget.query.sort_order_is_descending | boolean | No | — | — | | widget.query.time_to_convert_buckets | object | No | — | — | | widget.query.time_to_convert_buckets.range_min | number | Yes | — | — | | widget.query.time_to_convert_buckets.range_max | number | Yes | — | — | | widget.query.time_to_convert_buckets.interval_size | number | Yes | — | Constraints: min: 0 | | widget.query.time_to_convert_buckets.bucket_units_min_max | string | Yes | — | Allowed values: second, minute, hour, day | | widget.query.time_to_convert_buckets.bucket_units_bucket_size | string | Yes | — | Allowed values: second, minute, hour, day | | widget.query.time_to_convert_unit | string | No | — | Allowed values: second, minute, hour, day | | widget.query.show_sum_property_value_last_step | boolean | No | — | — | | widget.query.property_value_to_sum | string | No | — | — | | widget.query.exclude_units_who_did_event | object | No | — | — | | widget.query.exclude_units_who_did_event.events | object[] | Yes | — | — | | widget.query.exclude_units_who_did_event.events.event_name | string | Yes | — | — | | widget.query.exclude_units_who_did_event.events.filters | object[] | Yes | — | — | | widget.query.exclude_units_who_did_event.events.filters.property | object | Yes | — | — | | widget.query.exclude_units_who_did_event.events.filters.property.key | string | Yes | — | — | | widget.query.exclude_units_who_did_event.events.filters.property.column | string | Yes | — | Property namespace, such as `user_object` or `metric_source_metadata`. | | widget.query.exclude_units_who_did_event.events.filters.property.metric_source_column | string | No | — | — | | widget.query.exclude_units_who_did_event.events.filters.property.source | object | No | — | Constraints: nullable | | widget.query.exclude_units_who_did_event.events.filters.property.source.type | string | Yes | — | Allowed values: experiment, echidna_entity_property_source | | widget.query.exclude_units_who_did_event.events.filters.property.source.experiment_name | string | Yes | — | — | | widget.query.exclude_units_who_did_event.events.filters.property.source.rule_id | string | No | — | Constraints: nullable | | widget.query.exclude_units_who_did_event.events.filters.property.source.is_holdout | boolean | No | — | Constraints: nullable | | widget.query.exclude_units_who_did_event.events.filters.operator | string | Yes | — | Allowed values: ANY_OF, CONTAINS, EQ, GT, LT, GTE, LTE, IS_NOT_NULL, IS_NULL, NONE_OF, NOT_CONTAINS, SQL_FILTER, STARTS_WITH, ENDS_WITH, AFTER_EXPOSURE, BEFORE_EXPOSURE, IS_TRUE, IS_FALSE, INCLUDED, NOT_INCLUDED | | widget.query.exclude_units_who_did_event.events.filters.values | string[] | No | [] | — | | widget.query.exclude_units_who_did_event.events.filters.label | string | No | — | — | | widget.query.exclude_units_who_did_event.events.alias | string | No | — | — | | widget.query.exclude_units_who_did_event.events.is_first_time | boolean | No | — | — | | widget.query.exclude_units_who_did_event.events.metric_type | string | No | — | — | | widget.query.exclude_units_who_did_event.events.metric_source_id | string | No | — | — | | widget.query.exclude_units_who_did_event.events.event_name_column | string | No | — | Constraints: nullable | | widget.query.exclude_units_who_did_event.events.analytics_config | string | No | — | Allowed values: fact_table, single_event, multi_event | | widget.query.exclude_units_who_did_event.between_steps | object | No | — | — | | widget.query.exclude_units_who_did_event.between_steps.start | integer | Yes | — | Constraints: min: 0 | | widget.query.exclude_units_who_did_event.between_steps.end | integer | Yes | — | Constraints: min: 0 | | widget.reason | string | No | — | — | | widget.widget_type | string | No | — | — | | widget.query_type | string | No | — | — | | widget.chart_type | string | No | — | — | ## Response (application/json) **200** — Updated widget identity and dashboard revision. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.revision | string | Yes | — | — | ```json { "message": "string", "data": { "id": "string", "revision": "string" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` **412** — The revision changed. Read the dashboard again and reapply the edit. ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dashboards/{id}/widgets/{widgetId}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Approve Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/approve-dynamic-config-review ================================================================================ # Approve Dynamic Config Review ## Approve Dynamic Config Review **PUT** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve` Approve Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | No | — | Optional comment recorded with the approval. Constraints: max length: 2000 | ## Response (application/json) **200** — The approved dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/approve") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Archive Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/archive-dynamic-config ================================================================================ # Archive Dynamic Config ## Archive Dynamic Config **PUT** `/console/v1/dynamic_configs/{id}/archive` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/archive` Archive Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | forceArchive | boolean | No | — | — | | archiveReason | string | No | The gate is no longer needed | The reason for archiving the gate | ## Response (application/json) **200** — Archive Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "string", "data": { "id": "string", "name": "my_config", "idType": "userID", "description": "helpful summary of what this dynamic config does", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "a tag" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "isEnabled": true, "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "defaultValue": {}, "defaultValueJson5": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "schema": "string", "schemaJson5": "string", "releasePipelineID": "string", "isTemplate": true, "status": "Enabled", "checksPerHour": 0, "permalink": "https://example.com", "type": "PERMANENT", "typeReason": "NONE", "isPermanent": true } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/archive" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/archive", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/archive", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/archive"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/archive", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/archive")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/archive") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/cancel-dynamic-config-review ================================================================================ # Cancel Dynamic Config Review ## Cancel Dynamic Config Review **DELETE** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Cancel Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — Cancel an in-flight dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Dynamic config review cancelled successfully" } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Commit Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/commit-dynamic-config-review ================================================================================ # Commit Dynamic Config Review ## Commit Dynamic Config Review **PUT** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit` Commit Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | bypass_webhook | boolean | No | — | Skip the configured pre-commit webhook and apply the reviewed change immediately. Personal keys require the `bypass_precommit_webhook` permission. An omitted value bypasses automatically for ownerless `omni_read_write` Console API keys; set to `false` to run the configured webhook workflow. | ## Response (application/json) **200** — Commit a dynamic config review. Unless `bypass_webhook` is authorized, a configured pre-commit webhook must validate the review before a later commit applies the change. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | — | | status | string | Yes | — | Current review status after the commit attempt. A non-final webhook status means the reviewed change was not applied. Allowed values: pending_webhook_validation, failed_webhook_validation, approved_webhook_validation, committed | ```json { "message": "Dynamic config review committed successfully", "status": "committed" } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/commit") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/create-dynamic-config ================================================================================ # Create Dynamic Config ## Create Dynamic Config **POST** `/console/v1/dynamic_configs` Full URL: `https://statsigapi.net/console/v1/dynamic_configs` Create Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | my_config | The dynamic config display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | isEnabled | boolean | No | true | Is the dynamic config enabled | | description | string | No | — | Constraints: max length: 1000 | | rules | object[] | No | — | An array of Rule objects | | rules.name | string | Yes | — | The name of this rule. | | rules.passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | rules.conditions | object[] | Yes | — | An array of Condition objects. | | rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | rules.conditions.field | string | No | — | Constraints: nullable | | rules.conditions.customID | string | No | — | Constraints: nullable | | rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | rules.environments | string[] | No | — | Constraints: nullable | | rules.id | string | No | — | The Statsig ID of this rule. | | rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | rules.returnValue | object | No | — | — | | rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | rules.completedAutomatedRollouts.time | number | No | — | — | | rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | rules.returnValueJson5 | string | No | — | — | | rules.variants | object[] | No | — | — | | rules.variants.id | string | No | — | — | | rules.variants.name | string | Yes | — | — | | rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | rules.variants.returnValue | object | No | — | — | | rules.variants.returnValueJson5 | string | No | — | — | | defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | idType | string | No | userID | The type of ID which the dynamic config is based on. | | tags | string[] | No | — | The list of tag names attached to the dynamic config | | creatorID | string | No | — | Constraints: nullable | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | creatorEmail | string | No | — | Constraints: nullable | | schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | targetApps | oneOf | No | — | Constraints: string, string[] | | team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | id | string | No | — | The dynamic config name ID Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-.]*$ | | isTemplate | boolean | No | — | — | ## Response (application/json) **201** — Create Dynamic Config | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic Config created successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "name": "a dynamic config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifiedTime": 1707344887865, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "1vaQaBoLlkauH9iiuOSBP2", "createdTime": 1707344887764, "creatorName": "CONSOLE API", "creatorEmail": null, "targetApps": [], "holdoutIDs": [], "tags": [], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false, "isEnabled": true, "rules": [], "defaultValue": {} } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/dynamic_configs" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/dynamic_configs", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/dynamic_configs", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/create-dynamic-config-review ================================================================================ # Create Dynamic Config Review ## Create Dynamic Config Review **POST** `/console/v1/dynamic_configs/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews` Create Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | Yes | — | Human-readable description of the proposed change. Constraints: min length: 1, max length: 2000 | | reviewer_ids | string[] | No | [] | User IDs to request review from. | | reviewer_group_ids | string[] | No | [] | Reviewer group IDs to request review from. | | change | object | Yes | — | The proposed change. Provide exactly one change slot: the content bundle (`rules` and/or `default_value`), one verb/metadata field, or `restore`. | | change.rules | object[] | No | — | Proposed full rule set for the dynamic config. Same shape as the DC update contract. | | change.rules.name | string | Yes | — | The name of this rule. | | change.rules.passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | change.rules.conditions | object[] | Yes | — | An array of Condition objects. | | change.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | change.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | change.rules.conditions.field | string | No | — | Constraints: nullable | | change.rules.conditions.customID | string | No | — | Constraints: nullable | | change.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | change.rules.environments | string[] | No | — | Constraints: nullable | | change.rules.id | string | No | — | The Statsig ID of this rule. | | change.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | change.rules.returnValue | object | No | — | — | | change.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | change.rules.completedAutomatedRollouts.time | number | No | — | — | | change.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | change.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | change.rules.returnValueJson5 | string | No | — | — | | change.rules.variants | object[] | No | — | — | | change.rules.variants.id | string | No | — | — | | change.rules.variants.name | string | Yes | — | — | | change.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | change.rules.variants.returnValue | object | No | — | — | | change.rules.variants.returnValueJson5 | string | No | — | — | | change.default_value | object | No | — | Proposed default value for the dynamic config as a JSON object. | | change.is_enabled | boolean | No | — | Proposed enabled state for the dynamic config. An explicit target, not a toggle. | | change.is_archived | boolean | No | — | Proposed archived state for the dynamic config. `true` archives, `false` unarchives. | | change.delete | boolean | No | — | Delete the dynamic config. Set to `true`. Allowed values: true | | change.resalt | boolean | No | — | Re-randomize the dynamic config's salt. Set to `true`. Allowed values: true | | change.disable_reviews_locally | boolean | No | — | Stop requiring review on this dynamic config. Set to `true`. Allowed values: true | | change.restore | object | No | — | Revert to a prior committed snapshot (review type `rules`). | | change.restore.snapshot_id | string | Yes | — | Snapshot ID (SUID) of the committed historical state to restore. Constraints: min length: 1 | | change.release_pipeline_id | string | No | — | Set or clear the dynamic config's release pipeline (review type `update_release_pipeline`). Pass a pipeline ID to attach, or `null` to detach. Constraints: nullable, min length: 1 | | change.id_type | string | No | — | Change the dynamic config's primary unit ID type (review type `edit_id_type`). Constraints: min length: 1 | | change.allow_self_approval | boolean | No | — | Whether this dynamic config's reviews may be self-approved (review type `update_allow_self_approval`). | | change.target_app_ids | string[] | No | — | Replace the dynamic config's target applications (review type `update_target_applications`). | | change.allowed_reviewers | object | No | — | Set who may review this dynamic config (review type `allowed_reviewers`). | | change.allowed_reviewers.user_ids | string[] | No | — | User IDs allowed to review. Replaces the existing set. | | change.allowed_reviewers.group_ids | string[] | No | — | Reviewer group IDs allowed to review. Replaces the existing set. | ## Response (application/json) **201** — The created dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/delete-dynamic-config ================================================================================ # Delete Dynamic Config ## Delete Dynamic Config **DELETE** `/console/v1/dynamic_configs/{id}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}` Delete Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Dynamic Config deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The entity remains intact until the existing review workflow applies the deletion. Returns the review ID and status. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/dynamic_configs/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/dynamic_configs/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/dynamic_configs/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Dynamic Config Rule URL: https://docs.statsig.com/api-reference/dynamic-configs/delete-dynamic-config-rule ================================================================================ # Delete Dynamic Config Rule ## Delete Dynamic Config Rule **DELETE** `/console/v1/dynamic_configs/{id}/rule/{ruleId}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}` Delete Dynamic Config Rule ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Dynamic Config ID | | ruleId (path) | string | Yes | — | Rule ID | ## Response (application/json) **200** — Delete Dynamic Config Rule Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic Config rule deleted successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "creatorEmail": "johnsmith@mydomain.com", "creatorName": "John Smith", "createdTime": 1674769467002, "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifierName": "CONSOLE API", "lastModifiedTime": 1707344887865, "lastModifierEmail": null, "holdoutIDs": [], "isEnabled": true, "rules": [ { "name": "All Conditions", "id": "38ttpCpzrQFTMKcqFKk02l:10.00:1", "baseID": "38ttpCpzrQFTMKcqFKk02l", "passPercentage": 10, "conditions": [ { "type": "public", "operator": "any", "targetValue": 0, "field": "string", "customID": "string" } ], "returnValue": { "key": true }, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ], "defaultValue": { "key": "the default value" }, "tags": [ "a tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false } } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Disable Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/disable-dynamic-config ================================================================================ # Disable Dynamic Config ## Disable Dynamic Config **PUT** `/console/v1/dynamic_configs/{id}/disable` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/disable` Disable Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Disable Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "string", "data": { "id": "string", "name": "my_config", "idType": "userID", "description": "helpful summary of what this dynamic config does", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "a tag" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "isEnabled": true, "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "defaultValue": {}, "defaultValueJson5": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "schema": "string", "schemaJson5": "string", "releasePipelineID": "string", "isTemplate": true, "status": "Enabled", "checksPerHour": 0, "permalink": "https://example.com", "type": "PERMANENT", "typeReason": "NONE", "isPermanent": true } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/disable" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/disable", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/disable", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/disable"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/disable", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/disable")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/disable") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Edit Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/edit-dynamic-config-review ================================================================================ # Edit Dynamic Config Review ## Edit Dynamic Config Review **PUT** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Edit Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | Updated human-readable description of the proposed change. Constraints: min length: 1, max length: 2000 | | reviewer_ids | string[] | No | — | Replacement set of user IDs to request review from. Replaces the existing set. | | reviewer_group_ids | string[] | No | — | Replacement set of reviewer group IDs to request review from. Replaces the existing set. | | change | object | No | — | The proposed change. Provide exactly one change slot: the content bundle (`rules` and/or `default_value`), one verb/metadata field, or `restore`. | | change.rules | object[] | No | — | Proposed full rule set for the dynamic config. Same shape as the DC update contract. | | change.rules.name | string | Yes | — | The name of this rule. | | change.rules.passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | change.rules.conditions | object[] | Yes | — | An array of Condition objects. | | change.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | change.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | change.rules.conditions.field | string | No | — | Constraints: nullable | | change.rules.conditions.customID | string | No | — | Constraints: nullable | | change.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | change.rules.environments | string[] | No | — | Constraints: nullable | | change.rules.id | string | No | — | The Statsig ID of this rule. | | change.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | change.rules.returnValue | object | No | — | — | | change.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | change.rules.completedAutomatedRollouts.time | number | No | — | — | | change.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | change.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | change.rules.returnValueJson5 | string | No | — | — | | change.rules.variants | object[] | No | — | — | | change.rules.variants.id | string | No | — | — | | change.rules.variants.name | string | Yes | — | — | | change.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | change.rules.variants.returnValue | object | No | — | — | | change.rules.variants.returnValueJson5 | string | No | — | — | | change.default_value | object | No | — | Proposed default value for the dynamic config as a JSON object. | | change.is_enabled | boolean | No | — | Proposed enabled state for the dynamic config. An explicit target, not a toggle. | | change.is_archived | boolean | No | — | Proposed archived state for the dynamic config. `true` archives, `false` unarchives. | | change.delete | boolean | No | — | Delete the dynamic config. Set to `true`. Allowed values: true | | change.resalt | boolean | No | — | Re-randomize the dynamic config's salt. Set to `true`. Allowed values: true | | change.disable_reviews_locally | boolean | No | — | Stop requiring review on this dynamic config. Set to `true`. Allowed values: true | | change.restore | object | No | — | Revert to a prior committed snapshot (review type `rules`). | | change.restore.snapshot_id | string | Yes | — | Snapshot ID (SUID) of the committed historical state to restore. Constraints: min length: 1 | | change.release_pipeline_id | string | No | — | Set or clear the dynamic config's release pipeline (review type `update_release_pipeline`). Pass a pipeline ID to attach, or `null` to detach. Constraints: nullable, min length: 1 | | change.id_type | string | No | — | Change the dynamic config's primary unit ID type (review type `edit_id_type`). Constraints: min length: 1 | | change.allow_self_approval | boolean | No | — | Whether this dynamic config's reviews may be self-approved (review type `update_allow_self_approval`). | | change.target_app_ids | string[] | No | — | Replace the dynamic config's target applications (review type `update_target_applications`). | | change.allowed_reviewers | object | No | — | Set who may review this dynamic config (review type `allowed_reviewers`). | | change.allowed_reviewers.user_ids | string[] | No | — | User IDs allowed to review. Replaces the existing set. | | change.allowed_reviewers.group_ids | string[] | No | — | Reviewer group IDs allowed to review. Replaces the existing set. | ## Response (application/json) **200** — The updated dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Enable Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/enable-dynamic-config ================================================================================ # Enable Dynamic Config ## Enable Dynamic Config **PUT** `/console/v1/dynamic_configs/{id}/enable` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/enable` Enable Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Enable Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "string", "data": { "id": "string", "name": "my_config", "idType": "userID", "description": "helpful summary of what this dynamic config does", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "a tag" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "isEnabled": true, "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "defaultValue": {}, "defaultValueJson5": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "schema": "string", "schemaJson5": "string", "releasePipelineID": "string", "isTemplate": true, "status": "Enabled", "checksPerHour": 0, "permalink": "https://example.com", "type": "PERMANENT", "typeReason": "NONE", "isPermanent": true } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/enable" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/enable", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/enable", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/enable"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/enable", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/enable")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/enable") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Fully Update Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/fully-update-dynamic-config ================================================================================ # Fully Update Dynamic Config ## Fully Update Dynamic Config **POST** `/console/v1/dynamic_configs/{id}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}` Fully Update Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dryRun (query) | boolean | No | true | Skips persisting updates to the entity (used to validate that inputs are correct) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | isEnabled | boolean | Yes | true | Is the dynamic config enabled | | description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | rules | object[] | Yes | — | An array of Rule objects | | rules.name | string | Yes | — | The name of this rule. | | rules.passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | rules.conditions | object[] | Yes | — | An array of Condition objects. | | rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | rules.conditions.field | string | No | — | Constraints: nullable | | rules.conditions.customID | string | No | — | Constraints: nullable | | rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | rules.environments | string[] | No | — | Constraints: nullable | | rules.id | string | No | — | The Statsig ID of this rule. | | rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | rules.returnValue | object | No | — | — | | rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | rules.completedAutomatedRollouts.time | number | No | — | — | | rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | rules.returnValueJson5 | string | No | — | — | | rules.variants | object[] | No | — | — | | rules.variants.id | string | No | — | — | | rules.variants.name | string | Yes | — | — | | rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | rules.variants.returnValue | object | No | — | — | | rules.variants.returnValueJson5 | string | No | — | — | | defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | idType | string | No | userID | The type of ID which the dynamic config is based on. | | tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | creatorID | string | No | — | Constraints: nullable | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | creatorEmail | string | No | — | Constraints: nullable | | schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | targetApps | oneOf | No | — | Constraints: string, string[] | | team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | type | string | No | — | Set to PERMANENT to mark this config as long-lived, or TEMPORARY to unmark it. Only honored on the update endpoints; this field is ignored when creating a config. Allowed values: PERMANENT, TEMPORARY | ## Response (application/json) **200** — Fully Update Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic config updated successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "creatorEmail": "johnsmith@mydomain.com", "creatorName": "John Smith", "createdTime": 1674769467002, "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifierName": "CONSOLE API", "lastModifiedTime": 1707344887865, "lastModifierEmail": null, "holdoutIDs": [], "isEnabled": true, "rules": [ { "name": "All Conditions", "id": "38ttpCpzrQFTMKcqFKk02l:10.00:1", "baseID": "38ttpCpzrQFTMKcqFKk02l", "passPercentage": 10, "conditions": [ { "type": "public", "operator": "any", "targetValue": 0, "field": "string", "customID": "string" } ], "returnValue": { "key": true }, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ], "defaultValue": { "key": "the default value" }, "tags": [ "a tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/get-dynamic-config ================================================================================ # Get Dynamic Config ## Get Dynamic Config **GET** `/console/v1/dynamic_configs/{id}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}` Get Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic config read successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "creatorEmail": "johnsmith@mydomain.com", "creatorName": "John Smith", "createdTime": 1674769467002, "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifierName": "CONSOLE API", "lastModifiedTime": 1707344887865, "lastModifierEmail": null, "holdoutIDs": [], "isEnabled": true, "rules": [ { "name": "All Conditions", "id": "38ttpCpzrQFTMKcqFKk02l:10.00:1", "baseID": "38ttpCpzrQFTMKcqFKk02l", "passPercentage": 10, "conditions": [ { "type": "public", "operator": "any", "targetValue": 0, "field": "string", "customID": "string" } ], "returnValue": { "key": true }, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ], "defaultValue": { "key": "the default value" }, "tags": [ "a tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/get-dynamic-config-review ================================================================================ # Get Dynamic Config Review ## Get Dynamic Config Review **GET** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}` Get Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — The requested dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Dynamic Config Rules URL: https://docs.statsig.com/api-reference/dynamic-configs/get-dynamic-config-rules ================================================================================ # Get Dynamic Config Rules ## Get Dynamic Config Rules **GET** `/console/v1/dynamic_configs/{id}/rules` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/rules` Get Dynamic Config Rules ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get Dynamic Config Rules Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.rules | object[] | Yes | — | — | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | The return value of the rule. | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Dynamic Config rules read successfully.", "data": [ { "rules": [ { "id": "5pjzfmF8KLFsh81kBPyxvR", "baseID": "5pjzfmF8KLFsh81kBPyxvR", "name": "rule name", "passPercentage": 1, "conditions": [ { "type": "browser_name", "targetValue": [], "operator": "any" } ], "environments": null, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] }, { "id": "6jQEnu1fCnXqjXhm1qGEnt", "baseID": "6jQEnu1fCnXqjXhm1qGEnt", "name": "Other2", "passPercentage": 80, "conditions": [], "environments": null, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] }, { "id": "4DonExIcOjSV8kG3WSQ5Zm", "baseID": "4DonExIcOjSV8kG3WSQ5Zm", "name": "Austin's fav rule", "passPercentage": 8, "conditions": [], "environments": null, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ] } ], "pagination": { "itemsPerPage": 20000, "pageNumber": 1, "totalItems": 1, "nextPage": null, "previousPage": null, "all": "" } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/rules" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/rules", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/rules", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/rules"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/rules", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/rules")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/rules") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eligible Reviewers URL: https://docs.statsig.com/api-reference/dynamic-configs/get-eligible-reviewers ================================================================================ # Get Eligible Reviewers ## Get Eligible Reviewers **GET** `/console/v1/dynamic_configs/{id}/eligible_reviewers` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers` Get Eligible Reviewers ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Users and groups eligible to review changes to this dynamic config. `everyone_eligible` is true when no specific reviewers are configured. `users` is the flattened, deduped union of individual reviewers and all group members; `groups` lists each eligible group with its member `user_ids`. Project admins can always review and are not enumerated. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.everyone_eligible | boolean | Yes | — | — | | data.users | object[] | Yes | — | — | | data.users.id | string | Yes | — | — | | data.users.email | string | Yes | — | — | | data.users.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.groups.user_ids | string[] | Yes | — | — | ```json { "message": "string", "data": { "everyone_eligible": true, "users": [ { "id": "string", "email": "string", "name": "string" } ], "groups": [ { "id": "string", "name": "string", "user_ids": [ "string" ] } ] } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/eligible_reviewers") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Specific Dynamic Config Rule URL: https://docs.statsig.com/api-reference/dynamic-configs/get-specific-dynamic-config-rule ================================================================================ # Get Specific Dynamic Config Rule ## Get Specific Dynamic Config Rule **GET** `/console/v1/dynamic_configs/{id}/rule/{ruleId}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}` Get Specific Dynamic Config Rule ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Dynamic Config ID | | ruleId (path) | string | Yes | — | Rule ID | ## Response (application/json) **200** — Get Specific Dynamic Config Rule Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | The name of this rule. | | data.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: format: double, min: 0, max: 100 | | data.conditions | object[] | Yes | — | An array of Condition objects. | | data.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.conditions.field | string | No | — | Constraints: nullable | | data.conditions.customID | string | No | — | Constraints: nullable | | data.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.id | string | No | — | The Statsig ID of this rule. | | data.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.returnValue | object | No | — | The return value of the rule. | | data.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.completedAutomatedRollouts.time | number | No | — | — | | data.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.pendingAutomatedRollouts.time | number | No | — | — | | data.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: format: int64, nullable | ```json { "message": "Dynamic Config rules read successfully.", "data": { "id": "6jQEnu1fCnXqjXhm1qGEnt", "baseID": "6jQEnu1fCnXqjXhm1qGEnt", "name": "Other2", "passPercentage": 80, "conditions": [], "environments": null, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Dynamic Config Reviews URL: https://docs.statsig.com/api-reference/dynamic-configs/list-dynamic-config-reviews ================================================================================ # List Dynamic Config Reviews ## List Dynamic Config Reviews **GET** `/console/v1/dynamic_configs/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews` List Dynamic Config Reviews ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — A page of the dynamic config reviews, newest first. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": null, "operator": "any", "field": null, "customID": null, "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": null, "passPercent": null, "phaseDurationMs": null } ], "pendingAutomatedRollouts": [ { "time": null, "passPercent": null, "phaseDurationMs": null } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ null ], "toplineAlerts": [ null ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": null, "name": null, "passPercentage": null, "returnValue": null, "returnValueJson5": null } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ null ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ null ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": null, "operator": "any", "field": null, "customID": null, "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": null, "passPercent": null, "phaseDurationMs": null } ], "pendingAutomatedRollouts": [ { "time": null, "passPercent": null, "phaseDurationMs": null } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ null ], "toplineAlerts": [ null ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": null, "name": null, "passPercentage": null, "returnValue": null, "returnValueJson5": null } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ null ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ null ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Dynamic Config Versions URL: https://docs.statsig.com/api-reference/dynamic-configs/list-dynamic-config-versions ================================================================================ # List Dynamic Config Versions ## List Dynamic Config Versions **GET** `/console/v1/dynamic_configs/{id}/versions` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/versions` List Dynamic Config Versions ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | | startDate (query) | string | No | 2024-01-01 | Only return versions last modified on or after this date. Expected valid date in the form of YYYY-MM-DD | | endDate (query) | string | No | 2024-01-31 | Only return versions last modified on or before this date, inclusive. Expected valid date in the form of YYYY-MM-DD | ## Response (application/json) **200** — List Dynamic Config Versions Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "my_config", "idType": "userID", "description": "helpful summary of what this dynamic config does", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "a tag" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "isEnabled": true, "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "defaultValue": {}, "defaultValueJson5": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "schema": "string", "schemaJson5": "string", "releasePipelineID": "string", "isTemplate": true, "status": "Enabled", "checksPerHour": 0, "permalink": "https://example.com", "type": "PERMANENT", "typeReason": "NONE", "isPermanent": true } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Dynamic Configs URL: https://docs.statsig.com/api-reference/dynamic-configs/list-dynamic-configs ================================================================================ # List Dynamic Configs ## List Dynamic Configs **GET** `/console/v1/dynamic_configs` Full URL: `https://statsigapi.net/console/v1/dynamic_configs` List Dynamic Configs ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | releasePipelineID (query) | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | teamID (query) | string | No | — | Filter by team ID | | targetAppID (query) | string | No | — | Filter by target app ID | | type (query) | string | No | — | Filter by lifecycle type (TEMPORARY, PERMANENT, or STALE). Results depend on the nightly stale detection batch job having run. Allowed values: TEMPORARY, PERMANENT, STALE | | typeReason (query) | string | No | — | Filter by stale classification reason. Results depend on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | creatorName (query) | string | No | — | Name of the creator. Constraints: nullable | | creatorID (query) | string | No | — | ID of the user who created the entity. Constraints: nullable | | tags (query) | oneOf | No | — | Filter by tags Constraints: string, string[] | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Dynamic Configs Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Dynamic Configs listed successfully.", "data": [ { "id": "example_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/example_config", "name": "Example Config", "description": "An example dynamic configuration", "idType": "userID", "lastModifierID": "abc123", "lastModifiedTime": 1600000000000, "lastModifierName": "Jane Doe", "lastModifierEmail": "jane@example.com", "creatorID": "def456", "createdTime": 1500000000000, "creatorName": "John Smith", "creatorEmail": "john@example.com", "targetApps": [ "myapp" ], "holdoutIDs": [], "tags": [ "example_tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false, "team": "Product", "isEnabled": true, "rules": [], "defaultValue": {}, "defaultValueJson5": "{}", "schema": "{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"properties\":{}}", "schemaJson5": "{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"properties\": {}\n}", "version": 1 } ] } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Partially Update Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/partially-update-dynamic-config ================================================================================ # Partially Update Dynamic Config ## Partially Update Dynamic Config **PATCH** `/console/v1/dynamic_configs/{id}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}` Partially Update Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dryRun (query) | boolean | No | true | Skips persisting updates to the entity (used to validate that inputs are correct) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | isEnabled | boolean | No | true | Is the dynamic config enabled | | description | string | No | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | rules | object[] | No | — | An array of Rule objects | | rules.name | string | Yes | — | The name of this rule. | | rules.passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | rules.conditions | object[] | Yes | — | An array of Condition objects. | | rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | rules.conditions.field | string | No | — | Constraints: nullable | | rules.conditions.customID | string | No | — | Constraints: nullable | | rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | rules.environments | string[] | No | — | Constraints: nullable | | rules.id | string | No | — | The Statsig ID of this rule. | | rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | rules.returnValue | object | No | — | — | | rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | rules.completedAutomatedRollouts.time | number | No | — | — | | rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | rules.returnValueJson5 | string | No | — | — | | rules.variants | object[] | No | — | — | | rules.variants.id | string | No | — | — | | rules.variants.name | string | Yes | — | — | | rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | rules.variants.returnValue | object | No | — | — | | rules.variants.returnValueJson5 | string | No | — | — | | defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | idType | string | No | userID | The type of ID which the dynamic config is based on. | | tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | creatorID | string | No | — | Constraints: nullable | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | creatorEmail | string | No | — | Constraints: nullable | | schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | targetApps | oneOf | No | — | Constraints: string, string[] | | team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | type | string | No | — | Set to PERMANENT to mark this config as long-lived, or TEMPORARY to unmark it. Only honored on the update endpoints; this field is ignored when creating a config. Allowed values: PERMANENT, TEMPORARY | ## Response (application/json) **200** — Partially Update Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic config updated successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "creatorEmail": "johnsmith@mydomain.com", "creatorName": "John Smith", "createdTime": 1674769467002, "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifierName": "CONSOLE API", "lastModifiedTime": 1707344887865, "lastModifierEmail": null, "holdoutIDs": [], "isEnabled": true, "rules": [ { "name": "All Conditions", "id": "38ttpCpzrQFTMKcqFKk02l:10.00:1", "baseID": "38ttpCpzrQFTMKcqFKk02l", "passPercentage": 10, "conditions": [ { "type": "public", "operator": "any", "targetValue": 0, "field": "string", "customID": "string" } ], "returnValue": { "key": true }, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ], "defaultValue": { "key": "the default value" }, "tags": [ "a tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}?dryRun=true") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Reject Dynamic Config Review URL: https://docs.statsig.com/api-reference/dynamic-configs/reject-dynamic-config-review ================================================================================ # Reject Dynamic Config Review ## Reject Dynamic Config Review **PUT** `/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject` Reject Dynamic Config Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | Yes | — | Required reason for rejecting the review. Constraints: min length: 1, max length: 2000 | ## Response (application/json) **200** — The rejected dynamic config review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/reviews/{reviewID}/reject") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Unarchive Dynamic Config URL: https://docs.statsig.com/api-reference/dynamic-configs/unarchive-dynamic-config ================================================================================ # Unarchive Dynamic Config ## Unarchive Dynamic Config **PUT** `/console/v1/dynamic_configs/{id}/unarchive` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive` Unarchive Dynamic Config ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | unarchiveReason | string | No | The gate is needed again | The reason for unarchiving the gate | ## Response (application/json) **200** — Unarchive Dynamic Config Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "string", "data": { "id": "string", "name": "my_config", "idType": "userID", "description": "helpful summary of what this dynamic config does", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "a tag" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "isEnabled": true, "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "defaultValue": {}, "defaultValueJson5": "string", "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "schema": "string", "schemaJson5": "string", "releasePipelineID": "string", "isTemplate": true, "status": "Enabled", "checksPerHour": 0, "permalink": "https://example.com", "type": "PERMANENT", "typeReason": "NONE", "isPermanent": true } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/unarchive") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Dynamic Config Rule By Id URL: https://docs.statsig.com/api-reference/dynamic-configs/update-dynamic-config-rule-by-id ================================================================================ # Update Dynamic Config Rule By Id ## Update Dynamic Config Rule By Id **PATCH** `/console/v1/dynamic_configs/{id}/rule/{ruleId}` Full URL: `https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}` Update Dynamic Config Rule By Id ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Dynamic Config ID | | ruleId (path) | string | Yes | — | Rule ID | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dryRun (query) | boolean | No | true | Skips persisting updates to the entity (used to validate that inputs are correct) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | The name of this rule. | | passPercentage | number | No | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: format: double, min: 0, max: 100 | | conditions | object[] | No | — | An array of Condition objects. | | conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | conditions.field | string | No | — | Constraints: nullable | | conditions.customID | string | No | — | Constraints: nullable | | conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | environments | string[] | No | — | Constraints: nullable | | id | string | No | — | The Statsig ID of this rule. | | baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | returnValue | object | No | — | — | | completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | completedAutomatedRollouts.time | number | No | — | — | | completedAutomatedRollouts.passPercent | number | Yes | — | — | | completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | returnValueJson5 | string | No | — | — | | variants | object[] | No | — | — | | variants.id | string | No | — | — | | variants.name | string | Yes | — | — | | variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | variants.returnValue | object | No | — | — | | variants.returnValueJson5 | string | No | — | — | ## Response (application/json) **200** — Update Dynamic Config Rule Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | my_config | Optional name for the configuration. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | userID | The type of ID which the dynamic config is based on. | | data.description | string | Yes | helpful summary of what this dynamic config does | A brief summary of what the dynamic config is being used for Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | ["a tag"] | The list of tag names attached to the dynamic config | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the dynamic config, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the dynamic config, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.isEnabled | boolean | Yes | true | Is the dynamic config enabled | | data.rules | object[] | Yes | — | An array of Rule objects | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | — | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.rules.returnValueJson5 | string | No | — | — | | data.rules.variants | object[] | No | — | — | | data.rules.variants.id | string | No | — | — | | data.rules.variants.name | string | Yes | — | — | | data.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.rules.variants.returnValue | object | No | — | — | | data.rules.variants.returnValueJson5 | string | No | — | — | | data.defaultValue | object | No | — | The fallback JSON object when no rules are triggered | | data.defaultValueJson5 | string | No | — | Can include comments. If provided with defaultValue, must parse to the same JSON | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.schema | string | No | — | A schema using JSON Schema Draft 2020-12 to enforce return values of this dynamic config's rules. Constraints: nullable | | data.schemaJson5 | string | No | — | `schema` except with Json5 comments. Optional and should parse to same json as `schema`. Constraints: nullable | | data.releasePipelineID | string | No | — | The release pipeline ID associated with the dynamic config Constraints: nullable | | data.isTemplate | boolean | No | — | — | | data.status | string | No | — | Allowed values: Enabled, Disabled, Archived | | data.checksPerHour | number | No | — | Constraints: format: double, nullable | | data.permalink | string | Yes | — | A permalink to this dynamic config in the Statsig Console. Constraints: format: uri | | data.type | string | Yes | — | The lifecycle type of the config (TEMPORARY, PERMANENT, or STALE). STALE classification depends on the nightly stale detection batch job having run; a config not yet processed reads as TEMPORARY. Allowed values: PERMANENT, TEMPORARY, STALE, TEMPLATE | | data.typeReason | string | Yes | — | The reason for the current type classification. Depends on the nightly stale detection batch job having run. Allowed values: NONE, STALE_PROBABLY_DEAD_CHECK, STALE_NO_RULES, STALE_PROBABLY_FORGOTTEN, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED | | data.isPermanent | boolean | Yes | — | Whether the config has been explicitly marked as long-lived. | ```json { "message": "Dynamic Config rules updated successfully.", "data": { "id": "a_dynamic_config", "permalink": "https://console.statsig.com/company_id/dynamic_configs/a_dynamic_config", "description": "helpful summary of what this dynamic config does", "idType": "userID", "creatorEmail": "johnsmith@mydomain.com", "creatorName": "John Smith", "createdTime": 1674769467002, "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifierName": "CONSOLE API", "lastModifiedTime": 1707344887865, "lastModifierEmail": null, "holdoutIDs": [], "isEnabled": true, "rules": [ { "name": "All Conditions", "id": "38ttpCpzrQFTMKcqFKk02l:10.00:1", "baseID": "38ttpCpzrQFTMKcqFKk02l", "passPercentage": 10, "conditions": [ { "type": "public", "operator": "any", "targetValue": 0, "field": "string", "customID": "string" } ], "returnValue": { "key": true }, "completedAutomatedRollouts": [], "pendingAutomatedRollouts": [] } ], "defaultValue": { "key": "the default value" }, "tags": [ "a tag" ], "type": "TEMPORARY", "typeReason": "NONE", "isPermanent": false } } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/dynamic_configs/{id}/rule/{ruleId}?dryRun=true") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Environments URL: https://docs.statsig.com/api-reference/environments/get-environments ================================================================================ # Get Environments ## Get Environments **GET** `/console/v1/environments` Full URL: `https://statsigapi.net/console/v1/environments` Get Environments ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Response (application/json) **200** — Get Environments Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.environments | object[] | Yes | — | — | | data.environments.name | string | Yes | — | The name of the environment. | | data.environments.id | string | Yes | — | A unique identifier for the environment. | | data.environments.isProduction | boolean | Yes | — | Whether the environment is production. | | data.environments.requiresReview | boolean | Yes | — | Whether the environment requires review. | | data.environments.requiredReviewGroupID | string | No | — | The ID of the review group that the environment requires review from. | | data.environments.requiresReleasePipeline | boolean | Yes | — | Whether the environment requires a release pipeline. | ```json { "message": "Environments read successfully.", "data": { "environments": [ { "name": "development", "id": "0.35629335902367476", "isProduction": false, "requiresReview": false, "requiresReleasePipeline": true }, { "name": "staging", "id": "0.015089163460661137", "isProduction": false, "requiresReview": false, "requiresReleasePipeline": true }, { "name": "production", "id": "0.4067426155658289", "isProduction": true, "requiresReview": true, "requiresReleasePipeline": true } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/environments" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/environments", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/environments", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/environments"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/environments", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/environments")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/environments") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Environments URL: https://docs.statsig.com/api-reference/environments/update-environments ================================================================================ # Update Environments ## Update Environments **POST** `/console/v1/environments` Full URL: `https://statsigapi.net/console/v1/environments` Update Environments ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environments | object[] | Yes | — | — | | environments.name | string | Yes | — | The name of the environment. | | environments.id | string | No | — | A unique identifier for the environment. If not provided, the associated environment will be treated as a newly created environment. | | environments.isProduction | boolean | Yes | — | Whether the environment is production. | | environments.requiresReview | boolean | Yes | — | Whether the environment requires review. | | environments.requiredReviewGroupID | string | No | — | The ID of the review group that the environment requires review from. | | environments.requiresReleasePipeline | boolean | Yes | — | Whether the environment requires a release pipeline. | ## Response (application/json) **200** — Update Environments Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.environments | object[] | Yes | — | — | | data.environments.name | string | Yes | — | The name of the environment. | | data.environments.id | string | Yes | — | A unique identifier for the environment. | | data.environments.isProduction | boolean | Yes | — | Whether the environment is production. | | data.environments.requiresReview | boolean | Yes | — | Whether the environment requires review. | | data.environments.requiredReviewGroupID | string | No | — | The ID of the review group that the environment requires review from. | | data.environments.requiresReleasePipeline | boolean | Yes | — | Whether the environment requires a release pipeline. | ```json { "message": "Environments updated successfully.", "data": { "environments": [ { "name": "development", "id": "0.35629335902367476", "isProduction": false, "requiresReview": false, "requiresReleasePipeline": true }, { "name": "latest", "id": "0.08933465966698129", "isProduction": false, "requiresReview": false, "requiresReleasePipeline": true }, { "name": "staging", "id": "0.015089163460661137", "isProduction": false, "requiresReview": false, "requiresReleasePipeline": true }, { "name": "production", "id": "0.4067426155658289", "isProduction": true, "requiresReview": true, "requiresReleasePipeline": true } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/environments" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/environments", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/environments", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/environments"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/environments", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/environments")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/environments") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Eval URL: https://docs.statsig.com/api-reference/evals/create-eval ================================================================================ # Create Eval ## Create Eval **POST** `/console/v1/evals` Full URL: `https://statsigapi.net/console/v1/evals` Create Eval Create an eval, the container for runs. Optionally link it to a prompt. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | support_bot_regressions | Eval name. Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | description | string | No | — | — | | promptID | string | No | — | Prompt name or ID this eval belongs to, if any. | ## Response (application/json) **201** — Create Eval | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | Eval ID. | | data.name | string | Yes | — | Eval name. Used as the identifier in routes. | | data.description | string | Yes | — | — | | data.aiConfigID | string | Yes | — | Prompt that created this eval, if any. Constraints: nullable | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "description": "string", "aiConfigID": "string", "createdTime": 0, "lastModifiedTime": 0 } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/evals" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/evals", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/evals", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Eval Dataset URL: https://docs.statsig.com/api-reference/evals/create-eval-dataset ================================================================================ # Create Eval Dataset ## Create Eval Dataset **POST** `/console/v1/eval_datasets` Full URL: `https://statsigapi.net/console/v1/eval_datasets` Create Eval Dataset Create a dataset, optionally with rows. Columns are taken from the row cells; rows may record the production trace they came from. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Dataset name, unique in the project. Constraints: min length: 1 | | description | string | No | — | — | | rows | object[] | No | — | — | | rows.columns | object[] | Yes | — | Cell values by column name. A column name not yet on the dataset is added to it. | | rows.columns.name | string | Yes | — | Constraints: min length: 1 | | rows.columns.value | string | Yes | — | — | | rows.groups | string[] | No | — | Group names for the row, created when new. | | rows.sourceTraceID | string | No | — | Trace the row was taken from, when it came from production. | | rows.sourceSpanID | string | No | — | — | | outputFields | string[] | No | — | Column names that hold outputs to grade instead of generating completions. | ## Response (application/json) **201** — Create Eval Dataset | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.description | string | Yes | — | — | | data.isGlobal | boolean | Yes | — | — | | data.version | number | Yes | — | Counter bumped on every edit to the dataset rows or columns. Constraints: format: double | | data.columns | object[] | Yes | — | — | | data.columns.id | string | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.outputFields | string[] | Yes | — | — | | data.imageFields | string[] | Yes | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "description": "string", "isGlobal": true, "version": 0, "columns": [ { "id": "string", "name": "string" } ], "groups": [ { "id": "string", "name": "string" } ], "outputFields": [ "string" ], "imageFields": [ "string" ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/eval_datasets" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/eval_datasets", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/eval_datasets", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Eval Grader URL: https://docs.statsig.com/api-reference/evals/create-eval-grader ================================================================================ # Create Eval Grader ## Create Eval Grader **POST** `/console/v1/eval_graders` Full URL: `https://statsigapi.net/console/v1/eval_graders` Create Eval Grader Create a grader in the project catalog. Attach it to a prompt with Update Prompt Eval Settings, or pass its name to Create Eval Run. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Grader name, unique in the project. Constraints: min length: 1 | | prompt | object | Yes | — | — | | prompt.type | string | Yes | — | label_model is an LLM judge over {{output}} (content is the rubric); string_check compares {{output}} to a dataset column with operation; text_similarity scores {{output}} against a column with evaluation_metric; python runs source. Allowed values: label_model, string_check, text_similarity, python | | prompt.content | string | No | — | Rubric for label_model. May reference {{output}} and dataset columns. Constraints: nullable | | prompt.operation | string | No | — | Constraints: nullable Allowed values: eq, ne, like, ilike | | prompt.evaluation_metric | string | No | — | Similarity measure for text_similarity. Constraints: nullable Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | prompt.column | string | No | — | Dataset column compared against for string_check and text_similarity. Constraints: nullable | | prompt.source | string | No | — | Python source for a python grader. Constraints: nullable | | evalModel | string | No | — | OpenAI model that judges a `label_model` grader, such as `gpt-5-mini`. Other grader types ignore it. An unsupported model returns a 400. Defaults to `gpt-5-mini` on create; omit it on update to keep the current model. Constraints: min length: 1 | ## Response (application/json) **201** — Create Eval Grader | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.type | string | Yes | — | Grader type: label_model, string_check, text_similarity, python, completion_tokens, completion_latency, or logged_score. | | data.isGlobal | boolean | Yes | — | — | | data.prompt | oneOf | Yes | — | Constraints: object | | data.prompt.type | string | Yes | — | Allowed values: label_model, string_check, text_similarity, python, programmatic_grader, completion_tokens, completion_latency, logged_score | | data.prompt.content | string | No | — | — | | data.prompt.operation | string | No | — | Allowed values: eq, ne, like, ilike | | data.prompt.column | string | No | — | — | | data.prompt.evaluation_metric | string | No | — | Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | data.prompt.source | string | No | — | — | | data.evalModel | string | Yes | — | OpenAI model that judges a `label_model` grader. Other grader types ignore it. | | data.choiceScores | object | Yes | — | Constraints: nullable | | data.gradingRules | object[] | Yes | — | Ordered online grading rules. For each span, the first enabled rule that matches decides whether the grader scores it. | | data.gradingRules.id | string | Yes | — | — | | data.gradingRules.enabled | boolean | Yes | — | — | | data.gradingRules.conditions | object[] | Yes | — | Combined with AND. A rule with no conditions matches every span. | | data.gradingRules.conditions.field | string | Yes | — | Span field to match: `ai_config` (AI config IDs, matched by the config name), `config_version` (version IDs), `environment` (`statsig.environment`), `span_name`, `agent_name` (`gen_ai.agent.name`), `model` (`gen_ai.request.model`), or `span_attribute` (the attribute named by `key`). Allowed values: ai_config, config_version, environment, span_name, agent_name, model, span_attribute | | data.gradingRules.conditions.key | string | No | — | Attribute name of a `span_attribute` condition. | | data.gradingRules.conditions.operator | string | Yes | — | `is` matches any of the values exactly and `is_not` matches none of them. A span without the field reads as an empty string. Allowed values: is, is_not | | data.gradingRules.conditions.values | string[] | Yes | — | — | | data.gradingRules.samplingRate | number | Yes | — | Percentage of matching traces to grade, from 0 to 100. Sampling is by trace ID, so every span of a trace gets the same decision. Constraints: min: 0, max: 100 | | data.offlineTargets | oneOf[] | Yes | — | AI configs and datasets the grader scores in offline evals. A version evaluation of an AI config runs its graders and its dataset's graders. An eval run on a dataset always includes that dataset's graders. | | data.offlineTargets.type | string | Yes | — | Allowed values: ai_config, dataset | | data.offlineTargets.aiConfigID | string | No | — | — | | data.offlineTargets.isCritical | boolean | No | — | — | | data.offlineTargets.datasetID | string | No | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "type": "string", "isGlobal": true, "prompt": { "type": "label_model", "content": "string" }, "evalModel": "string", "choiceScores": {}, "gradingRules": [ { "id": "string", "enabled": true, "conditions": [ { "field": "ai_config", "key": "string", "operator": "is", "values": [ "string" ] } ], "samplingRate": 0 } ], "offlineTargets": [ { "type": "ai_config", "aiConfigID": "string", "isCritical": true } ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/eval_graders" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/eval_graders", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_graders", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_graders"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/eval_graders", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_graders")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_graders") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Eval Run URL: https://docs.statsig.com/api-reference/evals/create-eval-run ================================================================================ # Create Eval Run ## Create Eval Run **POST** `/console/v1/evals/{name}` Full URL: `https://statsigapi.net/console/v1/evals/{name}` Create Eval Run Start a run on an existing eval that scores a dataset with the named graders. Poll Get Eval Run until its status is completed, then read its results. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | my_eval_run | The Eval Run display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | graders | string[] | Yes | ["grader1","grader2"] | The list of grader names | | dataset | string | Yes | dataset1 | The dataset name | ## Response (application/json) **200** — Create Eval Run | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.evalID | string | Yes | — | — | | data.status | string | Yes | — | running until the run finishes, then completed, or failed when the run recorded an error. Allowed values: running, completed, failed | | data.createdTime | number | Yes | — | Constraints: format: double | | data.finishTime | number | Yes | — | Constraints: format: double, nullable | | data.runTime | number | Yes | — | Constraints: format: double, nullable | | data.datasetID | string | Yes | — | Dataset the run scored. Null for runs posted from code through send_results. Constraints: nullable | | data.datasetItemCount | number | Yes | — | Constraints: format: double | | data.graderIDs | string[] | Yes | — | — | | data.primaryEvalGraderID | string | Yes | — | Constraints: nullable | | data.parameters | object | Yes | — | Constraints: nullable | | data.errorReason | string | Yes | — | Constraints: nullable | ```json { "message": "string", "data": { "id": "string", "name": "string", "evalID": "string", "status": "running", "createdTime": 0, "finishTime": 0, "runTime": 0, "datasetID": "string", "datasetItemCount": 0, "graderIDs": [ "string" ], "primaryEvalGraderID": "string", "parameters": {}, "errorReason": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/evals/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/evals/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/evals/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Eval URL: https://docs.statsig.com/api-reference/evals/delete-eval ================================================================================ # Delete Eval ## Delete Eval **DELETE** `/console/v1/evals/{name}` Full URL: `https://statsigapi.net/console/v1/evals/{name}` Delete Eval Delete an eval and all of its runs. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Delete Eval Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Eval deleted successfully." } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/evals/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/evals/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/evals/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Eval Dataset URL: https://docs.statsig.com/api-reference/evals/delete-eval-dataset ================================================================================ # Delete Eval Dataset ## Delete Eval Dataset **DELETE** `/console/v1/eval_datasets/{name}` Full URL: `https://statsigapi.net/console/v1/eval_datasets/{name}` Delete Eval Dataset ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Delete Eval Dataset Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Eval Dataset deleted successfully." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/eval_datasets/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/eval_datasets/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/eval_datasets/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Eval Grader URL: https://docs.statsig.com/api-reference/evals/delete-eval-grader ================================================================================ # Delete Eval Grader ## Delete Eval Grader **DELETE** `/console/v1/eval_graders/{name}` Full URL: `https://statsigapi.net/console/v1/eval_graders/{name}` Delete Eval Grader ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Delete Eval Grader Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Eval Grader deleted successfully." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/eval_graders/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/eval_graders/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_graders/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_graders/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/eval_graders/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_graders/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_graders/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eval URL: https://docs.statsig.com/api-reference/evals/get-eval ================================================================================ # Get Eval ## Get Eval **GET** `/console/v1/evals/{name}` Full URL: `https://statsigapi.net/console/v1/evals/{name}` Get Eval Read one eval by name. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Get Eval | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | Eval ID. | | data.name | string | Yes | — | Eval name. Used as the identifier in routes. | | data.description | string | Yes | — | — | | data.aiConfigID | string | Yes | — | Prompt that created this eval, if any. Constraints: nullable | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "description": "string", "aiConfigID": "string", "createdTime": 0, "lastModifiedTime": 0 } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eval Dataset URL: https://docs.statsig.com/api-reference/evals/get-eval-dataset ================================================================================ # Get Eval Dataset ## Get Eval Dataset **GET** `/console/v1/eval_datasets/{name}` Full URL: `https://statsigapi.net/console/v1/eval_datasets/{name}` Get Eval Dataset Read one eval dataset by name or ID: its columns, groups, output fields and version. Rows are not included. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Get Eval Dataset | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.description | string | Yes | — | — | | data.isGlobal | boolean | Yes | — | — | | data.version | number | Yes | — | Counter bumped on every edit to the dataset rows or columns. Constraints: format: double | | data.columns | object[] | Yes | — | — | | data.columns.id | string | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.outputFields | string[] | Yes | — | — | | data.imageFields | string[] | Yes | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "description": "string", "isGlobal": true, "version": 0, "columns": [ { "id": "string", "name": "string" } ], "groups": [ { "id": "string", "name": "string" } ], "outputFields": [ "string" ], "imageFields": [ "string" ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/eval_datasets/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/eval_datasets/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets/{name}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/eval_datasets/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets/{name}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets/{name}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eval Grader URL: https://docs.statsig.com/api-reference/evals/get-eval-grader ================================================================================ # Get Eval Grader ## Get Eval Grader **GET** `/console/v1/eval_graders/{name}` Full URL: `https://statsigapi.net/console/v1/eval_graders/{name}` Get Eval Grader Read one grader by name or ID, including its definition. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Get Eval Grader | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.type | string | Yes | — | Grader type: label_model, string_check, text_similarity, python, completion_tokens, completion_latency, or logged_score. | | data.isGlobal | boolean | Yes | — | — | | data.prompt | oneOf | Yes | — | Constraints: object | | data.prompt.type | string | Yes | — | Allowed values: label_model, string_check, text_similarity, python, programmatic_grader, completion_tokens, completion_latency, logged_score | | data.prompt.content | string | No | — | — | | data.prompt.operation | string | No | — | Allowed values: eq, ne, like, ilike | | data.prompt.column | string | No | — | — | | data.prompt.evaluation_metric | string | No | — | Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | data.prompt.source | string | No | — | — | | data.evalModel | string | Yes | — | OpenAI model that judges a `label_model` grader. Other grader types ignore it. | | data.choiceScores | object | Yes | — | Constraints: nullable | | data.gradingRules | object[] | Yes | — | Ordered online grading rules. For each span, the first enabled rule that matches decides whether the grader scores it. | | data.gradingRules.id | string | Yes | — | — | | data.gradingRules.enabled | boolean | Yes | — | — | | data.gradingRules.conditions | object[] | Yes | — | Combined with AND. A rule with no conditions matches every span. | | data.gradingRules.conditions.field | string | Yes | — | Span field to match: `ai_config` (AI config IDs, matched by the config name), `config_version` (version IDs), `environment` (`statsig.environment`), `span_name`, `agent_name` (`gen_ai.agent.name`), `model` (`gen_ai.request.model`), or `span_attribute` (the attribute named by `key`). Allowed values: ai_config, config_version, environment, span_name, agent_name, model, span_attribute | | data.gradingRules.conditions.key | string | No | — | Attribute name of a `span_attribute` condition. | | data.gradingRules.conditions.operator | string | Yes | — | `is` matches any of the values exactly and `is_not` matches none of them. A span without the field reads as an empty string. Allowed values: is, is_not | | data.gradingRules.conditions.values | string[] | Yes | — | — | | data.gradingRules.samplingRate | number | Yes | — | Percentage of matching traces to grade, from 0 to 100. Sampling is by trace ID, so every span of a trace gets the same decision. Constraints: min: 0, max: 100 | | data.offlineTargets | oneOf[] | Yes | — | AI configs and datasets the grader scores in offline evals. A version evaluation of an AI config runs its graders and its dataset's graders. An eval run on a dataset always includes that dataset's graders. | | data.offlineTargets.type | string | Yes | — | Allowed values: ai_config, dataset | | data.offlineTargets.aiConfigID | string | No | — | — | | data.offlineTargets.isCritical | boolean | No | — | — | | data.offlineTargets.datasetID | string | No | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "type": "string", "isGlobal": true, "prompt": { "type": "label_model", "content": "string" }, "evalModel": "string", "choiceScores": {}, "gradingRules": [ { "id": "string", "enabled": true, "conditions": [ { "field": "ai_config", "key": "string", "operator": "is", "values": [ "string" ] } ], "samplingRate": 0 } ], "offlineTargets": [ { "type": "ai_config", "aiConfigID": "string", "isCritical": true } ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/eval_graders/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/eval_graders/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_graders/{name}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_graders/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/eval_graders/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_graders/{name}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_graders/{name}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eval Run URL: https://docs.statsig.com/api-reference/evals/get-eval-run ================================================================================ # Get Eval Run ## Get Eval Run **GET** `/console/v1/evals/{name}/runs/{runId}` Full URL: `https://statsigapi.net/console/v1/evals/{name}/runs/{runId}` Get Eval Run Read one eval run, including its status: running, completed, or failed. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Eval name | | runId (path) | string | Yes | — | Eval run ID | ## Response (application/json) **200** — Get Eval Run | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.evalID | string | Yes | — | — | | data.status | string | Yes | — | running until the run finishes, then completed, or failed when the run recorded an error. Allowed values: running, completed, failed | | data.createdTime | number | Yes | — | Constraints: format: double | | data.finishTime | number | Yes | — | Constraints: format: double, nullable | | data.runTime | number | Yes | — | Constraints: format: double, nullable | | data.datasetID | string | Yes | — | Dataset the run scored. Null for runs posted from code through send_results. Constraints: nullable | | data.datasetItemCount | number | Yes | — | Constraints: format: double | | data.graderIDs | string[] | Yes | — | — | | data.primaryEvalGraderID | string | Yes | — | Constraints: nullable | | data.parameters | object | Yes | — | Constraints: nullable | | data.errorReason | string | Yes | — | Constraints: nullable | ```json { "message": "string", "data": { "id": "string", "name": "string", "evalID": "string", "status": "running", "createdTime": 0, "finishTime": 0, "runTime": 0, "datasetID": "string", "datasetItemCount": 0, "graderIDs": [ "string" ], "primaryEvalGraderID": "string", "parameters": {}, "errorReason": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eval Run Results URL: https://docs.statsig.com/api-reference/evals/get-eval-run-results ================================================================================ # Get Eval Run Results ## Get Eval Run Results **GET** `/console/v1/evals/{name}/runs/{runId}/results` Full URL: `https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results` Get Eval Run Results Read the per-grader aggregate scores of an eval run. Scores are means from 0 to 1; a critical grader that scores 0 sets the primary score to 0. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Eval name | | runId (path) | string | Yes | — | Eval run ID | ## Response (application/json) **200** — Get Eval Run Results | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.runID | string | Yes | — | — | | data.status | string | Yes | — | Allowed values: running, completed, failed | | data.primaryGraderScore | number | Yes | — | Primary grader mean rounded to two decimals, or 0 when a critical grader scored 0. Null until a primary grader has a score. Constraints: format: double, nullable | | data.graders | object[] | Yes | — | — | | data.graders.graderID | string | Yes | — | — | | data.graders.graderName | string | Yes | — | — | | data.graders.graderType | string | Yes | — | — | | data.graders.score | number | Yes | — | Mean score across rows, 0 to 1. | | data.graders.isPrimary | boolean | Yes | — | — | | data.graders.isCritical | boolean | Yes | — | — | | data.graders.groups | object[] | Yes | — | — | | data.graders.groups.name | string | Yes | — | — | | data.graders.groups.score | number | Yes | — | — | | data.graders.tokenCounts | object | Yes | — | — | | data.graders.tokenCounts.input | number | Yes | — | — | | data.graders.tokenCounts.output | number | Yes | — | — | ```json { "message": "string", "data": { "runID": "string", "status": "running", "primaryGraderScore": 0, "graders": [ { "graderID": "string", "graderName": "string", "graderType": "string", "score": 0, "isPrimary": true, "isCritical": true, "groups": [ { "name": "string", "score": 0 } ], "tokenCounts": { "input": 0, "output": 0 } } ] } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Eval Dataset Rows URL: https://docs.statsig.com/api-reference/evals/list-eval-dataset-rows ================================================================================ # List Eval Dataset Rows ## List Eval Dataset Rows **GET** `/console/v1/eval_datasets/{name}/rows` Full URL: `https://statsigapi.net/console/v1/eval_datasets/{name}/rows` List Eval Dataset Rows List the rows of a dataset with cell values by column name, groups, and the source trace when known. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Eval Dataset Rows Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.rowID | string | Yes | — | — | | data.columns | object[] | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.columns.value | string | Yes | — | — | | data.groups | string[] | Yes | — | — | | data.sourceTraceID | string | Yes | — | Constraints: nullable | | data.sourceSpanID | string | Yes | — | Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "rowID": "string", "columns": [ { "name": "string", "value": "string" } ], "groups": [ "string" ], "sourceTraceID": "string", "sourceSpanID": "string" } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets/{name}/rows?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Eval Datasets URL: https://docs.statsig.com/api-reference/evals/list-eval-datasets ================================================================================ # List Eval Datasets ## List Eval Datasets **GET** `/console/v1/eval_datasets` Full URL: `https://statsigapi.net/console/v1/eval_datasets` List Eval Datasets List the eval datasets in this project, newest first. Pass a dataset name to Create Eval Run to score it. Rows are not included. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Eval Datasets Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.description | string | Yes | — | — | | data.isGlobal | boolean | Yes | — | — | | data.version | number | Yes | — | Counter bumped on every edit to the dataset rows or columns. Constraints: format: double | | data.columns | object[] | Yes | — | — | | data.columns.id | string | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.outputFields | string[] | Yes | — | — | | data.imageFields | string[] | Yes | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "string", "description": "string", "isGlobal": true, "version": 0, "columns": [ { "id": "string", "name": "string" } ], "groups": [ { "id": "string", "name": "string" } ], "outputFields": [ "string" ], "imageFields": [ "string" ], "createdTime": 0, "lastModifiedTime": 0 } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Eval Graders URL: https://docs.statsig.com/api-reference/evals/list-eval-graders ================================================================================ # List Eval Graders ## List Eval Graders **GET** `/console/v1/eval_graders` Full URL: `https://statsigapi.net/console/v1/eval_graders` List Eval Graders List the graders in this project, newest first. Pass a grader name to Create Eval Run to score a dataset with it. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Eval Graders Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.type | string | Yes | — | Grader type: label_model, string_check, text_similarity, python, completion_tokens, completion_latency, or logged_score. | | data.isGlobal | boolean | Yes | — | — | | data.prompt | oneOf | Yes | — | Constraints: object | | data.prompt.type | string | Yes | — | Allowed values: label_model, string_check, text_similarity, python, programmatic_grader, completion_tokens, completion_latency, logged_score | | data.prompt.content | string | No | — | — | | data.prompt.operation | string | No | — | Allowed values: eq, ne, like, ilike | | data.prompt.column | string | No | — | — | | data.prompt.evaluation_metric | string | No | — | Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | data.prompt.source | string | No | — | — | | data.evalModel | string | Yes | — | OpenAI model that judges a `label_model` grader. Other grader types ignore it. | | data.choiceScores | object | Yes | — | Constraints: nullable | | data.gradingRules | object[] | Yes | — | Ordered online grading rules. For each span, the first enabled rule that matches decides whether the grader scores it. | | data.gradingRules.id | string | Yes | — | — | | data.gradingRules.enabled | boolean | Yes | — | — | | data.gradingRules.conditions | object[] | Yes | — | Combined with AND. A rule with no conditions matches every span. | | data.gradingRules.conditions.field | string | Yes | — | Span field to match: `ai_config` (AI config IDs, matched by the config name), `config_version` (version IDs), `environment` (`statsig.environment`), `span_name`, `agent_name` (`gen_ai.agent.name`), `model` (`gen_ai.request.model`), or `span_attribute` (the attribute named by `key`). Allowed values: ai_config, config_version, environment, span_name, agent_name, model, span_attribute | | data.gradingRules.conditions.key | string | No | — | Attribute name of a `span_attribute` condition. | | data.gradingRules.conditions.operator | string | Yes | — | `is` matches any of the values exactly and `is_not` matches none of them. A span without the field reads as an empty string. Allowed values: is, is_not | | data.gradingRules.conditions.values | string[] | Yes | — | — | | data.gradingRules.samplingRate | number | Yes | — | Percentage of matching traces to grade, from 0 to 100. Sampling is by trace ID, so every span of a trace gets the same decision. Constraints: min: 0, max: 100 | | data.offlineTargets | oneOf[] | Yes | — | AI configs and datasets the grader scores in offline evals. A version evaluation of an AI config runs its graders and its dataset's graders. An eval run on a dataset always includes that dataset's graders. | | data.offlineTargets.type | string | Yes | — | Allowed values: ai_config, dataset | | data.offlineTargets.aiConfigID | string | No | — | — | | data.offlineTargets.isCritical | boolean | No | — | — | | data.offlineTargets.datasetID | string | No | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "string", "type": "string", "isGlobal": true, "prompt": { "type": "label_model", "content": "string" }, "evalModel": "string", "choiceScores": {}, "gradingRules": [ { "id": "string", "enabled": true, "conditions": [ { "field": "ai_config", "key": "string", "operator": "is", "values": [ "string" ] } ], "samplingRate": 0 } ], "offlineTargets": [ { "type": "ai_config", "aiConfigID": "string", "isCritical": true } ], "createdTime": 0, "lastModifiedTime": 0 } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/eval_graders?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/eval_graders?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_graders?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_graders?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/eval_graders?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_graders?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_graders?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Eval Run Result Rows URL: https://docs.statsig.com/api-reference/evals/list-eval-run-result-rows ================================================================================ # List Eval Run Result Rows ## List Eval Run Result Rows **GET** `/console/v1/evals/{name}/runs/{runId}/results/rows` Full URL: `https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows` List Eval Run Result Rows List the per-row results of a run: one record per dataset row and grader, with the graded output, score, groups and the trace it came from when known. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Eval name | | runId (path) | string | Yes | — | Eval run ID | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Eval Run Result Rows Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.rowID | string | Yes | — | Dataset row the result belongs to. Rows sent through send_results are numbered from 0. | | data.graderID | string | Yes | — | — | | data.score | number | Yes | — | Grader score for the row. `null` when the completion failed before a grader scored it. Constraints: format: double, nullable | | data.columns | object[] | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.columns.value | string | Yes | — | — | | data.output | string | Yes | — | Completion that was graded. | | data.judgeResponse | string | Yes | — | — | | data.groups | string[] | Yes | — | — | | data.traceID | string | Yes | — | Constraints: nullable | | data.spanID | string | Yes | — | Constraints: nullable | | data.runTime | number | Yes | — | Constraints: format: double | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "rowID": "string", "graderID": "string", "score": 0, "columns": [ { "name": "string", "value": "string" } ], "output": "string", "judgeResponse": "string", "groups": [ "string" ], "traceID": "string", "spanID": "string", "runTime": 0 } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}/runs/{runId}/results/rows?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Eval Runs URL: https://docs.statsig.com/api-reference/evals/list-eval-runs ================================================================================ # List Eval Runs ## List Eval Runs **GET** `/console/v1/evals/{name}/runs` Full URL: `https://statsigapi.net/console/v1/evals/{name}/runs` List Eval Runs List the runs of an eval, newest first. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Eval Runs Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.evalID | string | Yes | — | — | | data.status | string | Yes | — | running until the run finishes, then completed, or failed when the run recorded an error. Allowed values: running, completed, failed | | data.createdTime | number | Yes | — | Constraints: format: double | | data.finishTime | number | Yes | — | Constraints: format: double, nullable | | data.runTime | number | Yes | — | Constraints: format: double, nullable | | data.datasetID | string | Yes | — | Dataset the run scored. Null for runs posted from code through send_results. Constraints: nullable | | data.datasetItemCount | number | Yes | — | Constraints: format: double | | data.graderIDs | string[] | Yes | — | — | | data.primaryEvalGraderID | string | Yes | — | Constraints: nullable | | data.parameters | object | Yes | — | Constraints: nullable | | data.errorReason | string | Yes | — | Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "string", "evalID": "string", "status": "running", "createdTime": 0, "finishTime": 0, "runTime": 0, "datasetID": "string", "datasetItemCount": 0, "graderIDs": [ "string" ], "primaryEvalGraderID": "string", "parameters": {}, "errorReason": "string" } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/{name}/runs?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Evals URL: https://docs.statsig.com/api-reference/evals/list-evals ================================================================================ # List Evals ## List Evals **GET** `/console/v1/evals` Full URL: `https://statsigapi.net/console/v1/evals` List Evals List the evals in this project, newest first. An eval groups the runs that score a dataset with a set of graders, or that receive results posted from code. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Evals Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.id | string | Yes | — | Eval ID. | | data.name | string | Yes | — | Eval name. Used as the identifier in routes. | | data.description | string | Yes | — | — | | data.aiConfigID | string | Yes | — | Prompt that created this eval, if any. Constraints: nullable | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "id": "string", "name": "string", "description": "string", "aiConfigID": "string", "createdTime": 0, "lastModifiedTime": 0 } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/evals?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/evals?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/evals?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Send eval results URL: https://docs.statsig.com/api-reference/evals/send-eval-results ================================================================================ # Send eval results ## Send eval results **POST** `/console/v1/evals/send_results/{name}` Full URL: `https://statsigapi.net/console/v1/evals/send_results/{name}` Send eval results Create a run on an existing eval from results scored outside Statsig. Each result carries its input, output, optional expected value and categories, and one or more named scores from 0 to 1. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | My Eval Run | The name of the eval run Constraints: nullable | | results | object[] | Yes | [{"input":"Foo","expected":"Hi Foo","output":"Hi Foo","category":["greeting"],"scores":{"correctness":{"score":1,"metadata":{"justification":"friendly"}},"tone":{"score":1}}}] | Results with input, expected, output and score fields | | results.input | string | Yes | — | — | | results.expected | string | No | — | — | | results.output | string | Yes | — | — | | results.category | oneOf | No | — | Constraints: string[], string | | results.rowID | string | No | — | Stable id of the case this result belongs to, so runs line up row by row. Defaults to the position in results. | | results.traceID | string | No | — | Trace that produced the output, when known. | | results.spanID | string | No | — | — | | results.scores | object | Yes | — | — | | parameters | object | No | {"parameter_name":"parameter_value"} | Parameters | | summaryScores | object | No | {"summary_score_name":100} | Summary scores | | primaryGrader | string | No | — | Score name shown as the primary result. Defaults to the first score. | | criticalGraders | string[] | No | — | Score names treated as release gates: a mean of 0 fails the whole run. | ## Response (application/json) **200** — Send eval results | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.evalID | string | Yes | — | — | | data.status | string | Yes | — | running until the run finishes, then completed, or failed when the run recorded an error. Allowed values: running, completed, failed | | data.createdTime | number | Yes | — | Constraints: format: double | | data.finishTime | number | Yes | — | Constraints: format: double, nullable | | data.runTime | number | Yes | — | Constraints: format: double, nullable | | data.datasetID | string | Yes | — | Dataset the run scored. Null for runs posted from code through send_results. Constraints: nullable | | data.datasetItemCount | number | Yes | — | Constraints: format: double | | data.graderIDs | string[] | Yes | — | — | | data.primaryEvalGraderID | string | Yes | — | Constraints: nullable | | data.parameters | object | Yes | — | Constraints: nullable | | data.errorReason | string | Yes | — | Constraints: nullable | ```json { "message": "string", "data": { "id": "string", "name": "string", "evalID": "string", "status": "running", "createdTime": 0, "finishTime": 0, "runTime": 0, "datasetID": "string", "datasetItemCount": 0, "graderIDs": [ "string" ], "primaryEvalGraderID": "string", "parameters": {}, "errorReason": "string" } } ``` **403** — Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 403 | | message | string | Yes | — | — | ```json { "status": 403, "message": "Forbidden. The request was valid, but the server is refusing action. You might not have the necessary permissions to access the resource." } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/evals/send_results/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/evals/send_results/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/evals/send_results/{name}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/evals/send_results/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/evals/send_results/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/evals/send_results/{name}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/evals/send_results/{name}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Eval Dataset (partial) URL: https://docs.statsig.com/api-reference/evals/update-eval-dataset-partial ================================================================================ # Update Eval Dataset (partial) ## Update Eval Dataset (partial) **PATCH** `/console/v1/eval_datasets/{name}` Full URL: `https://statsigapi.net/console/v1/eval_datasets/{name}` Update Eval Dataset (partial) Add or remove rows, drop columns, or set the output fields. Every change bumps the dataset version. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | rowsToAdd | object[] | No | — | — | | rowsToAdd.columns | object[] | Yes | — | Cell values by column name. A column name not yet on the dataset is added to it. | | rowsToAdd.columns.name | string | Yes | — | Constraints: min length: 1 | | rowsToAdd.columns.value | string | Yes | — | — | | rowsToAdd.groups | string[] | No | — | Group names for the row, created when new. | | rowsToAdd.sourceTraceID | string | No | — | Trace the row was taken from, when it came from production. | | rowsToAdd.sourceSpanID | string | No | — | — | | rowIDsToRemove | string[] | No | — | — | | columnsToRemove | string[] | No | — | Column names to drop from every row. | | outputFields | string[] | No | — | — | ## Response (application/json) **200** — Update Eval Dataset | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.description | string | Yes | — | — | | data.isGlobal | boolean | Yes | — | — | | data.version | number | Yes | — | Counter bumped on every edit to the dataset rows or columns. Constraints: format: double | | data.columns | object[] | Yes | — | — | | data.columns.id | string | Yes | — | — | | data.columns.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.outputFields | string[] | Yes | — | — | | data.imageFields | string[] | Yes | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "description": "string", "isGlobal": true, "version": 0, "columns": [ { "id": "string", "name": "string" } ], "groups": [ { "id": "string", "name": "string" } ], "outputFields": [ "string" ], "imageFields": [ "string" ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/eval_datasets/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/eval_datasets/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_datasets/{name}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_datasets/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/eval_datasets/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_datasets/{name}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_datasets/{name}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Eval Grader (partial) URL: https://docs.statsig.com/api-reference/evals/update-eval-grader-partial ================================================================================ # Update Eval Grader (partial) ## Update Eval Grader (partial) **PATCH** `/console/v1/eval_graders/{name}` Full URL: `https://statsigapi.net/console/v1/eval_graders/{name}` Update Eval Grader (partial) Rename a grader or replace its definition. Runs already scored keep the definition they ran with. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Constraints: min length: 1 | | prompt | object | No | — | Replaces the whole definition when present. | | prompt.type | string | Yes | — | label_model is an LLM judge over {{output}} (content is the rubric); string_check compares {{output}} to a dataset column with operation; text_similarity scores {{output}} against a column with evaluation_metric; python runs source. Allowed values: label_model, string_check, text_similarity, python | | prompt.content | string | No | — | Rubric for label_model. May reference {{output}} and dataset columns. Constraints: nullable | | prompt.operation | string | No | — | Constraints: nullable Allowed values: eq, ne, like, ilike | | prompt.evaluation_metric | string | No | — | Similarity measure for text_similarity. Constraints: nullable Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | prompt.column | string | No | — | Dataset column compared against for string_check and text_similarity. Constraints: nullable | | prompt.source | string | No | — | Python source for a python grader. Constraints: nullable | | evalModel | string | No | — | OpenAI model that judges a `label_model` grader, such as `gpt-5-mini`. Other grader types ignore it. An unsupported model returns a 400. Defaults to `gpt-5-mini` on create; omit it on update to keep the current model. Constraints: min length: 1 | | gradingRules | object[] | No | — | Replaces the grader's ordered online grading rules. Enabled rules start online grading of matching live spans without attaching the grader to a prompt or turning on Auto Eval, so changing which rules are enabled needs a project or org admin. Only graders whose definition reads just {{input}}, {{output}} and {{trajectory}} can have rules. AI config and version IDs must exist. | | gradingRules.id | string | No | — | Omit for a new rule. Keep it to update an existing one. | | gradingRules.enabled | boolean | Yes | — | — | | gradingRules.conditions | object[] | Yes | — | Combined with AND. A rule with no conditions matches every span. | | gradingRules.conditions.field | string | Yes | — | Span field to match: `ai_config` (AI config IDs, matched by the config name), `config_version` (version IDs), `environment` (`statsig.environment`), `span_name`, `agent_name` (`gen_ai.agent.name`), `model` (`gen_ai.request.model`), or `span_attribute` (the attribute named by `key`). Allowed values: ai_config, config_version, environment, span_name, agent_name, model, span_attribute | | gradingRules.conditions.key | string | No | — | Attribute name of a `span_attribute` condition. | | gradingRules.conditions.operator | string | Yes | — | `is` matches any of the values exactly and `is_not` matches none of them. A span without the field reads as an empty string. Allowed values: is, is_not | | gradingRules.conditions.values | string[] | Yes | — | — | | gradingRules.samplingRate | number | Yes | — | Percentage of matching traces to grade, from 0 to 100. Sampling is by trace ID, so every span of a trace gets the same decision. Constraints: min: 0, max: 100 | | offlineTargets | oneOf[] | No | — | AI configs (by aiConfigID) and datasets (by datasetID) the grader scores in offline evals. Replaces the whole list when present. Detaching an AI config where the grader runs online is rejected; turn off online grading on the config first. | | offlineTargets.type | string | Yes | — | Allowed values: ai_config, dataset | | offlineTargets.aiConfigID | string | No | — | — | | offlineTargets.isCritical | boolean | No | — | — | | offlineTargets.datasetID | string | No | — | — | ## Response (application/json) **200** — Update Eval Grader | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | — | | data.name | string | Yes | — | — | | data.type | string | Yes | — | Grader type: label_model, string_check, text_similarity, python, completion_tokens, completion_latency, or logged_score. | | data.isGlobal | boolean | Yes | — | — | | data.prompt | oneOf | Yes | — | Constraints: object | | data.prompt.type | string | Yes | — | Allowed values: label_model, string_check, text_similarity, python, programmatic_grader, completion_tokens, completion_latency, logged_score | | data.prompt.content | string | No | — | — | | data.prompt.operation | string | No | — | Allowed values: eq, ne, like, ilike | | data.prompt.column | string | No | — | — | | data.prompt.evaluation_metric | string | No | — | Allowed values: fuzzy_match, bleu, gleu, meteor, rouge_1, rouge_2, rouge_3, rouge_4, rouge_5, rouge_l, cosine | | data.prompt.source | string | No | — | — | | data.evalModel | string | Yes | — | OpenAI model that judges a `label_model` grader. Other grader types ignore it. | | data.choiceScores | object | Yes | — | Constraints: nullable | | data.gradingRules | object[] | Yes | — | Ordered online grading rules. For each span, the first enabled rule that matches decides whether the grader scores it. | | data.gradingRules.id | string | Yes | — | — | | data.gradingRules.enabled | boolean | Yes | — | — | | data.gradingRules.conditions | object[] | Yes | — | Combined with AND. A rule with no conditions matches every span. | | data.gradingRules.conditions.field | string | Yes | — | Span field to match: `ai_config` (AI config IDs, matched by the config name), `config_version` (version IDs), `environment` (`statsig.environment`), `span_name`, `agent_name` (`gen_ai.agent.name`), `model` (`gen_ai.request.model`), or `span_attribute` (the attribute named by `key`). Allowed values: ai_config, config_version, environment, span_name, agent_name, model, span_attribute | | data.gradingRules.conditions.key | string | No | — | Attribute name of a `span_attribute` condition. | | data.gradingRules.conditions.operator | string | Yes | — | `is` matches any of the values exactly and `is_not` matches none of them. A span without the field reads as an empty string. Allowed values: is, is_not | | data.gradingRules.conditions.values | string[] | Yes | — | — | | data.gradingRules.samplingRate | number | Yes | — | Percentage of matching traces to grade, from 0 to 100. Sampling is by trace ID, so every span of a trace gets the same decision. Constraints: min: 0, max: 100 | | data.offlineTargets | oneOf[] | Yes | — | AI configs and datasets the grader scores in offline evals. A version evaluation of an AI config runs its graders and its dataset's graders. An eval run on a dataset always includes that dataset's graders. | | data.offlineTargets.type | string | Yes | — | Allowed values: ai_config, dataset | | data.offlineTargets.aiConfigID | string | No | — | — | | data.offlineTargets.isCritical | boolean | No | — | — | | data.offlineTargets.datasetID | string | No | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.lastModifiedTime | number | Yes | — | Constraints: format: double | ```json { "message": "string", "data": { "id": "string", "name": "string", "type": "string", "isGlobal": true, "prompt": { "type": "label_model", "content": "string" }, "evalModel": "string", "choiceScores": {}, "gradingRules": [ { "id": "string", "enabled": true, "conditions": [ { "field": "ai_config", "key": "string", "operator": "is", "values": [ "string" ] } ], "samplingRate": 0 } ], "offlineTargets": [ { "type": "ai_config", "aiConfigID": "string", "isCritical": true } ], "createdTime": 0, "lastModifiedTime": 0 } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/eval_graders/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/eval_graders/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/eval_graders/{name}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/eval_graders/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/eval_graders/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/eval_graders/{name}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/eval_graders/{name}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get metrics using event name URL: https://docs.statsig.com/api-reference/events/get-metrics-using-event-name ================================================================================ # Get metrics using event name ## Get metrics using event name **GET** `/console/v1/events/{eventName}/metrics` Full URL: `https://statsigapi.net/console/v1/events/{eventName}/metrics` Get metrics using event name ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventName (path) | string | Yes | — | — | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — Get metrics from events response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.name | string | Yes | metricName | The name of the metric, serving as its primary identifier. | | data.type | string | Yes | sum | The type of the metric, defining its aggregation method and characteristics. Allowed values: ratio, sum, composite, mean, event_count_custom, event_user, event_user_window, funnel, undefined, setup_incomplete, composite_sum, import_window, user_warehouse, hybrid_warehouse, count_distinct, ads_segment_active_users, ads_segment_exposed_user_days, percentile, latest_value | | data.isVerified | boolean | No | false | Marks the metric as verified, indicating trustworthiness within the organization. | | data.isReadOnly | boolean | No | false | Set to true to make the metric definition editable only through the Console API. | | data.unitTypes | string[] | No | ["stableID","userID"] | Array of unit types associated with the metric, such as stableID or userID. | | data.metricEvents | object[] | No | [{"name":"event1","type":"value"}] | An array of event definitions used to compute the metric. For ratio metrics, each event must use count or count_distinct aggregation. | | data.metricEvents.name | string | Yes | — | The name of the metric event. | | data.metricEvents.type | string | No | — | Aggregation type for the metric event. Allowed values: count, count_distinct, value, metadata. For ratio metrics, only count and count_distinct are valid. Do not confuse with criteria[].type, which is a filter condition type. Constraints: nullable Allowed values: count, count_distinct, value, metadata | | data.metricEvents.metadataKey | string | No | — | The key for associated metadata, if applicable. | | data.metricEvents.criteria | object[] | No | — | Filtering criteria for the metric event, including conditions and values to refine the event data. | | data.metricEvents.criteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.metricEvents.criteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.metricEvents.criteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.metricEvents.criteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.metricEvents.criteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.metricComponentMetrics | object[] | No | [] | List of input metrics used to calculate the new metric for composite types. | | data.metricComponentMetrics.name | string | Yes | — | — | | data.metricComponentMetrics.type | string | Yes | — | — | | data.description | string | No | the description of this metric | An optional description providing additional context about the metric. | | data.directionality | string | Yes | increase | Specifies the desired directionality for the metric, indicating whether an increase or decrease is favorable. Allowed values: increase, decrease | | data.tags | string[] | No | ["tag1","tag2"] | Optional tags for categorizing the metric and improving searchability. | | data.isPermanent | boolean | No | false | Indicates whether the metric is permanent and should not be deleted. | | data.rollupTimeWindow | string | No | custom | Time window for the metric rollup. Specify "custom" for a customized time window. | | data.customRollUpStart | number | No | 1 | Custom time window start date in days since exposure. Constraints: format: double | | data.customRollUpEnd | number | No | 1 | Custom time window end date in days since exposure. Constraints: format: double | | data.percentile | number | No | 0.95 | Percentile value for percentile metrics. Constraints: format: double, min: 0.001, max: 0.999 | | data.funnelEventList | object[] | No | — | List of events used to create funnel metrics. | | data.funnelEventList.name | string | Yes | event1 | The name of the funnel event used in the metric. | | data.funnelEventList.type | string | Yes | event_dau | The type of funnel event, specifying how the event is tracked. Allowed values: event_dau, event_user, event_count, event_count_custom | | data.funnelCountDistinct | string | No | — | Specifies whether to count events or distinct users for the funnel metric. Allowed values: events, users | | data.warehouseNative | object | No | — | Defines warehouse native metrics for advanced configurations. | | data.warehouseNative.aggregation | string | No | — | Allowed: count┃sum┃mean┃daily_participation┃ratio┃funnel┃count_distinct┃percentile┃first_value┃latest_value┃retention┃max┃min┃composite Allowed values: count, sum, mean, daily_participation, ratio, funnel, count_distinct, percentile, first_value, latest_value, retention, max, min, composite, | | data.warehouseNative.metricSourceName | string | No | — | Deprecated: use `metricSources` instead. If provided, this will overwrite all metric sources. For Count, Sum, Mean, User Count aggregation types: the name of metric source | | data.warehouseNative.criteria | object[] | No | — | Deprecated: use `metricSources` instead. If provided with `metricSourceName`, this will overwrite all metric sources. Filtering criteria for the metric source | | data.warehouseNative.criteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.warehouseNative.criteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.warehouseNative.criteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.warehouseNative.criteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.warehouseNative.criteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.warehouseNative.metricSources | object[] | No | — | List of metric sources for this metric. | | data.warehouseNative.metricSources.metricSourceName | string | Yes | — | — | | data.warehouseNative.metricSources.criteria | object[] | Yes | — | Filtering criteria for the metric source | | data.warehouseNative.metricSources.criteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.warehouseNative.metricSources.criteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.warehouseNative.metricSources.criteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.warehouseNative.metricSources.criteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.warehouseNative.metricSources.criteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.warehouseNative.metricSources.valueColumn | string | No | — | — | | data.warehouseNative.waitForCohortWindow | boolean | No | — | — | | data.warehouseNative.denominatorCriteria | object[] | No | — | Filtering criteria for the denominator metric source for a ratio, or the start event for a retention metric if useSecondaryRetentionEvent is set | | data.warehouseNative.denominatorCriteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.warehouseNative.denominatorCriteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.warehouseNative.denominatorCriteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.warehouseNative.denominatorCriteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.warehouseNative.denominatorCriteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.warehouseNative.denominatorAggregation | string | No | — | Aggregation for the ratio denominator. Allowed: `count`┃`sum`┃`daily_participation`┃`count_distinct`┃`first_value`┃`latest_value`┃`max`┃`min`. Allowed values: count, sum, mean, daily_participation, ratio, funnel, count_distinct, percentile, first_value, latest_value, retention, max, min, composite, | | data.warehouseNative.denominatorCustomRollupEnd | number | No | — | Custom end window for ratio denominator unit count metrics with "custom" rollup time window. Measured in days or minutes depending on the "denominatorCustomRollupMeasureInMinutes" flag. Constraints: format: double | | data.warehouseNative.denominatorCustomRollupStart | number | No | — | Custom start window for ratio denominator unit count metrics with "custom" rollup time window. Measured in days or minutes depending on the "denominatorCustomRollupMeasureInMinutes" flag. Constraints: format: double | | data.warehouseNative.denominatorMetricSourceName | string | No | — | Name of the metric source for the denominator of a ratio, or the start event for a retention metric if useSecondaryRetentionEvent is set | | data.warehouseNative.denominatorRollupTimeWindow | string | No | — | Rollup-mode for ratio denominator unit count metrics. Allowed values: "daily" for daily participation rate, "max" for one-time event, "custom" for a custom attribution window | | data.warehouseNative.denominatorValueColumn | string | No | — | Column name for the denominator’s value. | | data.warehouseNative.funnelCalculationWindow | integer | No | — | Duration for counting funnel events in days. Constraints: format: int64, min: 0 | | data.warehouseNative.funnelCountDistinct | string | No | — | Allowed: users┃sessions for distinct count method in funnel events. Allowed values: sessions, users | | data.warehouseNative.funnelEvents | object[] | No | — | List of funnel events with associated criteria and identifiers. | | data.warehouseNative.funnelEvents.criteria | object[] | No | — | Optional array of criteria to filter the funnel events, defined by various types and conditions. | | data.warehouseNative.funnelEvents.criteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.warehouseNative.funnelEvents.criteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.warehouseNative.funnelEvents.criteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.warehouseNative.funnelEvents.criteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.warehouseNative.funnelEvents.criteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.warehouseNative.funnelEvents.metricSourceName | string | No | — | Optional name of the metric source associated with the funnel event. | | data.warehouseNative.funnelEvents.name | string | No | — | Optional step name for the funnel event, can be null if not specified. Constraints: nullable | | data.warehouseNative.funnelEvents.sessionIdentifierField | string | No | — | Name of column which being used as session identifier. Funnel event with the same metric source Constraints: nullable | | data.warehouseNative.funnelStartCriteria | string | No | — | Allowed: start_event┃exposure to determine funnel start criteria. Allowed values: start_event, exposure | | data.warehouseNative.metricDimensionColumns | string[] | No | — | Specify metadata columns for breaking down metric analysis. | | data.warehouseNative.metricDimensionLimits | object[] | No | — | Per-dimension breakdown limits; values beyond the limit are grouped into OTHER. | | data.warehouseNative.metricDimensionLimits.name | string | Yes | — | Name of the metadata dimension to apply a breakdown limit. | | data.warehouseNative.metricDimensionLimits.limit | integer | Yes | 10 | Maximum number of values to retain for this dimension (0-100). Constraints: min: 0, max: 100 | | data.warehouseNative.metricBakeDays | integer | No | — | Number of days for metric baking; specify duration for analysis. Constraints: format: int64, min: 0 | | data.warehouseNative.loadingWindow | integer | No | 90 | Lookback window in days for loading metric data. Defaults to 90 days. Constraints: format: int64, min: 0 | | data.warehouseNative.numeratorAggregation | string | No | — | Aggregation for the ratio numerator. Allowed: `count`┃`sum`┃`daily_participation`┃`count_distinct`┃`first_value`┃`latest_value`┃`max`┃`min`. Allowed values: count, sum, mean, daily_participation, ratio, funnel, count_distinct, percentile, first_value, latest_value, retention, max, min, composite, | | data.warehouseNative.valueColumn | string | No | — | Deprecated: use `metricSources` instead. If provided with `metricSourceName`, this will overwrite all metric sources. Column name representing the metric’s value. | | data.warehouseNative.valueThreshold | number | No | — | Threshold value for filtering metrics. Constraints: format: double | | data.warehouseNative.allowNullRatioDenominator | boolean | No | — | Include units which do not have a denominator. Only applicable to ratios. | | data.warehouseNative.funnelStrictOrdering | boolean | No | — | — | | data.warehouseNative.funnelUseExposureAsFirstEvent | boolean | No | — | — | | data.warehouseNative.funnelTimestampAllowanceMs | number | No | — | Constraints: format: double | | data.warehouseNative.funnelTimeToConvert | boolean | No | — | — | | data.warehouseNative.winsorizationHigh | number | No | — | High threshold for winsorization; must be between 0 and 1. Constraints: format: double, min: 0, max: 1 | | data.warehouseNative.winsorizationLow | number | No | — | Low threshold for winsorization; must be between 0 and 1. Constraints: format: double, min: 0, max: 1 | | data.warehouseNative.winsorizationHighDenominator | number | No | — | Constraints: format: double, min: 0, max: 1 | | data.warehouseNative.winsorizationLowDenominator | number | No | — | Constraints: format: double, min: 0, max: 1 | | data.warehouseNative.cupedAttributionWindow | integer | No | — | Attribution window for CUPED adjustments in days. Constraints: format: int64, nullable, min: 0 | | data.warehouseNative.rollupTimeWindow | string | No | — | Rollup-mode for unit count metrics. Allowed values: "daily" for daily participation rate, "max" for one-time event, "custom" for a custom attribution window | | data.warehouseNative.customRollUpStart | integer | No | — | Custom start window for unit count metrics with "custom" rollup time window, or for other metrics with the "Use Cohort Window in Experiments" option on enabled. Measured in days or minutes depending on the "customRollupMeasureInMinutes" flag. Constraints: format: int64, min: 0 | | data.warehouseNative.customRollUpEnd | integer | No | — | Custom end window for unit count metrics with "custom" rollup time window, or for other metrics with the "Use Cohort Window in Experiments" option on enabled. Measured in days or minutes depending on the "customRollupMeasureInMinutes" flag. Constraints: format: int64, min: 0 | | data.warehouseNative.onlyIncludeUsersWithConversionEvent | boolean | No | — | Flag to include only users with a conversion event in the metric. | | data.warehouseNative.denominatorCustomRollupMeasureInMinutes | boolean | No | — | Flag to measure the denominator custom rollup window in minutes instead of days. | | data.warehouseNative.customRollupMeasureInMinutes | boolean | No | — | Flag to measure the custom rollup window in minutes instead of days. | | data.warehouseNative.percentile | number | No | — | Percentile value for statistical calculations. Constraints: format: double, min: 0.001, max: 0.999 | | data.warehouseNative.useLogTransform | boolean | No | — | Use log transform for the metric. | | data.warehouseNative.useSecondaryRetentionEvent | boolean | No | — | Use a different start and completion event for retention calculations. | | data.warehouseNative.retentionEnd | integer | No | — | Retention end in days. Constraints: format: int64, min: 0 | | data.warehouseNative.retentionLength | integer | No | — | Retention lookback window in days. Constraints: format: int64, min: 0 | | data.warehouseNative.logTransformBase | number | No | — | Log transform base to be used for the metric. Constraints: format: double, nullable, min: 0 | | data.warehouseNative.cap | number | No | — | Maximum cap for metric values. Constraints: format: double | | data.warehouseNative.surrogateMetricMSE | number | No | — | Nonnegative mean squared prediction error used to inflate experiment variance. Supports `latest_value`, `first_value`, and `composite`. For composites, supply the error of the entire formula in squared metric units, accounting for all predictive components. Constraints: format: double, nullable | | data.warehouseNative.components | object[] | No | — | Components for composite metrics, defining each component of the formula | | data.warehouseNative.components.operator | string | Yes | — | Operator for this component Allowed values: +, - | | data.warehouseNative.components.aggregation | string | No | — | Aggregation type for this component Allowed values: count, sum, mean, daily_participation, ratio, funnel, count_distinct, percentile, first_value, latest_value, retention, max, min, composite, | | data.warehouseNative.components.metricSourceName | string | No | — | Metric source name for this component | | data.warehouseNative.components.name | string | No | — | Optional name for this component Constraints: nullable | | data.warehouseNative.components.criteria | object[] | No | — | Optional filtering criteria for this component | | data.warehouseNative.components.criteria.type | string | Yes | — | Type of event criterion for filtering metrics. Options include `value`, `metadata`, `user`, and `user_custom`; in Warehouse Native, this should always be `metadata`. Allowed values: value, metadata, user, user_custom | | data.warehouseNative.components.criteria.column | string | No | — | Optional column specifying which data attribute to filter on. | | data.warehouseNative.components.criteria.condition | string | Yes | — | sql_filter, starts_with, ends_with, after_exposure, and before_exposure are only applicable in Warehouse Native Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.warehouseNative.components.criteria.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.warehouseNative.components.criteria.nullVacuousOverride | boolean | No | — | If true, overrides null values in criterion evaluation. | | data.warehouseNative.components.valueColumn | string | No | — | Value column for this component | | data.team | string | No | — | The team associated with the metric, applicable for enterprise environments. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the metric, applicable for enterprise environments. Constraints: nullable | | data.localMetric | object | No | — | Attaches the new metric to an experiment or gate as a local metric. Statsig stores the name as `<configName>:<name>` unless `name` already starts with that prefix. Dimension filters and breakdown columns go on `warehouseNative.criteria` and `warehouseNative.metricDimensionColumns`. | | data.localMetric.configName | string | Yes | purchase_experiment | Name of the experiment or gate that owns this local metric. | | data.localMetric.section | string | Yes | primary | Scorecard section that receives the metric. Use `primary`, `secondary`, or `other` on an experiment. Use `monitoring` on a gate. `other` requires an Other Metrics scorecard section on the experiment. Allowed values: primary, secondary, other, monitoring | | data.localMetric.clusterUnitType | string | No | user_id | Unit type for cluster analysis. `userID` is stored as `user_id` and `stableID` is stored as `stable_id`. When `unitTypes` is set, this must be one of those values. | | data.dryRun | boolean | No | — | Skips persisting the metric (used to validate that inputs are correct) | | data.id | string | Yes | metricId | Unique identifier for the metric, used for referencing within the system. | | data.isHidden | boolean | No | false | Indicates if the metric is hidden from the user interface. | | data.lineage | object | Yes | — | — | | data.lineage.events | string[] | Yes | ["event1","event2"] | List of event names that contribute to the metric’s calculation. | | data.lineage.metrics | string[] | Yes | ["metric1","metric2"] | List of metric names that are part of this metric’s lineage. | | data.creatorName | string | No | creatorName | Name of the person who created the metric, if available. Constraints: nullable | | data.creatorEmail | string | No | creatorEmail | Email address of the metric creator for contact purposes. Constraints: nullable | | data.createdTime | number | No | 1716230400 | Timestamp indicating when the metric was created. Constraints: format: double | | data.lastModifierID | string | No | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | No | — | Time of the last modification to this metric. Constraints: format: double, nullable | | data.lastModifierEmail | string | No | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | No | — | Name of the last modifier. Constraints: nullable | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled metric reloads. Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled metric reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.permalink | string | Yes | — | A permalink to this metric in the Statsig Console. Constraints: format: uri | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Metrics listed successfully.", "data": [ { "id": "add_to_cart::event_count", "name": "add_to_cart", "directionality": "increase", "type": "event_count", "description": "", "isPermanent": false, "isReadOnly": false, "isHidden": false, "isVerified": false, "tags": [ "dashboard_test" ], "createdTime": 1678165878415, "lineage": { "events": [ "add_to_cart" ], "metrics": [] }, "team": null }, { "id": "add_to_cart::event_dau", "name": "add_to_cart", "directionality": "increase", "type": "event_dau", "description": "", "isPermanent": false, "isReadOnly": false, "isHidden": false, "isVerified": false, "tags": [ "asdf", "dashboard_test" ], "createdTime": 1680128775716, "lineage": { "events": [ "add_to_cart" ], "metrics": [] }, "team": null }, { "id": "test funnel 1::funnel", "name": "test funnel 1", "directionality": "increase", "type": "funnel", "description": "", "isPermanent": false, "isReadOnly": false, "isHidden": false, "isVerified": false, "tags": [], "creatorName": "Test User", "creatorEmail": "test@statsig.com", "createdTime": 1695253296002, "owner": { "name": "Test User" }, "lineage": { "events": [], "metrics": [ "add_to_cart::event_count", "add_to_cart_games::event_count_custom" ] }, "team": null, "funnelCountDistinct": "events", "funnelEventList": [ { "name": "add_to_cart", "type": "event_count" }, { "name": "add_to_cart_games", "type": "event_count_custom" } ] }, { "id": "super_long_metric_nameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee_thing::funnel", "name": "super_long_metric_nameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee_thing", "directionality": "increase", "type": "funnel", "description": "test", "isPermanent": false, "isReadOnly": false, "isHidden": false, "isVerified": false, "tags": [ "Funnels" ], "creatorName": "Test User ", "creatorEmail": "test@statsig.com", "createdTime": 1698427486777, "owner": { "name": "Test User" }, "lineage": { "events": [], "metrics": [ "add_to_cart::event_dau", "new_custom_metric::event_user" ] }, "team": null, "funnelCountDistinct": "users", "funnelEventList": [ { "name": "add_to_cart", "type": "event_dau" }, { "name": "new_custom_metric", "type": "event_user" } ] }, { "id": "test_funnel_metric::funnel", "name": "test_funnel_metric", "directionality": "decrease", "type": "funnel", "description": "", "isPermanent": false, "isReadOnly": false, "isHidden": false, "isVerified": false, "tags": [ "Funnels" ], "creatorName": "Test User", "creatorEmail": "test@statsig.com", "createdTime": 1701984009755, "owner": { "name": "Test User" }, "lineage": { "events": [], "metrics": [ "add_to_cart::event_dau" ] }, "team": null, "funnelCountDistinct": "users", "funnelEventList": [ { "name": "add_to_cart", "type": "event_dau" } ] } ], "pagination": { "itemsPerPage": 5, "pageNumber": 1, "totalItems": 1254, "nextPage": "?page=2&limit=5", "previousPage": null, "all": "" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/events/{eventName}/metrics?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get specific events URL: https://docs.statsig.com/api-reference/events/get-specific-events ================================================================================ # Get specific events ## Get specific events **GET** `/console/v1/events/{eventName}` Full URL: `https://statsigapi.net/console/v1/events/{eventName}` Get specific events Returns recently logged events for the given event name. Results cover a limited rolling window of recent occurrences, not full historical volume for that event. `limit` and `page` paginate only within the returned set; `totalItems` is the size of that set, not lifetime event volume. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | eventName (path) | string | Yes | — | — | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — Get specific events response. `pagination.totalItems` is the number of recent events in the current result set, not total events ever logged for this event name. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.timestamp | string | Yes | — | The timestamp when the event occurred, represented as a string. | | data.name | string | Yes | — | The name of the event (e.g., "add_to_cart"). | | data.source | string | Yes | — | The source of the event, indicating where it was triggered from. | | data.value | string | Yes | — | The value associated with the event, providing additional context. | | data.userID | string | Yes | — | The ID of the user who triggered the event. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Event values listed successfully.", "data": [ { "timestamp": "1720567904601", "name": "add_to_cart", "source": "statsig-node", "value": "appliances", "userID": "3411", "metadata": {} }, { "timestamp": "1720567904594", "name": "add_to_cart", "source": "statsig-node", "value": "sports", "userID": "1037", "metadata": {} }, { "timestamp": "1720567904307", "name": "add_to_cart", "source": "statsig-node", "value": "", "userID": "5056", "metadata": {} }, { "timestamp": "1720567904299", "name": "add_to_cart", "source": "statsig-node", "value": "books", "userID": "7326", "metadata": {} }, { "timestamp": "1720567904288", "name": "add_to_cart", "source": "statsig-node", "value": "books", "userID": "166", "metadata": {} }, { "timestamp": "1720567904310", "name": "add_to_cart", "source": "statsig-node", "value": "office products", "userID": "3255", "metadata": {} }, { "timestamp": "1720567904299", "name": "add_to_cart", "source": "statsig-node", "value": "sports", "userID": "8598", "metadata": {} } ], "pagination": { "itemsPerPage": 7, "pageNumber": 1, "totalItems": 7, "nextPage": null, "previousPage": null, "all": "/console/v1/events/add_to_cart" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/events/{eventName}?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Events URL: https://docs.statsig.com/api-reference/events/list-events ================================================================================ # List Events ## List Events **GET** `/console/v1/events` Full URL: `https://statsigapi.net/console/v1/events` List Events Returns recently logged events across all event names in your project. Results cover a limited rolling window of recent traffic, not full event history. `limit` and `page` paginate only within the returned set; `totalItems` is the size of that set, not lifetime event volume. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Events response. `pagination.totalItems` is the number of recent events in the current result set, not total events ever logged. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.timestamp | string | Yes | — | The timestamp when the event occurred, represented as a string. | | data.name | string | Yes | — | The name of the event (e.g., "add_to_cart"). | | data.source | string | Yes | — | The source of the event, indicating where it was triggered from. | | data.value | string | Yes | — | The value associated with the event, providing additional context. | | data.userID | string | Yes | — | The ID of the user who triggered the event. | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Event values listed successfully.", "data": [ { "timestamp": "1720567284328", "name": "time_spent_on_page", "source": "statsig-node", "value": "463", "userID": "1922", "metadata": {} }, { "timestamp": "1720567284328", "name": "add_to_cart", "source": "statsig-node", "value": "appliances", "userID": "1922", "metadata": {} }, { "timestamp": "1720567284321", "name": "time_spent_on_page", "source": "statsig-node", "value": "421", "userID": "1026", "metadata": {} }, { "timestamp": "1720567284321", "name": "add_to_cart", "source": "statsig-node", "value": "electronics", "userID": "1026", "metadata": {} }, { "timestamp": "1720567284485", "name": "time_spent_on_page", "source": "statsig-node", "value": "273", "userID": "8455", "metadata": {} } ], "pagination": { "itemsPerPage": 5, "pageNumber": 1, "totalItems": 1000, "nextPage": "/console/v1/events?page=2&limit=5", "previousPage": null, "all": "/console/v1/events" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/events?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/events?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/events?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/events?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/events?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/events?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/events?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Abandon Experiment URL: https://docs.statsig.com/api-reference/experiments/abandon-experiment ================================================================================ # Abandon Experiment ## Abandon Experiment **PUT** `/console/v1/experiments/{id}/abandon` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/abandon` Abandon Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | decisionReason | string | Yes | Your reason for stopping early | The reason for making the decision to update the experiment status | ## Response (application/json) **200** — Abandon Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully abandoned." } ``` **400** — Experiment has not yet started | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/abandon" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/abandon", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/abandon", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/abandon"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/abandon", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/abandon")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/abandon") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Approve Experiment Review URL: https://docs.statsig.com/api-reference/experiments/approve-experiment-review ================================================================================ # Approve Experiment Review ## Approve Experiment Review **PUT** `/console/v1/experiments/{id}/reviews/{reviewID}/approve` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve` Approve Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | No | — | Optional comment recorded with the approval. Constraints: max length: 2000 | ## Response (application/json) **200** — The approved experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/approve") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Archive Experiment URL: https://docs.statsig.com/api-reference/experiments/archive-experiment ================================================================================ # Archive Experiment ## Archive Experiment **PUT** `/console/v1/experiments/{id}/archive` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/archive` Archive Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | archiveReason | string | No | The experiment is no longer needed | The reason for archiving the experiment | ## Response (application/json) **200** — Archive Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully archived." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/archive" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "archiveReason": "The experiment is no longer needed" }' ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/archive", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "archiveReason": "The experiment is no longer needed" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/archive", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "archiveReason": "The experiment is no longer needed" }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/archive"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "archiveReason": "The experiment is no longer needed" }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"archiveReason\":\"The experiment is no longer needed\"}") req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/archive", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/archive")) .method("PUT", HttpRequest.BodyPublishers.ofString("{\"archiveReason\":\"The experiment is no longer needed\"}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/archive") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"archiveReason\":\"The experiment is no longer needed\"}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Experiment Review URL: https://docs.statsig.com/api-reference/experiments/cancel-experiment-review ================================================================================ # Cancel Experiment Review ## Cancel Experiment Review **DELETE** `/console/v1/experiments/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}` Cancel Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — Cancel an in-flight experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment review cancelled successfully" } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Scheduled Experiment Stop URL: https://docs.statsig.com/api-reference/experiments/cancel-scheduled-experiment-stop ================================================================================ # Cancel Scheduled Experiment Stop ## Cancel Scheduled Experiment Stop **POST** `/console/v1/experiments/{id}/cancel_scheduled_stop` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop` Cancel Scheduled Experiment Stop ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Cancel Scheduled Experiment Stop Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Successfully cancelled scheduled experiment stop" } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/cancel_scheduled_stop") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Commit Experiment Review URL: https://docs.statsig.com/api-reference/experiments/commit-experiment-review ================================================================================ # Commit Experiment Review ## Commit Experiment Review **PUT** `/console/v1/experiments/{id}/reviews/{reviewID}/commit` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit` Commit Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | bypass_webhook | boolean | No | — | Skip the configured pre-commit webhook and apply the reviewed change immediately. Personal keys require the `bypass_precommit_webhook` permission. An omitted value bypasses automatically for ownerless `omni_read_write` Console API keys; set to `false` to run the configured webhook workflow. | ## Response (application/json) **200** — Commit an experiment review. Unless `bypass_webhook` is authorized, a configured pre-commit webhook must validate the review before a later commit applies the change. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | — | | status | string | Yes | — | Current review status after the commit attempt. A non-final webhook status means the reviewed change was not applied. Allowed values: pending_webhook_validation, failed_webhook_validation, approved_webhook_validation, committed | ```json { "message": "Experiment review committed successfully", "status": "committed" } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/commit") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Conclude Experiment & Defer Decision URL: https://docs.statsig.com/api-reference/experiments/conclude-experiment-defer-decision ================================================================================ # Conclude Experiment & Defer Decision ## Conclude Experiment & Defer Decision **PUT** `/console/v1/experiments/{id}/defer_decision` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/defer_decision` Conclude Experiment & Defer Decision ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | stopReason | string | No | We want more time before choosing a winner | Optional reason for concluding the experiment and deferring the shipping decision | ## Response (application/json) **200** — Conclude Experiment & Defer Decision Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully concluded and decision deferred." } ``` **400** — Experiment cannot defer decision. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/defer_decision" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/defer_decision", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/defer_decision", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/defer_decision"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/defer_decision", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/defer_decision")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/defer_decision") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Experiment URL: https://docs.statsig.com/api-reference/experiments/create-experiment ================================================================================ # Create Experiment ## Create Experiment **POST** `/console/v1/experiments` Full URL: `https://statsigapi.net/console/v1/experiments` Create Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | The experiment display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | description | string | No | — | A description of the new experiment Constraints: max length: 1000 | | idType | string | No | — | The idType the experiment will be performed on | | secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | hypothesis | string | No | — | A statement that will be tested by this experiment | | links | object[] | No | — | Links to relevant documentation or resources | | links.url | string | Yes | — | The URL of the link Constraints: format: uri | | links.title | string | No | — | The title of the link | | externalEvents | object[] | No | — | — | | externalEvents.name | string | Yes | — | — | | externalEvents.timestamp | number | Yes | — | — | | groups | object[] | No | — | The test groups for your experiment | | groups.name | string | Yes | — | — | | groups.id | string | No | — | Constraints: nullable | | groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | groups.disabled | boolean | No | — | — | | groups.description | string | No | — | — | | groups.foreignGroupID | string | No | — | — | | groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | controlGroupID | string | No | — | Optional control group ID | | allocation | number | No | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | userBuckets | number[] | No | — | — | | primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | primaryMetrics | object[] | No | — | Main metrics needed to evaluate your hypothesis | | primaryMetrics.name | string | Yes | — | The metric name. | | primaryMetrics.type | string | Yes | — | The metric type. | | primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | secondaryMetrics | object[] | No | — | Additional metrics to monitor that might impact the analysis or final decision of the experiment | | secondaryMetrics.name | string | Yes | — | The metric name. | | secondaryMetrics.type | string | Yes | — | The metric type. | | secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | otherMetrics.name | string | Yes | — | The metric name. | | otherMetrics.type | string | Yes | — | The metric type. | | otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | tags | string[] | No | — | Tags associated with the experiment | | duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetingGateID | string | No | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | inlineTargetingRules | object[] | No | [{"name":"Eligible users","passPercentage":100,"conditions":[{"type":"passes_segment","targetValue":"paid_users"}]}] | Replaces inline targeting with these rules. Conditions in a rule use AND; rules use ordered evaluation. Set to `[]` to remove targeting. Omit on update to keep existing targeting. Providing this field switches from gate to inline targeting; you can't also set a nonempty `targetingGateID`. Use `passes_segment`, `fails_segment`, `passes_gate`, or `fails_gate` with the segment or gate name ID as `targetValue`. | | inlineTargetingRules.name | string | Yes | — | The name of this rule. | | inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | sequentialTesting | boolean | No | — | Apply sequential testing? | | bonferroniCorrection | boolean | No | — | Is Bonferroni correction applied per variant? | | bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | defaultConfidenceInterval | string | No | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | bayesianPriors.metric | object | Yes | — | — | | bayesianPriors.metric.name | string | Yes | — | — | | bayesianPriors.metric.type | string | Yes | — | — | | bayesianPriors.priorMean | number | Yes | — | — | | bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | manualQualityScores.criteriaDescription | string | Yes | — | — | | manualQualityScores.score | number | Yes | — | — | | manualQualityScores.weight | number | Yes | — | — | | status | string | No | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | assignmentSourceName | string | No | — | Source name of the assignment | | assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | isAnalysisOnly | boolean | No | — | For Warehouse Native Constraints: nullable | | team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | analysisEndTime | string | No | — | Warehouse Native only - end time for analysis only experiments | | assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | assignmentSourceFilters.column | string | No | — | Column to filter on. | | assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | analyticsType | string | No | — | The mode of analysis for the experiment, e.g frequentist, bayesian, sprt Allowed values: frequentist, bayesian, sprt | | defaultSPRTPowerParam | number | No | — | SPRT power parameter percentage used as the default for experiment analysis. Constraints: format: double | | defaultSPRTMDE | number | No | — | Default MDE value for every metric if one isn't provided. Only used in manual mode. Constraints: format: double | | sprtBaselineMode | string | No | — | In manual mode, mde/mean/stdDev must be provided for every metric in the experiment. In in_experiment_control, only the mde is needed for every metric, or the defaultSPRTMDE field must be passed. Allowed values: manual, in_experiment_control | | sprtMDESettings | object[] | No | — | The SPRT values for use in the experiment. | | sprtMDESettings.metricKey | string | Yes | — | — | | sprtMDESettings.groupSettings | object[] | Yes | — | — | | sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | sprtMDESettings.groupSettings.mde | number | Yes | — | — | | sprtMDESettings.groupSettings.mean | number | No | — | — | | sprtMDESettings.groupSettings.stdDev | number | No | — | — | | isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | sidecarURLFilters.value | string | Yes | — | — | | sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | decisionReason | string | No | — | Experiment notes reported after experiment completes | | preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | preComputedUserDimensions.propertySource | string | No | — | — | | preComputedUserDimensions.name | string | Yes | — | — | | cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | cureCovariates.name | string | Yes | — | — | | cureCovariates.type | string | Yes | — | — | | stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | stratifiedSampling.metric | object | No | — | — | | stratifiedSampling.metric.name | string | Yes | — | — | | stratifiedSampling.metric.type | string | No | — | — | | stratifiedSampling.metric.startDate | string | Yes | — | — | | stratifiedSampling.metric.endDate | string | Yes | — | — | | stratifiedSampling.entityPropertySource | object | No | — | — | | stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | stratifiedSampling.csv | object | No | — | — | | stratifiedSampling.csv.original | string | Yes | — | — | | stratifiedSampling.csv.identifier | string | Yes | — | — | | stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | enabledNonProdEnvironments | string[] | No | — | — | | id | string | No | — | The experiment name ID Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_-]*$ | | layerID | string | No | — | Which layer to place the experiment into. | | isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. Settable at creation only. | ## Response (application/json) **201** — Create Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "Experiment created successfully.", "data": { "id": "a_experiment", "permalink": "https://console.statsig.com/company_id/experiments/a_experiment", "name": "a_experiment", "description": "description", "idType": "userID", "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifiedTime": 1707427635442, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "1vaQaBoLlkauH9iiuOSBP2", "createdTime": 1707427634717, "creatorName": "CONSOLE API", "creatorEmail": null, "targetApps": [], "holdoutIDs": [], "tags": [], "status": "setup", "experimentType": "BASE", "launchedGroupID": null, "startTime": null, "endTime": null, "layerID": null, "hypothesis": "This will be a good feature :)", "primaryMetrics": [ { "name": "d1_retention_rate", "type": "user" } ], "primaryMetricTags": [], "secondaryMetrics": [], "secondaryMetricTags": [], "groups": [ { "name": "Control", "id": "6sEQvUd4c6E55V6ljBYMeJ", "size": 50, "parameterValues": { "assigned_group": "control" }, "description": "", "isControl": true }, { "name": "Test", "id": "6sEQvVS6EoNzpkEgUJUpxL", "size": 50, "parameterValues": { "assigned_group": "test" }, "description": "", "isControl": false } ], "allocation": 100, "duration": 14, "targetingGateID": "", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "decisionReason": null, "decisionTime": null, "healthChecks": [], "healthCheckStatus": "PASSED", "isStale": false, "inlineTargetingRulesJSON": "{}", "powerAnalyses": [] } } ``` **400** — Name is already in use | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "name": "Test Experiment", "description": "Description test", "inlineTargetingRules": [ { "name": "Eligible users", "passPercentage": 100, "conditions": [ { "type": "passes_segment", "targetValue": "paid_users" } ] } ] }' ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "name": "Test Experiment", "description": "Description test", "inlineTargetingRules": [ { "name": "Eligible users", "passPercentage": 100, "conditions": [ { "type": "passes_segment", "targetValue": "paid_users" } ] } ] } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "name": "Test Experiment", "description": "Description test", "inlineTargetingRules": [ { "name": "Eligible users", "passPercentage": 100, "conditions": [ { "type": "passes_segment", "targetValue": "paid_users" } ] } ] }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "name": "Test Experiment", "description": "Description test", "inlineTargetingRules": [ { "name": "Eligible users", "passPercentage": 100, "conditions": [ { "type": "passes_segment", "targetValue": "paid_users" } ] } ] }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"name\":\"Test Experiment\",\"description\":\"Description test\",\"inlineTargetingRules\":[{\"name\":\"Eligible users\",\"passPercentage\":100,\"conditions\":[{\"type\":\"passes_segment\",\"targetValue\":\"paid_users\"}]}]}") req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments")) .method("POST", HttpRequest.BodyPublishers.ofString("{\"name\":\"Test Experiment\",\"description\":\"Description test\",\"inlineTargetingRules\":[{\"name\":\"Eligible users\",\"passPercentage\":100,\"conditions\":[{\"type\":\"passes_segment\",\"targetValue\":\"paid_users\"}]}]}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"name\":\"Test Experiment\",\"description\":\"Description test\",\"inlineTargetingRules\":[{\"name\":\"Eligible users\",\"passPercentage\":100,\"conditions\":[{\"type\":\"passes_segment\",\"targetValue\":\"paid_users\"}]}]}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Experiment Review URL: https://docs.statsig.com/api-reference/experiments/create-experiment-review ================================================================================ # Create Experiment Review ## Create Experiment Review **POST** `/console/v1/experiments/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews` Create Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | type | string | Yes | — | The kind of experiment change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, disable_reviews_locally | | description | string | No | — | Human-readable description of the proposed change. Optional; recorded empty when omitted (e.g. `update_owners`, mirroring the console owner-edit flow, which collects no description). Constraints: max length: 2000 | | reviewer_ids | string[] | No | [] | User IDs to request review from. | | reviewer_group_ids | string[] | No | [] | Reviewer group IDs to request review from. | | reason | string | No | — | Optional reason recorded with the change, applied when committed (e.g. stop / pause / abandon / decision reason). Constraints: max length: 2000 | | winning_group_id | string | No | — | For `make_decision`: the group to ship. Required. | | remove_targeting | boolean | No | — | For `make_decision`: drop targeting on ship (default false). | | remove_overrides | boolean | No | — | For `make_decision`: drop overrides on ship (default false). | | start_date | string | No | — | For `start`: optional scheduled start date. | | stop_time | integer | No | — | Epoch-ms time to stop the experiment. Required with `stop_action_type` for `scheduled_stop`. For `start`: optional, and must be sent together with `stop_action_type`. For `scheduled_stop_edit`: the new stop time, or `null` to cancel the pending stop (its action is left unchanged). Constraints: format: int64, nullable | | stop_action_type | string | No | — | What the scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Required with `stop_time` for `scheduled_stop`; sent with `stop_time` for `start`. For `scheduled_stop_edit`: the new action; omit to keep the pending action. Allowed values: pause, stop | | group_id | string | No | — | For `rollout` / `schedule_rollout`: the group to roll out. Required. | | rollout_percentage | number | No | — | For `rollout`: the pass percentage to roll the group out to. Required. Constraints: format: double, min: 0, max: 100 | | clear_phases | boolean | No | — | For `rollout`: clear any scheduled rollout phases (default false). | | rollout_phases | object[] | No | — | For `schedule_rollout`: the ordered rollout phases to schedule. Required. | | rollout_phases.percentage | number | Yes | — | Pass percentage for this phase (0–100). Constraints: min: 0, max: 100 | | rollout_phases.time | number | No | — | Absolute start time of the phase (epoch ms). | | rollout_phases.time_string | string | No | — | Human-readable start time of the phase. | | rollout_phases.is_complete | boolean | No | — | Whether this phase is already complete (default false). | | rollout_phases.phase_duration_ms | number | No | — | Duration of the phase, used for progressive rollouts. | | enabled_group_names | string[] | No | — | For `change_enabled_groups`: group names to enable. | | disabled_group_names | string[] | No | — | For `change_enabled_groups`: group names to disable. | | owners | object[] | No | — | For `update_owners`: the replacement owner set. Required. | | owners.owner_id | string | Yes | — | ID of the owner (user ID or SDK key ID). Constraints: min length: 1 | | owners.owner_type | string | No | — | Kind of owner. Defaults to `user`. Allowed values: user, sdk_key | | team_id | string | No | — | For `update_team`: the team to assign, or `null` to clear it. Constraints: nullable, min length: 1 | | default_impact_multiplier | number | No | — | For `update_default_impact_multiplier`: the new multiplier. Required. Constraints: format: double | | target_app_ids | string[] | No | — | For `update_target_applications`: the full set of target application IDs. Required. | | allowed_reviewer_user_ids | string[] | No | — | For `update_allowed_reviewers`: the full set of allowed reviewer user IDs. | | allowed_reviewer_group_ids | string[] | No | — | For `update_allowed_reviewers`: the full set of allowed reviewer group IDs. | | start_time | integer | No | — | For `scheduled_start`: epoch-ms time to schedule the start. Required. Constraints: format: int64 | | new_time | integer | No | — | For `scheduled_start_edit`: epoch-ms time to reschedule the start to. Required. Constraints: format: int64 | | overrides | object[] | No | — | For `update_overrides`: the full set of gate/segment overrides. Omit to preserve the experiment’s current overrides; send `[]` to clear them. | | overrides.type | string | Yes | — | Allowed values: gate, segment | | overrides.group_id | string | Yes | — | — | | overrides.name | string | Yes | — | — | | overrides.environment | string | No | — | Constraints: nullable | | id_overrides | object[] | No | — | For `update_overrides`: the full set of ID overrides. Omit to preserve the experiment’s current ID overrides; send `[]` to clear them. | | id_overrides.ids | string[] | Yes | — | — | | id_overrides.group_id | string | Yes | — | — | | id_overrides.environment | string | No | — | Constraints: nullable | | id_overrides.unit_type | string | No | — | Constraints: nullable | | allow_overrides_in_pulse | boolean | No | — | For `update_overrides`: whether overridden units are included in Pulse. Omit to preserve the current setting. | | settings | object | No | — | For `update_settings`: the experiment settings to change, matching the `PATCH /console/v1/experiments/:id` body. Required for `update_settings`. Fields omitted from the payload keep the experiment’s current values. A group sent by name, without `size` or `parameterValues`, keeps that group’s current size and parameters. | | settings.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | settings.description | string | No | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | settings.idType | string | No | — | The type of ID which the experiment is based on | | settings.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | settings.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | settings.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | settings.hypothesis | string | No | — | A statement that will be tested by this experiment | | settings.links | object[] | No | — | Links to relevant documentation or resources | | settings.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | settings.links.title | string | No | — | The title of the link | | settings.externalEvents | object[] | No | — | — | | settings.externalEvents.name | string | Yes | — | — | | settings.externalEvents.timestamp | number | Yes | — | — | | settings.controlGroupID | string | No | — | Optional control group ID | | settings.allocation | number | No | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | settings.userBuckets | number[] | No | — | — | | settings.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | settings.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | settings.primaryMetrics | object[] | No | — | Main metrics needed to evaluate your hypothesis | | settings.primaryMetrics.name | string | Yes | — | The metric name. | | settings.primaryMetrics.type | string | Yes | — | The metric type. | | settings.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | settings.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | settings.secondaryMetrics | object[] | No | — | Additional metrics to monitor that might impact the analysis or final decision of the experiment | | settings.secondaryMetrics.name | string | Yes | — | The metric name. | | settings.secondaryMetrics.type | string | Yes | — | The metric type. | | settings.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | settings.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | settings.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | settings.otherMetrics.name | string | Yes | — | The metric name. | | settings.otherMetrics.type | string | Yes | — | The metric type. | | settings.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | settings.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | settings.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | settings.tags | string[] | No | — | Tags associated with the experiment | | settings.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | settings.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | settings.targetingGateID | string | No | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | settings.inlineTargetingRules | object[] | No | [{"name":"Eligible users","passPercentage":100,"conditions":[{"type":"passes_segment","targetValue":"paid_users"}]}] | Replaces inline targeting with these rules. Conditions in a rule use AND; rules use ordered evaluation. Set to `[]` to remove targeting. Omit on update to keep existing targeting. Providing this field switches from gate to inline targeting; you can't also set a nonempty `targetingGateID`. Use `passes_segment`, `fails_segment`, `passes_gate`, or `fails_gate` with the segment or gate name ID as `targetValue`. | | settings.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | settings.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | settings.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | settings.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | settings.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | settings.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | settings.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | settings.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | settings.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | settings.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | settings.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | settings.sequentialTesting | boolean | No | — | Apply sequential testing? | | settings.bonferroniCorrection | boolean | No | — | Is Bonferroni correction applied per variant? | | settings.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | settings.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | settings.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | settings.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | settings.defaultConfidenceInterval | string | No | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | settings.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | settings.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | settings.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | settings.bayesianPriors.metric | object | Yes | — | — | | settings.bayesianPriors.metric.name | string | Yes | — | — | | settings.bayesianPriors.metric.type | string | Yes | — | — | | settings.bayesianPriors.priorMean | number | Yes | — | — | | settings.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | settings.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | settings.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | settings.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | settings.manualQualityScores.criteriaDescription | string | Yes | — | — | | settings.manualQualityScores.score | number | Yes | — | — | | settings.manualQualityScores.weight | number | Yes | — | — | | settings.status | string | No | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | settings.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | settings.assignmentSourceName | string | No | — | Source name of the assignment | | settings.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | settings.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | settings.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | settings.isAnalysisOnly | boolean | No | — | For Warehouse Native Constraints: nullable | | settings.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | settings.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | settings.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | settings.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | settings.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | settings.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | settings.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | settings.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | settings.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | settings.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | settings.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | settings.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | settings.analysisEndTime | string | No | — | Warehouse Native only - end time for analysis only experiments | | settings.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | settings.assignmentSourceFilters.column | string | No | — | Column to filter on. | | settings.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | settings.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | settings.analyticsType | string | No | — | The mode of analysis for the experiment, e.g frequentist, bayesian, sprt Allowed values: frequentist, bayesian, sprt | | settings.defaultSPRTPowerParam | number | No | — | SPRT power parameter percentage used as the default for experiment analysis. Constraints: format: double | | settings.defaultSPRTMDE | number | No | — | Default MDE value for every metric if one isn't provided. Only used in manual mode. Constraints: format: double | | settings.sprtBaselineMode | string | No | — | In manual mode, mde/mean/stdDev must be provided for every metric in the experiment. In in_experiment_control, only the mde is needed for every metric, or the defaultSPRTMDE field must be passed. Allowed values: manual, in_experiment_control | | settings.sprtMDESettings | object[] | No | — | The SPRT values for use in the experiment. | | settings.sprtMDESettings.metricKey | string | Yes | — | — | | settings.sprtMDESettings.groupSettings | object[] | Yes | — | — | | settings.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | settings.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | settings.sprtMDESettings.groupSettings.mean | number | No | — | — | | settings.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | settings.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | settings.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | settings.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | settings.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | settings.sidecarURLFilters.value | string | Yes | — | — | | settings.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | settings.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | settings.decisionReason | string | No | — | Experiment notes reported after experiment completes | | settings.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | settings.preComputedUserDimensions.propertySource | string | No | — | — | | settings.preComputedUserDimensions.name | string | Yes | — | — | | settings.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | settings.cureCovariates.name | string | Yes | — | — | | settings.cureCovariates.type | string | Yes | — | — | | settings.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | settings.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | settings.stratifiedSampling.metric | object | No | — | — | | settings.stratifiedSampling.metric.name | string | Yes | — | — | | settings.stratifiedSampling.metric.type | string | No | — | — | | settings.stratifiedSampling.metric.startDate | string | Yes | — | — | | settings.stratifiedSampling.metric.endDate | string | Yes | — | — | | settings.stratifiedSampling.entityPropertySource | object | No | — | — | | settings.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | settings.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | settings.stratifiedSampling.csv | object | No | — | — | | settings.stratifiedSampling.csv.original | string | Yes | — | — | | settings.stratifiedSampling.csv.identifier | string | Yes | — | — | | settings.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | settings.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | settings.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | settings.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | settings.enabledNonProdEnvironments | string[] | No | — | — | | settings.groups | object[] | No | — | — | | settings.groups.name | string | Yes | — | — | | settings.groups.id | string | No | — | Constraints: nullable | | settings.groups.size | number | No | — | Constraints: min: 0, max: 100 | | settings.groups.parameterValues | object | No | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | settings.groups.disabled | boolean | No | — | — | | settings.groups.description | string | No | — | — | | settings.groups.foreignGroupID | string | No | — | — | | settings.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | ## Response (application/json) **201** — The created experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/reviews" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/reviews", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/reviews", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete a Single Experiment Override URL: https://docs.statsig.com/api-reference/experiments/delete-a-single-experiment-override ================================================================================ # Delete a Single Experiment Override ## Delete a Single Experiment Override **DELETE** `/console/v1/experiments/{id}/overrides/conditional/{type}/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}` Delete a Single Experiment Override Removes a single gate or segment override from the experiment. Idempotent: returns 200 even when no matching override exists. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Experiment name | | type (path) | string | Yes | — | Override type Allowed values: gate, segment | | name (path) | string | Yes | — | Name of the gate or segment being overridden | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | groupID (query) | string | Yes | — | The experiment group name the override targets | | environment (query) | string | No | — | Environment the override is scoped to. Omit to target the override that applies to all environments. | ## Response (application/json) **200** — Delete Single Experiment Override Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Test" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "remove_just_this_id" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment or group not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides/conditional/{type}/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete a Single Experiment User ID Override URL: https://docs.statsig.com/api-reference/experiments/delete-a-single-experiment-user-id-override ================================================================================ # Delete a Single Experiment User ID Override ## Delete a Single Experiment User ID Override **DELETE** `/console/v1/experiments/{id}/overrides/userID/{userID}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}` Delete a Single Experiment User ID Override Removes a single user ID from the matching userID override bucket on the experiment. Idempotent: returns 200 even when the user ID is not currently overridden. Only clears the bucket named by `groupID`, `unitType`, and `environment`; every other override bucket stays in place. The response body carries the full override set for the experiment after the delete. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | Experiment name | | userID (path) | string | Yes | — | User ID to remove from the override | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | groupID (query) | string | Yes | Control | The experiment group name the override targets | | unitType (query) | string | No | — | The unit type of the override. Defaults to the experiment unit type when omitted. | | environment (query) | string | No | — | Environment the override is scoped to. Omit to target the override that applies to all environments. | ## Response (application/json) **200** — Delete Single Experiment User ID Override Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "message": "Experiment Overrides updated successfully.", "data": { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Test", "environment": null } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "user_a" ], "environment": null, "unitType": "userID" }, { "groupID": "Control", "ids": [ "user_b" ], "environment": "staging", "unitType": "userID" }, { "groupID": "Test", "ids": [ "user_c" ], "environment": null, "unitType": "userID" } ] } } ``` **400** — `groupID` is missing. The `errors` array names the parameter that failed validation. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Bad Request Exception" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment or group not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides/userID/{userID}?groupID=Control") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Experiment URL: https://docs.statsig.com/api-reference/experiments/delete-experiment ================================================================================ # Delete Experiment ## Delete Experiment **DELETE** `/console/v1/experiments/{id}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}` Delete Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "Experiment deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The entity remains intact until the existing review workflow applies the deletion. Returns the review ID and status. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Experiment Overrides URL: https://docs.statsig.com/api-reference/experiments/delete-experiment-overrides ================================================================================ # Delete Experiment Overrides ## Delete Experiment Overrides **DELETE** `/console/v1/experiments/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides` Delete Experiment Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Delete Update Experiment Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Test" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "remove_just_this_id" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Disable Experiment Groups URL: https://docs.statsig.com/api-reference/experiments/disable-experiment-groups ================================================================================ # Disable Experiment Groups ## Disable Experiment Groups **POST** `/console/v1/experiments/{id}/disable_groups` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/disable_groups` Disable Experiment Groups ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | group_names | string[] | Yes | — | — | ## Response (application/json) **201** — Disable experiment groups | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "string", "data": { "reviewSettings": { "requiredReview": true, "allowedReviewers": [ { "id": "string", "name": "string", "email": "string" } ] }, "activeReview": { "reviewID": "string", "reviewStatus": "string", "description": "string" }, "id": "string", "name": "string", "idType": "string", "description": "string", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "string" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "secondaryIDType": "string", "identifierMappingMode": "strictOneToOne", "identityResolutionSource": "string", "hypothesis": "string", "links": [ { "url": "https://example.com", "title": "string" } ], "externalEvents": [ { "name": "string", "timestamp": 0 } ], "groups": [ { "name": "string", "id": "string", "size": 0, "parameterValues": {}, "disabled": true, "description": "string", "foreignGroupID": "string", "highlighted": true, "isControl": true, "shipped": true, "images": [ "string" ], "foreignGroupIDVerified": true } ], "controlGroupID": "string", "allocation": 0, "userBuckets": [ 0 ], "primaryMetricTags": [ "string" ], "secondaryMetricTags": [ "string" ], "primaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "secondaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "otherMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "duration": 1, "targetExposures": 1, "targetingGateID": "string", "sequentialTesting": true, "bonferroniCorrection": true, "bonferroniCorrectionPerMetric": true, "benjaminiHochbergPerVariant": true, "benjaminiHochbergPerMetric": true, "benjaminiPrimaryMetricsOnly": true, "defaultConfidenceInterval": "80", "defaultRollupWindow": 0, "defaultChanceToBeatThreshold": 0, "bayesianPriors": [ { "metric": { "name": "string", "type": "string" }, "priorMean": 0, "priorStdDev": 0 } ], "manualQualityScores": [ { "criteriaName": "HYPOTHESIS_LENGTH", "status": "PASSED", "criteriaDescription": "string", "score": 0, "weight": 0 } ], "status": "active", "launchedGroupID": "string", "assignmentSourceName": "string", "assignmentSourceExperimentName": "string", "isAnalysisOnly": true, "allocationDuration": 1, "cohortedAnalysisDuration": 1, "cohortedMetricsMatureAfterEnd": true, "cohortWaitUntilEndToInclude": true, "fixedAnalysisDuration": 1, "scheduledReloadHour": 0, "scheduledReloadType": "full", "scheduledReloadDays": [ 0 ], "turboMode": true, "autoLoadToplineImpact": true, "analysisEndTime": "string", "assignmentSourceFilters": [ { "column": "string", "condition": "in", "values": [ "string" ] } ], "analyticsType": "string", "defaultSPRTPowerParam": 0, "defaultSPRTMDE": 0, "sprtBaselineMode": "manual", "sprtMDESettings": [ { "metricKey": "string", "groupSettings": [ { "groupKey": "string", "mde": 0, "mean": 0, "stdDev": 0 } ] } ], "isSidecar": true, "sidecarEditorURL": "string", "sidecarURLFilters": [ { "type": "contains", "value": "string" } ], "sidecarDisableAutoRun": true, "sidecarPrerunScript": "string", "decisionReason": "string", "preComputedUserDimensions": [ { "propertySource": "string", "name": "string" } ], "cureCovariates": [ { "name": "string", "type": "string" } ], "stratifiedSampling": { "status": "pending", "metric": { "name": "string", "type": "string", "startDate": "string", "endDate": "string" }, "entityPropertySource": { "propertySourceName": "string", "column": "string" }, "csv": { "original": "string", "identifier": "string" }, "useStratifiedSalt": true, "useUnits": true, "deltaReduction": 0, "spreadReduction": 0 }, "enabledNonProdEnvironments": [ "string" ], "subtype": "conversion", "externalExperimentName": "string", "rolloutPhaseData": [ { "percentage": 0, "time": 0, "timeString": "string", "isComplete": true, "phaseDurationMs": 0 } ], "rolloutGroupID": "string", "rolloutPercentage": 0, "preRolloutSnapshotID": "string", "salt": "string", "scheduledStartTime": 0, "scheduledStopTime": 0, "scheduledStopActionType": "pause", "restartReason": "string", "originalTargetDuration": 0, "wasAutoDisabled": true, "isPromptExperiment": true, "isTemplate": true, "allowOverridesInPulse": true, "excludePausedExposuresAndEvents": true, "defaultImpactMultiplier": 0, "bonferroniPrimaryMetricWeight": 0, "defaultSPRTTestDelta": 0, "defaultSPRTControlDelta": 0, "isImpactBankEnabled": true, "originalTargetExposures": 0, "reviewsRequiredLocally": true, "isHistoricalCloudExperiment": true, "originalScheduledReloadHour": 0, "layerID": "string", "startTime": 0, "endTime": 0, "decisionTime": 0, "healthChecks": [ { "name": "string", "description": "string", "status": "PASSED", "metadata": { "type": "string", "lastPulseLoadTime": 0, "crossoverPercent": 0, "p_value": 0, "assignmentSourceID": "string", "assignmentSourceName": "string", "foreignExperimentID": "string", "deduplication_rate": 0, "deduplication_rates": [ { "group_id": "string", "rate": 0, "group_name": "string" } ], "primary_id_type": "string", "secondary_id_type": "string", "missingMetrics": [ "string" ], "metrics": [ { "metric_name": "string", "earliest_date": "2024-01-01T00:00:00Z", "latest_date": "2024-01-01T00:00:00Z" } ], "lastUpdatedDs": "string", "groups": [ { "groupID": "string", "groupName": "string", "status": "PASSED", "metrics": [ { "metricKey": null, "metricTitle": null, "status": "PASSED" } ] } ], "groupBucketInfo": [ { "groupID": "string", "averageBucketSize": 0 } ] }, "type": "has_checks" } ], "healthCheckStatus": "PASSED", "experimentType": "BASE", "isStale": true, "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "inlineTargetingRulesJSON": "string", "inlineTargetingRules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 } } ], "qualityScore": { "score": 0, "breakdown": [ { "criterion": "string", "status": "PASSED", "passingDescription": "string", "score": 0, "weight": 0 } ] }, "summarySections": [ { "name": "string", "content": "string" } ], "permalink": "https://example.com", "shipWithHoldout": { "holdoutPercent": 10, "shippedGroupID": "string", "shippedGroupName": "string", "shippedWithHoldoutTime": 0, "expectedDuration": 0 }, "powerAnalyses": [ { "id": "string", "name": "string", "status": "pending", "isPrimary": true } ], "geotestData": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ "string" ], "excludedFromTreatment": [ "string" ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ "string" ] } ] }, "geotestDesignSets": [ { "id": "string", "name": "string", "state": "loading", "creatorName": "string", "createdTime": 0, "parameters": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ "string" ], "excludedFromTreatment": [ "string" ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ "string" ] } ] }, "designOptions": [ { "power": 0, "cost": 0, "percentPerGroup": [ 0 ], "geosInGroup": [ [ "string" ] ], "unusedGeos": [ "string" ], "duration": 0, "effect_size": 0, "avg_scaled_l2_imbalance": 0, "avg_att": 0, "average_mde": 0, "abs_lift_in_zero": 0, "proportion_total_Y": 0, "holdout": 0, "rank": 0, "correlation": 0 } ] } ], "gridSearchData": { "desiredTargetGroups": 0, "parameters": [ { "name": "string", "type": "string", "baseline": "string", "values": [ "string" ] } ], "exclusions": [ {} ], "bucketMapping": {}, "dropMapping": {} } } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/disable_groups" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/disable_groups", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/disable_groups", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/disable_groups"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/disable_groups", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/disable_groups")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/disable_groups") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Edit Experiment Review URL: https://docs.statsig.com/api-reference/experiments/edit-experiment-review ================================================================================ # Edit Experiment Review ## Edit Experiment Review **PUT** `/console/v1/experiments/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}` Edit Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | No | — | New description. Omit to keep the current value. Constraints: min length: 1, max length: 2000 | | reviewer_ids | string[] | No | — | Replacement reviewer user IDs. Omit to keep the current set. | | reviewer_group_ids | string[] | No | — | Replacement reviewer group IDs. Omit to keep the current set. | ## Response (application/json) **200** — The updated experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Edit Scheduled Experiment Stop URL: https://docs.statsig.com/api-reference/experiments/edit-scheduled-experiment-stop ================================================================================ # Edit Scheduled Experiment Stop ## Edit Scheduled Experiment Stop **POST** `/console/v1/experiments/{id}/edit_scheduled_stop` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop` Edit Scheduled Experiment Stop ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | scheduledTime | integer | No | — | Unix timestamp (in milliseconds) at which to stop the experiment Constraints: format: int64 | | actionType | string | No | — | `pause` stops new assignments (Stop New Assignments). `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Allowed values: pause, stop | ## Response (application/json) **200** — Edit Scheduled Experiment Stop Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Successfully edited scheduled experiment stop" } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/edit_scheduled_stop") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Enable Experiment Groups URL: https://docs.statsig.com/api-reference/experiments/enable-experiment-groups ================================================================================ # Enable Experiment Groups ## Enable Experiment Groups **POST** `/console/v1/experiments/{id}/enable_groups` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/enable_groups` Enable Experiment Groups ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | group_names | string[] | Yes | — | — | ## Response (application/json) **201** — Enable experiment groups | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "string", "data": { "reviewSettings": { "requiredReview": true, "allowedReviewers": [ { "id": "string", "name": "string", "email": "string" } ] }, "activeReview": { "reviewID": "string", "reviewStatus": "string", "description": "string" }, "id": "string", "name": "string", "idType": "string", "description": "string", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "string" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "secondaryIDType": "string", "identifierMappingMode": "strictOneToOne", "identityResolutionSource": "string", "hypothesis": "string", "links": [ { "url": "https://example.com", "title": "string" } ], "externalEvents": [ { "name": "string", "timestamp": 0 } ], "groups": [ { "name": "string", "id": "string", "size": 0, "parameterValues": {}, "disabled": true, "description": "string", "foreignGroupID": "string", "highlighted": true, "isControl": true, "shipped": true, "images": [ "string" ], "foreignGroupIDVerified": true } ], "controlGroupID": "string", "allocation": 0, "userBuckets": [ 0 ], "primaryMetricTags": [ "string" ], "secondaryMetricTags": [ "string" ], "primaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "secondaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "otherMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "duration": 1, "targetExposures": 1, "targetingGateID": "string", "sequentialTesting": true, "bonferroniCorrection": true, "bonferroniCorrectionPerMetric": true, "benjaminiHochbergPerVariant": true, "benjaminiHochbergPerMetric": true, "benjaminiPrimaryMetricsOnly": true, "defaultConfidenceInterval": "80", "defaultRollupWindow": 0, "defaultChanceToBeatThreshold": 0, "bayesianPriors": [ { "metric": { "name": "string", "type": "string" }, "priorMean": 0, "priorStdDev": 0 } ], "manualQualityScores": [ { "criteriaName": "HYPOTHESIS_LENGTH", "status": "PASSED", "criteriaDescription": "string", "score": 0, "weight": 0 } ], "status": "active", "launchedGroupID": "string", "assignmentSourceName": "string", "assignmentSourceExperimentName": "string", "isAnalysisOnly": true, "allocationDuration": 1, "cohortedAnalysisDuration": 1, "cohortedMetricsMatureAfterEnd": true, "cohortWaitUntilEndToInclude": true, "fixedAnalysisDuration": 1, "scheduledReloadHour": 0, "scheduledReloadType": "full", "scheduledReloadDays": [ 0 ], "turboMode": true, "autoLoadToplineImpact": true, "analysisEndTime": "string", "assignmentSourceFilters": [ { "column": "string", "condition": "in", "values": [ "string" ] } ], "analyticsType": "string", "defaultSPRTPowerParam": 0, "defaultSPRTMDE": 0, "sprtBaselineMode": "manual", "sprtMDESettings": [ { "metricKey": "string", "groupSettings": [ { "groupKey": "string", "mde": 0, "mean": 0, "stdDev": 0 } ] } ], "isSidecar": true, "sidecarEditorURL": "string", "sidecarURLFilters": [ { "type": "contains", "value": "string" } ], "sidecarDisableAutoRun": true, "sidecarPrerunScript": "string", "decisionReason": "string", "preComputedUserDimensions": [ { "propertySource": "string", "name": "string" } ], "cureCovariates": [ { "name": "string", "type": "string" } ], "stratifiedSampling": { "status": "pending", "metric": { "name": "string", "type": "string", "startDate": "string", "endDate": "string" }, "entityPropertySource": { "propertySourceName": "string", "column": "string" }, "csv": { "original": "string", "identifier": "string" }, "useStratifiedSalt": true, "useUnits": true, "deltaReduction": 0, "spreadReduction": 0 }, "enabledNonProdEnvironments": [ "string" ], "subtype": "conversion", "externalExperimentName": "string", "rolloutPhaseData": [ { "percentage": 0, "time": 0, "timeString": "string", "isComplete": true, "phaseDurationMs": 0 } ], "rolloutGroupID": "string", "rolloutPercentage": 0, "preRolloutSnapshotID": "string", "salt": "string", "scheduledStartTime": 0, "scheduledStopTime": 0, "scheduledStopActionType": "pause", "restartReason": "string", "originalTargetDuration": 0, "wasAutoDisabled": true, "isPromptExperiment": true, "isTemplate": true, "allowOverridesInPulse": true, "excludePausedExposuresAndEvents": true, "defaultImpactMultiplier": 0, "bonferroniPrimaryMetricWeight": 0, "defaultSPRTTestDelta": 0, "defaultSPRTControlDelta": 0, "isImpactBankEnabled": true, "originalTargetExposures": 0, "reviewsRequiredLocally": true, "isHistoricalCloudExperiment": true, "originalScheduledReloadHour": 0, "layerID": "string", "startTime": 0, "endTime": 0, "decisionTime": 0, "healthChecks": [ { "name": "string", "description": "string", "status": "PASSED", "metadata": { "type": "string", "lastPulseLoadTime": 0, "crossoverPercent": 0, "p_value": 0, "assignmentSourceID": "string", "assignmentSourceName": "string", "foreignExperimentID": "string", "deduplication_rate": 0, "deduplication_rates": [ { "group_id": "string", "rate": 0, "group_name": "string" } ], "primary_id_type": "string", "secondary_id_type": "string", "missingMetrics": [ "string" ], "metrics": [ { "metric_name": "string", "earliest_date": "2024-01-01T00:00:00Z", "latest_date": "2024-01-01T00:00:00Z" } ], "lastUpdatedDs": "string", "groups": [ { "groupID": "string", "groupName": "string", "status": "PASSED", "metrics": [ { "metricKey": null, "metricTitle": null, "status": "PASSED" } ] } ], "groupBucketInfo": [ { "groupID": "string", "averageBucketSize": 0 } ] }, "type": "has_checks" } ], "healthCheckStatus": "PASSED", "experimentType": "BASE", "isStale": true, "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "inlineTargetingRulesJSON": "string", "inlineTargetingRules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 } } ], "qualityScore": { "score": 0, "breakdown": [ { "criterion": "string", "status": "PASSED", "passingDescription": "string", "score": 0, "weight": 0 } ] }, "summarySections": [ { "name": "string", "content": "string" } ], "permalink": "https://example.com", "shipWithHoldout": { "holdoutPercent": 10, "shippedGroupID": "string", "shippedGroupName": "string", "shippedWithHoldoutTime": 0, "expectedDuration": 0 }, "powerAnalyses": [ { "id": "string", "name": "string", "status": "pending", "isPrimary": true } ], "geotestData": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ "string" ], "excludedFromTreatment": [ "string" ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ "string" ] } ] }, "geotestDesignSets": [ { "id": "string", "name": "string", "state": "loading", "creatorName": "string", "createdTime": 0, "parameters": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ "string" ], "excludedFromTreatment": [ "string" ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ "string" ] } ] }, "designOptions": [ { "power": 0, "cost": 0, "percentPerGroup": [ 0 ], "geosInGroup": [ [ "string" ] ], "unusedGeos": [ "string" ], "duration": 0, "effect_size": 0, "avg_scaled_l2_imbalance": 0, "avg_att": 0, "average_mde": 0, "abs_lift_in_zero": 0, "proportion_total_Y": 0, "holdout": 0, "rank": 0, "correlation": 0 } ] } ], "gridSearchData": { "desiredTargetGroups": 0, "parameters": [ { "name": "string", "type": "string", "baseline": "string", "values": [ "string" ] } ], "exclusions": [ {} ], "bucketMapping": {}, "dropMapping": {} } } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/enable_groups" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/enable_groups", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/enable_groups", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/enable_groups"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/enable_groups", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/enable_groups")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/enable_groups") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Finish Experiment Early URL: https://docs.statsig.com/api-reference/experiments/finish-experiment-early ================================================================================ # Finish Experiment Early ## Finish Experiment Early **PUT** `/console/v1/experiments/{id}/make_decision` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/make_decision` Finish Experiment Early ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id | string | Yes | groupid123 | The ID of the group to launch | | decisionReason | string | Yes | Your reason for stopping early | The reason for making the decision to update the experiment status | | removeTargeting | boolean | No | false | Indicates whether to remove targeting from the experiment | | holdout | integer | No | 10 | Integer percentage of users to hold back when shipping with holdback. Must be an integer between 0 and 50 (inclusive): the launched group size is computed as 100 - holdout * 2, so values above 50 would produce a negative-sized launched group. When set, the experiment remains live with a holdback group so long-term impact can be measured before making a final decision. Requires the ship_experiment_with_holdout gate to be enabled for the project. Constraints: format: int64, min: 0, max: 50 | ## Response (application/json) **200** — Make Experiment Decision Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Decision made for Experiment." } ``` **400** — Experiment has not yet started | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/make_decision" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }' ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/make_decision", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/make_decision", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/make_decision"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "id": "experiment123", "decisionReason": "Your reason for stopping early", "removeTargeting": false }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}") req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/make_decision", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/make_decision")) .method("PUT", HttpRequest.BodyPublishers.ofString("{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/make_decision") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"id\":\"experiment123\",\"decisionReason\":\"Your reason for stopping early\",\"removeTargeting\":false}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Fully Update Experiment URL: https://docs.statsig.com/api-reference/experiments/fully-update-experiment ================================================================================ # Fully Update Experiment ## Fully Update Experiment **POST** `/console/v1/experiments/{id}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}` Fully Update Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | idType | string | Yes | — | The type of ID which the experiment is based on | | secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | hypothesis | string | Yes | — | A statement that will be tested by this experiment | | links | object[] | No | — | Links to relevant documentation or resources | | links.url | string | Yes | — | The URL of the link Constraints: format: uri | | links.title | string | No | — | The title of the link | | externalEvents | object[] | No | — | — | | externalEvents.name | string | Yes | — | — | | externalEvents.timestamp | number | Yes | — | — | | groups | object[] | Yes | — | The test groups for your experiment | | groups.name | string | Yes | — | — | | groups.id | string | No | — | Constraints: nullable | | groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | groups.disabled | boolean | No | — | — | | groups.description | string | No | — | — | | groups.foreignGroupID | string | No | — | — | | groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | controlGroupID | string | No | — | Optional control group ID | | allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | userBuckets | number[] | No | — | — | | primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | primaryMetrics | object[] | No | — | Main metrics needed to evaluate your hypothesis | | primaryMetrics.name | string | Yes | — | The metric name. | | primaryMetrics.type | string | Yes | — | The metric type. | | primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | secondaryMetrics | object[] | No | — | Additional metrics to monitor that might impact the analysis or final decision of the experiment | | secondaryMetrics.name | string | Yes | — | The metric name. | | secondaryMetrics.type | string | Yes | — | The metric type. | | secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | otherMetrics.name | string | Yes | — | The metric name. | | otherMetrics.type | string | Yes | — | The metric type. | | otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | tags | string[] | No | — | Tags associated with the experiment | | duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | inlineTargetingRules | object[] | No | [{"name":"Eligible users","passPercentage":100,"conditions":[{"type":"passes_segment","targetValue":"paid_users"}]}] | Replaces inline targeting with these rules. Conditions in a rule use AND; rules use ordered evaluation. Set to `[]` to remove targeting. Omit on update to keep existing targeting. Providing this field switches from gate to inline targeting; you can't also set a nonempty `targetingGateID`. Use `passes_segment`, `fails_segment`, `passes_gate`, or `fails_gate` with the segment or gate name ID as `targetValue`. | | inlineTargetingRules.name | string | Yes | — | The name of this rule. | | inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | sequentialTesting | boolean | No | — | Apply sequential testing? | | bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | bayesianPriors.metric | object | Yes | — | — | | bayesianPriors.metric.name | string | Yes | — | — | | bayesianPriors.metric.type | string | Yes | — | — | | bayesianPriors.priorMean | number | Yes | — | — | | bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | manualQualityScores.criteriaDescription | string | Yes | — | — | | manualQualityScores.score | number | Yes | — | — | | manualQualityScores.weight | number | Yes | — | — | | status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | assignmentSourceName | string | No | — | Source name of the assignment | | assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | isAnalysisOnly | boolean | No | — | For Warehouse Native Constraints: nullable | | team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | analysisEndTime | string | No | — | Warehouse Native only - end time for analysis only experiments | | assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | assignmentSourceFilters.column | string | No | — | Column to filter on. | | assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | analyticsType | string | No | — | The mode of analysis for the experiment, e.g frequentist, bayesian, sprt Allowed values: frequentist, bayesian, sprt | | defaultSPRTPowerParam | number | No | — | SPRT power parameter percentage used as the default for experiment analysis. Constraints: format: double | | defaultSPRTMDE | number | No | — | Default MDE value for every metric if one isn't provided. Only used in manual mode. Constraints: format: double | | sprtBaselineMode | string | No | — | In manual mode, mde/mean/stdDev must be provided for every metric in the experiment. In in_experiment_control, only the mde is needed for every metric, or the defaultSPRTMDE field must be passed. Allowed values: manual, in_experiment_control | | sprtMDESettings | object[] | No | — | The SPRT values for use in the experiment. | | sprtMDESettings.metricKey | string | Yes | — | — | | sprtMDESettings.groupSettings | object[] | Yes | — | — | | sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | sprtMDESettings.groupSettings.mde | number | Yes | — | — | | sprtMDESettings.groupSettings.mean | number | No | — | — | | sprtMDESettings.groupSettings.stdDev | number | No | — | — | | isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | sidecarURLFilters.value | string | Yes | — | — | | sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | decisionReason | string | No | — | Experiment notes reported after experiment completes | | preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | preComputedUserDimensions.propertySource | string | No | — | — | | preComputedUserDimensions.name | string | Yes | — | — | | cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | cureCovariates.name | string | Yes | — | — | | cureCovariates.type | string | Yes | — | — | | stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | stratifiedSampling.metric | object | No | — | — | | stratifiedSampling.metric.name | string | Yes | — | — | | stratifiedSampling.metric.type | string | No | — | — | | stratifiedSampling.metric.startDate | string | Yes | — | — | | stratifiedSampling.metric.endDate | string | Yes | — | — | | stratifiedSampling.entityPropertySource | object | No | — | — | | stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | stratifiedSampling.csv | object | No | — | — | | stratifiedSampling.csv.original | string | Yes | — | — | | stratifiedSampling.csv.identifier | string | Yes | — | — | | stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | enabledNonProdEnvironments | string[] | No | — | — | ## Response (application/json) **200** — Fully Update Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "string", "data": { "id": "a_experiment", "description": "a helpful summary of what this experiment does", "lastModifierName": "CONSOLE API", "lastModifierID": "f0JAV9dd7KF0sUbi1DHWB", "idType": "userID", "status": "setup", "layerID": "layer1", "hypothesis": "Does 1 or 0 work better?", "primaryMetrics": [ { "name": "l14", "type": "user" } ], "primaryMetricTags": [], "secondaryMetrics": [ { "name": "mau_28d", "type": "user" } ], "secondaryMetricTags": [], "groups": [ { "name": "group1", "size": 50, "parameterValues": { "key": 1 } }, { "name": "gruop2", "size": 50, "parameterValues": { "key": 0 } } ], "allocation": 50.46, "duration": 14, "targetingGateID": "a_gate", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "tags": [] } } ``` **400** — Name is already in use | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Eligible Reviewers URL: https://docs.statsig.com/api-reference/experiments/get-eligible-reviewers ================================================================================ # Get Eligible Reviewers ## Get Eligible Reviewers **GET** `/console/v1/experiments/{id}/eligible_reviewers` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers` Get Eligible Reviewers ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Users and groups eligible to review changes to this experiment. `everyone_eligible` is true when no specific reviewers are configured. `users` is the flattened, deduped union of individual reviewers and all group members; `groups` lists each eligible group with its member `user_ids`. Project admins can always review and are not enumerated. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.everyone_eligible | boolean | Yes | — | — | | data.users | object[] | Yes | — | — | | data.users.id | string | Yes | — | — | | data.users.email | string | Yes | — | — | | data.users.name | string | Yes | — | — | | data.groups | object[] | Yes | — | — | | data.groups.id | string | Yes | — | — | | data.groups.name | string | Yes | — | — | | data.groups.user_ids | string[] | Yes | — | — | ```json { "data": { "everyone_eligible": false, "users": [ { "id": "user_abc", "email": "alice@example.com", "name": "Alice Example" } ], "groups": [ { "id": "group_xyz", "name": "Growth", "user_ids": [ "user_abc" ] } ] }, "message": "Successfully retrieved eligible reviewers" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/eligible_reviewers") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Experiment URL: https://docs.statsig.com/api-reference/experiments/get-experiment ================================================================================ # Get Experiment ## Get Experiment **GET** `/console/v1/experiments/{id}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}` Get Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fields (query) | string[] | No | — | Comma-separated list of top-level fields to return (sparse fieldset), e.g. `id,name,hypothesis,groups`. `id` is always included. Reduces response size; when omitted the full experiment is returned. | ## Response (application/json) **200** — Get Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "Experiments listed successfully.", "data": { "id": "a_experiment", "permalink": "https://console.statsig.com/company_id/experiments/a_experiment", "description": "", "lastModifiedTime": 1707427635442, "lastModifierEmail": null, "createdTime": 1707427634717, "creatorName": "CONSOLE API", "lastModifierName": "CONSOLE API", "lastModifierID": "4FKF0sUbi1D7xZFW5vcHWB", "idType": "userID", "status": "setup", "experimentType": "BASE", "launchedGroupID": null, "layerID": "statsig::a_experiment_layer", "hypothesis": "", "primaryMetrics": [], "primaryMetricTags": [], "secondaryMetrics": [], "secondaryMetricTags": [], "startTime": null, "endTime": null, "decisionTime": null, "groups": [ { "name": "Control", "id": "4HbgLdfqlIeN3sHkyMG1qC", "size": 50, "parameterValues": {}, "isControl": true }, { "name": "Test", "size": 50, "parameterValues": {}, "isControl": false } ], "allocation": 100, "duration": 14, "targetingGateID": "", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "tags": [ "* Core" ], "decisionReason": "", "owner": { "ownerType": "USER", "ownerName": "Test User" }, "healthCheckStatus": "PASSED", "isStale": false, "inlineTargetingRulesJSON": "{}", "powerAnalyses": [ { "id": "experiment_data_report_id", "name": "My Power Analysis", "status": "ready", "isPrimary": true } ] } } ``` **400** — Invalid field(s) requested. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Experiment Context URL: https://docs.statsig.com/api-reference/experiments/get-experiment-context ================================================================================ # Get Experiment Context ## Get Experiment Context **GET** `/console/v1/experiments/{id}/context` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/context` Get Experiment Context ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get Experiment Context Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.experimentID | string | Yes | — | The experiment ID | | data.context | string | Yes | — | AI-ready experiment context | ```json { "message": "string", "data": { "experimentID": "string", "context": "string" } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/context" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/context", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/context", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/context"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/context", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/context")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/context") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Experiment Guardrail Alert Statuses URL: https://docs.statsig.com/api-reference/experiments/get-experiment-guardrail-alert-statuses ================================================================================ # Get Experiment Guardrail Alert Statuses ## Get Experiment Guardrail Alert Statuses **GET** `/console/v1/experiments/{id}/alerts` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/alerts` Get Experiment Guardrail Alert Statuses ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Experiment guardrail alert statuses fetched successfully | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.alerts | object | Yes | — | Alert status keyed by encoded metric id | ```json { "message": "string", "data": { "alerts": {} } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/alerts" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/alerts", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/alerts", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/alerts"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/alerts", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/alerts")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/alerts") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Experiment Overrides URL: https://docs.statsig.com/api-reference/experiments/get-experiment-overrides ================================================================================ # Get Experiment Overrides ## Get Experiment Overrides **GET** `/console/v1/experiments/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides` Get Experiment Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get Experiment Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "message": "Experiment Overrides read successfully.", "data": { "overrides": [ { "groupID": "Control", "name": "a_gate", "type": "gate" }, { "groupID": "test", "name": "a_segment", "type": "segment" } ], "userIDOverrides": [ { "ids": [ "updated_id_list" ], "groupID": "Control" }, { "ids": [ "updated_id_lists" ], "groupID": "Test" } ] } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Experiment Review URL: https://docs.statsig.com/api-reference/experiments/get-experiment-review ================================================================================ # Get Experiment Review ## Get Experiment Review **GET** `/console/v1/experiments/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}` Get Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — The requested experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Experiment Reviews URL: https://docs.statsig.com/api-reference/experiments/list-experiment-reviews ================================================================================ # List Experiment Reviews ## List Experiment Reviews **GET** `/console/v1/experiments/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews` List Experiment Reviews ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — A page of the experiment reviews, newest first. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Experiment Versions URL: https://docs.statsig.com/api-reference/experiments/list-experiment-versions ================================================================================ # List Experiment Versions ## List Experiment Versions **GET** `/console/v1/experiments/{id}/versions` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/versions` List Experiment Versions ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | | startDate (query) | string | No | 2024-01-01 | Only return versions last modified on or after this date. Expected valid date in the form of YYYY-MM-DD | | endDate (query) | string | No | 2024-01-31 | Only return versions last modified on or before this date, inclusive. Expected valid date in the form of YYYY-MM-DD | ## Response (application/json) **200** — List Experiment Versions Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "reviewSettings": { "requiredReview": true, "allowedReviewers": [ { "id": "string", "name": "string", "email": "string" } ] }, "activeReview": { "reviewID": "string", "reviewStatus": "string", "description": "string" }, "id": "string", "name": "string", "idType": "string", "description": "string", "lastModifierID": "string", "lastModifiedTime": 0, "lastModifierEmail": "string", "lastModifierName": "string", "creatorID": "string", "createdTime": 0, "creatorName": "string", "creatorEmail": "string", "tags": [ "string" ], "targetApps": "string", "holdoutIDs": [ "string" ], "team": "string", "teamID": "string", "version": 0, "secondaryIDType": "string", "identifierMappingMode": "strictOneToOne", "identityResolutionSource": "string", "hypothesis": "string", "links": [ { "url": "https://example.com", "title": "string" } ], "externalEvents": [ { "name": "string", "timestamp": 0 } ], "groups": [ { "name": "string", "id": "string", "size": 0, "parameterValues": {}, "disabled": true, "description": "string", "foreignGroupID": "string", "highlighted": true, "isControl": true, "shipped": true, "images": [ "string" ], "foreignGroupIDVerified": true } ], "controlGroupID": "string", "allocation": 0, "userBuckets": [ 0 ], "primaryMetricTags": [ "string" ], "secondaryMetricTags": [ "string" ], "primaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "secondaryMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "otherMetrics": [ { "name": "string", "type": "string", "direction": "increase", "hypothesizedValue": 0 } ], "duration": 1, "targetExposures": 1, "targetingGateID": "string", "sequentialTesting": true, "bonferroniCorrection": true, "bonferroniCorrectionPerMetric": true, "benjaminiHochbergPerVariant": true, "benjaminiHochbergPerMetric": true, "benjaminiPrimaryMetricsOnly": true, "defaultConfidenceInterval": "80", "defaultRollupWindow": 0, "defaultChanceToBeatThreshold": 0, "bayesianPriors": [ { "metric": { "name": "string", "type": "string" }, "priorMean": 0, "priorStdDev": 0 } ], "manualQualityScores": [ { "criteriaName": "HYPOTHESIS_LENGTH", "status": "PASSED", "criteriaDescription": "string", "score": 0, "weight": 0 } ], "status": "active", "launchedGroupID": "string", "assignmentSourceName": "string", "assignmentSourceExperimentName": "string", "isAnalysisOnly": true, "allocationDuration": 1, "cohortedAnalysisDuration": 1, "cohortedMetricsMatureAfterEnd": true, "cohortWaitUntilEndToInclude": true, "fixedAnalysisDuration": 1, "scheduledReloadHour": 0, "scheduledReloadType": "full", "scheduledReloadDays": [ 0 ], "turboMode": true, "autoLoadToplineImpact": true, "analysisEndTime": "string", "assignmentSourceFilters": [ { "column": "string", "condition": "in", "values": [ "string" ] } ], "analyticsType": "string", "defaultSPRTPowerParam": 0, "defaultSPRTMDE": 0, "sprtBaselineMode": "manual", "sprtMDESettings": [ { "metricKey": "string", "groupSettings": [ { "groupKey": "string", "mde": 0, "mean": 0, "stdDev": 0 } ] } ], "isSidecar": true, "sidecarEditorURL": "string", "sidecarURLFilters": [ { "type": "contains", "value": "string" } ], "sidecarDisableAutoRun": true, "sidecarPrerunScript": "string", "decisionReason": "string", "preComputedUserDimensions": [ { "propertySource": "string", "name": "string" } ], "cureCovariates": [ { "name": "string", "type": "string" } ], "stratifiedSampling": { "status": "pending", "metric": { "name": "string", "type": "string", "startDate": "string", "endDate": "string" }, "entityPropertySource": { "propertySourceName": "string", "column": "string" }, "csv": { "original": "string", "identifier": "string" }, "useStratifiedSalt": true, "useUnits": true, "deltaReduction": 0, "spreadReduction": 0 }, "enabledNonProdEnvironments": [ "string" ], "subtype": "conversion", "externalExperimentName": "string", "rolloutPhaseData": [ { "percentage": 0, "time": 0, "timeString": "string", "isComplete": true, "phaseDurationMs": 0 } ], "rolloutGroupID": "string", "rolloutPercentage": 0, "preRolloutSnapshotID": "string", "salt": "string", "scheduledStartTime": 0, "scheduledStopTime": 0, "scheduledStopActionType": "pause", "restartReason": "string", "originalTargetDuration": 0, "wasAutoDisabled": true, "isPromptExperiment": true, "isTemplate": true, "allowOverridesInPulse": true, "excludePausedExposuresAndEvents": true, "defaultImpactMultiplier": 0, "bonferroniPrimaryMetricWeight": 0, "defaultSPRTTestDelta": 0, "defaultSPRTControlDelta": 0, "isImpactBankEnabled": true, "originalTargetExposures": 0, "reviewsRequiredLocally": true, "isHistoricalCloudExperiment": true, "originalScheduledReloadHour": 0, "layerID": "string", "startTime": 0, "endTime": 0, "decisionTime": 0, "healthChecks": [ { "name": "string", "description": "string", "status": "PASSED", "metadata": { "type": "string", "lastPulseLoadTime": 0, "crossoverPercent": 0, "p_value": 0, "assignmentSourceID": "string", "assignmentSourceName": "string", "foreignExperimentID": "string", "deduplication_rate": 0, "deduplication_rates": [ { "group_id": "string", "rate": 0, "group_name": "string" } ], "primary_id_type": "string", "secondary_id_type": "string", "missingMetrics": [ "string" ], "metrics": [ { "metric_name": "string", "earliest_date": "2024-01-01T00:00:00Z", "latest_date": "2024-01-01T00:00:00Z" } ], "lastUpdatedDs": "string", "groups": [ { "groupID": "string", "groupName": "string", "status": "PASSED", "metrics": [ null ] } ], "groupBucketInfo": [ { "groupID": "string", "averageBucketSize": 0 } ] }, "type": "has_checks" } ], "healthCheckStatus": "PASSED", "experimentType": "BASE", "isStale": true, "owner": { "ownerID": "user123", "ownerType": "USER", "ownerName": "John Doe", "ownerEmail": "owner123@test.com" }, "inlineTargetingRulesJSON": "string", "inlineTargetingRules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ "string" ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 } } ], "qualityScore": { "score": 0, "breakdown": [ { "criterion": "string", "status": "PASSED", "passingDescription": "string", "score": 0, "weight": 0 } ] }, "summarySections": [ { "name": "string", "content": "string" } ], "permalink": "https://example.com", "shipWithHoldout": { "holdoutPercent": 10, "shippedGroupID": "string", "shippedGroupName": "string", "shippedWithHoldoutTime": 0, "expectedDuration": 0 }, "powerAnalyses": [ { "id": "string", "name": "string", "status": "pending", "isPrimary": true } ], "geotestData": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ "string" ], "excludedFromTreatment": [ "string" ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ "string" ] } ] }, "geotestDesignSets": [ { "id": "string", "name": "string", "state": "loading", "creatorName": "string", "createdTime": 0, "parameters": { "geoIDType": "string", "treatmentStartDS": "string", "treatmentEndDS": "string", "preTreatmentDuration": 0, "expectedEffectSize": 0, "oneSidedDirection": "increase", "alpha": 0, "model": "None", "method": "conformal", "budgeting": { "totalBudget": 0, "incrementalCost": 0 }, "conformalGridSize": 0, "includeFixedEffects": true, "conformalType": "iid", "iidResamples": 0, "domainSet": [ "string" ], "designStartDS": "string", "designEndDS": "string", "groups": [ { "name": "string", "includedInTreatment": [ null ], "excludedFromTreatment": [ null ] } ], "treatmentGeoNumMin": 0, "treatmentGeoNumMax": 0, "rollingLookbackWindows": 0, "includeCorrelations": true, "dynamicTimeWarping": 0, "controlShareBounds": { "lowerBound": 0, "upperBound": 0 }, "finalGroups": [ { "name": "string", "geos": [ null ] } ] }, "designOptions": [ { "power": 0, "cost": 0, "percentPerGroup": [ 0 ], "geosInGroup": [ [ null ] ], "unusedGeos": [ "string" ], "duration": 0, "effect_size": 0, "avg_scaled_l2_imbalance": 0, "avg_att": 0, "average_mde": 0, "abs_lift_in_zero": 0, "proportion_total_Y": 0, "holdout": 0, "rank": 0, "correlation": 0 } ] } ], "gridSearchData": { "desiredTargetGroups": 0, "parameters": [ { "name": "string", "type": "string", "baseline": "string", "values": [ "string" ] } ], "exclusions": [ {} ], "bucketMapping": {}, "dropMapping": {} } } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/versions?limit=10&page=1&startDate=2024-01-01&endDate=2024-01-31") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Experiments URL: https://docs.statsig.com/api-reference/experiments/list-experiments ================================================================================ # List Experiments ## List Experiments **GET** `/console/v1/experiments` Full URL: `https://statsigapi.net/console/v1/experiments` List Experiments ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | layerID (query) | string | No | — | Which layer to place the experiment into. | | idType (query) | string | No | — | The idType the experiment will be performed on | | teamID (query) | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | status (query) | oneOf | No | — | The current status of the experiment Constraints: string, string[] | | targetAppID (query) | string | No | — | — | | stale (query) | boolean | No | — | When true, only returns stale experiments. If omitted or false, returns all experiments. | | createdStartDate (query) | string | No | 2024-01-01 | Expected valid date in the form of YYYY-MM-DD | | createdEndDate (query) | string | No | 2024-01-01 | Expected valid date in the form of YYYY-MM-DD | | experimentType (query) | oneOf | No | — | Filter by experiment type Constraints: string, string[] | | ids (query) | string[] | No | — | Fetch a specific set of experiments by ID in a single request (comma-separated, max 100). Only experiments matching these IDs are returned; unknown IDs are omitted. For more than 100, split into batches of 100. Combine with `fields` to fetch trimmed details for several experiments at once. | | fields (query) | string[] | No | — | Comma-separated list of top-level fields to return (sparse fieldset), e.g. `id,name,hypothesis,groups`. `id` is always included. Reduces response size; when omitted the full experiment is returned. | | creatorName (query) | string | No | — | Name of the creator. Constraints: nullable | | creatorID (query) | string | No | — | ID of the user who created the entity. Constraints: nullable | | tags (query) | oneOf | No | — | Filter by tags Constraints: string, string[] | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Experiments Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Experiments listed successfully.", "data": [ { "id": "a_experiment", "permalink": "https://console.statsig.com/company_id/experiments/a_experiment", "name": "a_experiment", "description": "description", "idType": "userID", "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifiedTime": 1707427635442, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "1vaQaBoLlkauH9iiuOSBP2", "createdTime": 1707427634717, "creatorName": "CONSOLE API", "creatorEmail": null, "targetApps": [], "holdoutIDs": [], "tags": [], "status": "setup", "experimentType": "BASE", "launchedGroupID": null, "startTime": null, "endTime": null, "layerID": null, "hypothesis": "This will be a good feature :)", "primaryMetrics": [ { "name": "d1_retention_rate", "type": "user" } ], "primaryMetricTags": [], "secondaryMetrics": [], "secondaryMetricTags": [], "groups": [ { "name": "Control", "id": "6sEQvUd4c6E55V6ljBYMeJ", "size": 50, "parameterValues": { "assigned_group": "control" }, "description": "", "isControl": true }, { "name": "Test", "id": "6sEQvVS6EoNzpkEgUJUpxL", "size": 50, "parameterValues": { "assigned_group": "test" }, "description": "", "isControl": false } ], "allocation": 100, "duration": 14, "targetingGateID": "", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "decisionReason": null, "decisionTime": null, "healthChecks": [], "owner": { "ownerType": "USER", "ownerName": "Test User" }, "inlineTargetingRulesJSON": "{}", "healthCheckStatus": "PASSED", "isStale": false, "powerAnalyses": [] }, { "id": "b_experiment", "permalink": "https://console.statsig.com/company_id/experiments/b_experiment", "name": "b experiment", "description": "", "idType": "userID", "inlineTargetingRulesJSON": "{}", "lastModifierID": "68ztZp2v2nFc81RAsvuvj4", "lastModifiedTime": 1706744900374, "lastModifierName": "jacob O'Quinn", "lastModifierEmail": "jacob@statsig.com", "creatorID": "68ztZp2v2nFc81RAsvuvj4", "createdTime": 1678394676162, "creatorName": "jacob O'Quinn", "creatorEmail": "jacob@statsig.com", "targetApps": [], "holdoutIDs": [], "tags": [ "customTag", "asdf" ], "status": "archived", "experimentType": "BASE", "launchedGroupID": null, "startTime": null, "endTime": null, "layerID": null, "hypothesis": "", "primaryMetrics": [], "primaryMetricTags": [], "secondaryMetrics": [], "secondaryMetricTags": [ "★ Core" ], "groups": [ { "name": "Control", "id": "7dCnwm0by2laSOcBNKIL8r", "size": 50, "parameterValues": { "control": "control value" }, "description": "", "isControl": true }, { "name": "Test", "id": "7dCnwnFe0kuFcdKxoSEort", "size": 50, "parameterValues": { "control": "test value" }, "description": "", "isControl": false } ], "allocation": 100, "duration": 14, "targetingGateID": "targeting_gate_to_select_users", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "decisionReason": null, "decisionTime": null, "healthCheckStatus": "WAITING", "healthChecks": [ { "name": "Checks not yet detected", "status": "WAITING", "description": "This experiment has not recorded any exposure checks in production yet." }, { "name": "Valid unit type not yet verified", "status": "WAITING", "description": "Exposure checks for this experiment are pending evaluation. This experiment requires exposure checks with unit IDs of type userID" }, { "name": "Event metric data not yet verified", "status": "WAITING", "description": "This experiment has recorded no event metric with a valid unit ID yet, or these event metrics are pending evaluation. If you are importing events, this may take up to a day to reflect. This experiment requires metrics with unit IDs of type userID" }, { "name": "Pulse metrics not yet available", "status": "WAITING", "description": "Expect to see your Pulse Results within 24 hours. Statsig computes Pulse results on a daily basis." }, { "name": "Exposure balance not yet verified", "status": "WAITING", "description": "Exposure balance for this experiment is pending evaluation. As the experiment records more exposures, Statsig will continue to evaluate experiment exposure balance." } ], "isStale": false, "powerAnalyses": [] } ] } ``` **400** — Invalid field(s) requested. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments?createdStartDate=2024-01-01&createdEndDate=2024-01-01&limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Partially Update Experiment URL: https://docs.statsig.com/api-reference/experiments/partially-update-experiment ================================================================================ # Partially Update Experiment ## Partially Update Experiment **PATCH** `/console/v1/experiments/{id}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}` Partially Update Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | description | string | No | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | idType | string | No | — | The type of ID which the experiment is based on | | secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | hypothesis | string | No | — | A statement that will be tested by this experiment | | links | object[] | No | — | Links to relevant documentation or resources | | links.url | string | Yes | — | The URL of the link Constraints: format: uri | | links.title | string | No | — | The title of the link | | externalEvents | object[] | No | — | — | | externalEvents.name | string | Yes | — | — | | externalEvents.timestamp | number | Yes | — | — | | groups | object[] | No | — | The test groups for your experiment | | groups.name | string | Yes | — | — | | groups.id | string | No | — | Constraints: nullable | | groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | groups.disabled | boolean | No | — | — | | groups.description | string | No | — | — | | groups.foreignGroupID | string | No | — | — | | groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | controlGroupID | string | No | — | Optional control group ID | | allocation | number | No | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | userBuckets | number[] | No | — | — | | primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | primaryMetrics | object[] | No | — | Main metrics needed to evaluate your hypothesis | | primaryMetrics.name | string | Yes | — | The metric name. | | primaryMetrics.type | string | Yes | — | The metric type. | | primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | secondaryMetrics | object[] | No | — | Additional metrics to monitor that might impact the analysis or final decision of the experiment | | secondaryMetrics.name | string | Yes | — | The metric name. | | secondaryMetrics.type | string | Yes | — | The metric type. | | secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | otherMetrics.name | string | Yes | — | The metric name. | | otherMetrics.type | string | Yes | — | The metric type. | | otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | tags | string[] | No | — | Tags associated with the experiment | | duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | targetingGateID | string | No | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | inlineTargetingRules | object[] | No | [{"name":"Eligible users","passPercentage":100,"conditions":[{"type":"passes_segment","targetValue":"paid_users"}]}] | Replaces inline targeting with these rules. Conditions in a rule use AND; rules use ordered evaluation. Set to `[]` to remove targeting. Omit on update to keep existing targeting. Providing this field switches from gate to inline targeting; you can't also set a nonempty `targetingGateID`. Use `passes_segment`, `fails_segment`, `passes_gate`, or `fails_gate` with the segment or gate name ID as `targetValue`. | | inlineTargetingRules.name | string | Yes | — | The name of this rule. | | inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | sequentialTesting | boolean | No | — | Apply sequential testing? | | bonferroniCorrection | boolean | No | — | Is Bonferroni correction applied per variant? | | bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | defaultConfidenceInterval | string | No | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | bayesianPriors.metric | object | Yes | — | — | | bayesianPriors.metric.name | string | Yes | — | — | | bayesianPriors.metric.type | string | Yes | — | — | | bayesianPriors.priorMean | number | Yes | — | — | | bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | manualQualityScores.criteriaDescription | string | Yes | — | — | | manualQualityScores.score | number | Yes | — | — | | manualQualityScores.weight | number | Yes | — | — | | status | string | No | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | assignmentSourceName | string | No | — | Source name of the assignment | | assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | isAnalysisOnly | boolean | No | — | For Warehouse Native Constraints: nullable | | team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | analysisEndTime | string | No | — | Warehouse Native only - end time for analysis only experiments | | assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | assignmentSourceFilters.column | string | No | — | Column to filter on. | | assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | analyticsType | string | No | — | The mode of analysis for the experiment, e.g frequentist, bayesian, sprt Allowed values: frequentist, bayesian, sprt | | defaultSPRTPowerParam | number | No | — | SPRT power parameter percentage used as the default for experiment analysis. Constraints: format: double | | defaultSPRTMDE | number | No | — | Default MDE value for every metric if one isn't provided. Only used in manual mode. Constraints: format: double | | sprtBaselineMode | string | No | — | In manual mode, mde/mean/stdDev must be provided for every metric in the experiment. In in_experiment_control, only the mde is needed for every metric, or the defaultSPRTMDE field must be passed. Allowed values: manual, in_experiment_control | | sprtMDESettings | object[] | No | — | The SPRT values for use in the experiment. | | sprtMDESettings.metricKey | string | Yes | — | — | | sprtMDESettings.groupSettings | object[] | Yes | — | — | | sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | sprtMDESettings.groupSettings.mde | number | Yes | — | — | | sprtMDESettings.groupSettings.mean | number | No | — | — | | sprtMDESettings.groupSettings.stdDev | number | No | — | — | | isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | sidecarURLFilters.value | string | Yes | — | — | | sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | decisionReason | string | No | — | Experiment notes reported after experiment completes | | preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | preComputedUserDimensions.propertySource | string | No | — | — | | preComputedUserDimensions.name | string | Yes | — | — | | cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | cureCovariates.name | string | Yes | — | — | | cureCovariates.type | string | Yes | — | — | | stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | stratifiedSampling.metric | object | No | — | — | | stratifiedSampling.metric.name | string | Yes | — | — | | stratifiedSampling.metric.type | string | No | — | — | | stratifiedSampling.metric.startDate | string | Yes | — | — | | stratifiedSampling.metric.endDate | string | Yes | — | — | | stratifiedSampling.entityPropertySource | object | No | — | — | | stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | stratifiedSampling.csv | object | No | — | — | | stratifiedSampling.csv.original | string | Yes | — | — | | stratifiedSampling.csv.identifier | string | Yes | — | — | | stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | enabledNonProdEnvironments | string[] | No | — | — | ## Response (application/json) **200** — Partially Update Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "string", "data": { "id": "a_experiment", "description": "a helpful summary of what this experiment does", "lastModifierName": "CONSOLE API", "lastModifierID": "f0JAV9dd7KF0sUbi1DHWB", "idType": "userID", "status": "setup", "layerID": "layer1", "hypothesis": "Does 1 or 0 work better?", "primaryMetrics": [ { "name": "l14", "type": "user" } ], "primaryMetricTags": [], "secondaryMetrics": [ { "name": "mau_28d", "type": "user" } ], "secondaryMetricTags": [], "groups": [ { "name": "group1", "size": 50, "parameterValues": { "key": 1 } }, { "name": "gruop2", "size": 50, "parameterValues": { "key": 0 } } ], "allocation": 50.46, "duration": 14, "targetingGateID": "a_gate", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "tags": [] } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/experiments/{id}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/experiments/{id}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/experiments/{id}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Partially Update Experiment Overrides URL: https://docs.statsig.com/api-reference/experiments/partially-update-experiment-overrides ================================================================================ # Partially Update Experiment Overrides ## Partially Update Experiment Overrides **PATCH** `/console/v1/experiments/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides` Partially Update Experiment Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | overrides.type | string | Yes | — | Allowed values: gate, segment | | overrides.id | string | Yes | — | The id of the segment or gate | | overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ## Response (application/json) **200** — Partially Update Experiment Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "gate", "id": "a_gate", "groupID": "Test" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "newly_added_id" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/experiments/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/experiments/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/experiments/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Reject Experiment Review URL: https://docs.statsig.com/api-reference/experiments/reject-experiment-review ================================================================================ # Reject Experiment Review ## Reject Experiment Review **PUT** `/console/v1/experiments/{id}/reviews/{reviewID}/reject` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject` Reject Experiment Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | Yes | — | Required reason for rejecting the review. Constraints: min length: 1, max length: 2000 | ## Response (application/json) **200** — The rejected experiment review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change this review would apply, as `{ current, proposed }` over exactly the fields committing the review would write. `current` is the live value read at request time; where commit treats an unset argument as "leave unchanged", `proposed` repeats the live value rather than a default. Populated on single-review responses only — list responses omit it so a page of reviews does not pay an extra read per row. When the review does propose something but it could not be read back, `content` is PRESENT with `unavailable_reason` set and both value objects empty, never `null` — so "this type proposes nothing" stays distinguishable from "we cannot tell you what this would do". This surface's reasons are `review_data_unavailable` (the stored change data is missing or does not match the type the review declares; expected on legacy rows) and `content_unreadable` (the data is present but the before/after could not be assembled; a logged server-side fault). `null` when the review type is a bare action with no recoverable proposed value: `stop`, `pause`, `restart`, `reallocate`, `delete`, `disable_reviews_locally` (always), `start` (unless the review carries a backdated start date that commit will actually write — analysis-only experiments on warehouse-native projects — or a scheduled stop), `scheduled_start_edit` when `new_time` is `ignore` (commit is a no-op), `scheduled_stop_edit` when `new_time` is `ignore` and no action type is set (commit is a no-op), `scheduled_stop`/`scheduled_stop_edit` on an autotune, and `update_settings` on an autotune (the stored settings have no experiment-contract shape). Every other type carries content, including `archive`, `unarchive`, `update_owners`, `update_team`, `change_enabled_groups` and `update_allowed_reviewers`, for which the Console currently shows no before/after. Keys by type: `archive`/`unarchive` -> `archived`, `allocation` (archiving a layer-bound experiment zeroes its allocation); `abandon` -> `decision_note_title`, `decision_reason`; `start` -> `start_time` for a backdated start, and `stop_time`, `stop_action_type` when a stop is scheduled with the start (`current` is the pending scheduled stop it replaces); `scheduled_start`/`scheduled_start_edit` -> `start_time`; `scheduled_stop`/`scheduled_stop_edit` -> `stop_time`, `stop_action_type` (`pause` stops new assignments, `stop` concludes the experiment and defers the decision; `current` is the pending scheduled stop, both `null` when none is pending; cancelling proposes both `null`); `set_schedule` -> `start_time` when a start is set, and `stop_time`, `stop_action_type` when a stop is set (an omitted side is left out; an omitted stop field repeats the pending value); `null` on an autotune when a stop is included; `rollout` -> `group_id`, `rollout_percentage`, `rollout_phases`, `has_upcoming_automated_rollout`; `schedule_rollout` -> `group_id`, `rollout_phases`; `make_decision` -> `winning_group_id`, `decision_note_title`, `decision_reason`, and on experiments `overrides`, `id_overrides`, `inline_targeting_rules_json`, `targeting_gate_id`; `update_overrides` -> `overrides`, `id_overrides`, `allow_overrides_in_pulse`; `update_target_applications` -> `target_app_ids`; `update_default_impact_multiplier` -> `default_impact_multiplier`; `update_owners` -> `owners`; `update_team` -> `team_id`, `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids` (moving to a team whose approval mode is `admin_only`/`team_only` widens who may approve future reviews); `update_allowed_reviewers` -> `allowed_reviewer_user_ids`, `allowed_reviewer_group_ids`; `change_enabled_groups` -> `groups` (the full list, with the delta applied); `update_settings` -> a single `settings` object holding the full resolved settings set, including `overrides`, `idOverrides`, `allowOverridesInPulse` and `customScorecardSections`. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: start, stop, pause, restart, abandon, archive, delete, make_decision, update_settings, update_overrides, update_target_applications, update_allowed_reviewers, update_default_impact_multiplier, scheduled_start, scheduled_start_edit, scheduled_stop, scheduled_stop_edit, set_schedule, disable_reviews_locally, rollout, schedule_rollout, reallocate, change_enabled_groups, unarchive, update_owners, update_team | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `review_data_unavailable`: the review's stored change data is missing, or does not match the type the review declares — expected on legacy rows. `content_unreadable`: the data is present but the before/after could not be assembled; that is a server-side fault and is logged. Allowed values: review_data_unavailable, content_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "start", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "start", "current": {}, "proposed": {}, "unavailable_reason": "review_data_unavailable" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reviews/{reviewID}/reject") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Reset Experiment URL: https://docs.statsig.com/api-reference/experiments/reset-experiment ================================================================================ # Reset Experiment ## Reset Experiment **PUT** `/console/v1/experiments/{id}/reset` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/reset` Reset Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Reset Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully restarted." } ``` **400** — Experiment has not yet started | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/reset" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/reset", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/reset", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/reset"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/reset", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/reset")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/reset") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Resolve Metric Rollout Alert URL: https://docs.statsig.com/api-reference/experiments/resolve-metric-rollout-alert ================================================================================ # Resolve Metric Rollout Alert ## Resolve Metric Rollout Alert **POST** `/console/v1/experiments/{id}/alerts/{metricId}/resolve` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve` Resolve Metric Rollout Alert ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | | metricId (path) | string | Yes | — | metric id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reasoning | string | No | Issue has been addressed | Reason for resolving the alert | ## Response (application/json) **200** — Metric rollout alert resolved successfully | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.resolvedAt | number | No | 1718630400 | Timestamp when alert was resolved Constraints: format: double | ```json { "message": "string", "data": { "resolvedAt": 1718630400 } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/alerts/{metricId}/resolve") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Restart As New Experiment URL: https://docs.statsig.com/api-reference/experiments/restart-as-new-experiment ================================================================================ # Restart As New Experiment ## Restart As New Experiment **POST** `/console/v1/experiments/{id}/restart_as_new` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/restart_as_new` Restart As New Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | The experiment display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | ## Response (application/json) **200** — Restart As New Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The display name of the experiment Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\- ]*$ | | data.idType | string | Yes | — | — | | data.description | string | Yes | — | A helpful summary of what this experiment does Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | The Statsig ID of the creator of this experiment Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | The email of the creator of this experiment Constraints: nullable | | data.tags | string[] | Yes | — | — | | data.targetApps | oneOf | No | — | Target apps assigned to this experiment Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | The team name associated with the experiment, Enterprise only. Constraints: nullable | | data.teamID | string | No | — | The team ID associated with the experiment, Enterprise only. Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.secondaryIDType | string | No | — | The secondary ID type for the experiment used in WHN for ID resolution Constraints: nullable | | data.identifierMappingMode | string | No | — | The identifier mapping mode for the experiment used in WHN for ID resolution Allowed values: strictOneToOne, firstTouchOneToMany, lastTouchOneToMany | | data.identityResolutionSource | string | No | — | The identity resolution entity property source for the experiment used in WHN for ID resolution Constraints: nullable | | data.hypothesis | string | Yes | — | A statement that will be tested by this experiment | | data.links | object[] | No | — | Links to relevant documentation or resources | | data.links.url | string | Yes | — | The URL of the link Constraints: format: uri | | data.links.title | string | No | — | The title of the link | | data.externalEvents | object[] | No | — | — | | data.externalEvents.name | string | Yes | — | — | | data.externalEvents.timestamp | number | Yes | — | — | | data.groups | object[] | Yes | — | The test groups for your experiment | | data.groups.name | string | Yes | — | — | | data.groups.id | string | No | — | Constraints: nullable | | data.groups.size | number | Yes | — | Constraints: min: 0, max: 100 | | data.groups.parameterValues | object | Yes | — | A map of parameter name to the value this group serves. Sidecar (Visual Editor) experiments also return `sidecarURLFilters`, `sidecarDisableAutoRun`, `sidecarPrerunScript`, and `sidecarExperimentName` here, copied from the experiment itself on read. Sending them here does nothing; set them as experiment fields instead. | | data.groups.disabled | boolean | No | — | — | | data.groups.description | string | No | — | — | | data.groups.foreignGroupID | string | No | — | — | | data.groups.highlighted | boolean | No | — | Marks this experiment group as highlighted in analysis views. Highlighted groups are prioritized (shown first) and can be used to filter. | | data.groups.isControl | boolean | No | — | Whether this group is the experiment's control. Derived from the experiment's `controlGroupID`, so it is always consistent with the `controlGroupID` returned alongside it. Read-only: to change the control group, set `controlGroupID` on the experiment. | | data.groups.shipped | boolean | No | — | Whether this group is the one that was shipped. Derived from the experiment's `launchedGroupID`, so it is always consistent with the `launchedGroupID` returned alongside it. Read-only. | | data.groups.images | string[] | No | — | Names of images attached to this group. | | data.groups.foreignGroupIDVerified | boolean | No | — | Whether `foreignGroupID` has been verified against the external system. Read-only. Constraints: nullable | | data.controlGroupID | string | No | — | Optional control group ID | | data.allocation | number | Yes | — | Percent of layer allocated to this experiment Constraints: format: double, min: 0, max: 100 | | data.userBuckets | number[] | No | — | — | | data.primaryMetricTags | string[] | No | — | Primary metric tags for the experiment | | data.secondaryMetricTags | string[] | No | — | Secondary metric tags for the experiment | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.name | string | Yes | — | The metric name. | | data.primaryMetrics.type | string | Yes | — | The metric type. | | data.primaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.primaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.name | string | Yes | — | The metric name. | | data.secondaryMetrics.type | string | Yes | — | The metric type. | | data.secondaryMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.secondaryMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.otherMetrics | object[] | No | — | Additional metrics you want to investigate or learn from. The usual corrections applied to Primary and Secondary metrics are not applied to these. | | data.otherMetrics.name | string | Yes | — | The metric name. | | data.otherMetrics.type | string | Yes | — | The metric type. | | data.otherMetrics.direction | string | No | — | The expected direction for one-sided testing (a feature to only measure metric movements in a single direction) Allowed values: increase, decrease | | data.otherMetrics.hypothesizedValue | number | No | — | The comparison value for the one-sample testing (a feature to use a fixed baseline as the control value) | | data.duration | integer | No | — | Expected length of the experiment in days. Create and update accept `duration` or `targetExposures`, not both. On update, sending `duration` clears a stored `targetExposures`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetExposures | integer | No | — | Exposure count that ends the experiment. On update, sending `targetExposures` clears a stored `duration`. Omit the field to keep the stored value. `null` is not accepted. Constraints: format: int64, min: 1 | | data.targetingGateID | string | Yes | — | Restrict your experiment to users passing the selected feature gate Constraints: nullable | | data.sequentialTesting | boolean | No | — | Apply sequential testing? | | data.bonferroniCorrection | boolean | Yes | — | Is Bonferroni correction applied per variant? | | data.bonferroniCorrectionPerMetric | boolean | No | — | Is Bonferroni correction applied per metric? | | data.benjaminiHochbergPerVariant | boolean | No | — | Is Benjamini-Hochberg procedure applied per variant? | | data.benjaminiHochbergPerMetric | boolean | No | — | Is Benjamini-Hochberg procedure applied per metric? | | data.benjaminiPrimaryMetricsOnly | boolean | No | — | Is Benjamini-Hochberg procedure applied for primary metrics only? | | data.defaultConfidenceInterval | string | Yes | — | Default error margin used for results Allowed values: 80, 90, 95, 98, 99 | | data.defaultRollupWindow | integer | No | — | Default rollup window in days for experiment results. Use -1 for cumulative. Only -1, 1, and 7 allowed for cloud experiments. Constraints: format: int64 | | data.defaultChanceToBeatThreshold | number | No | — | Default chance-to-beat threshold used for Bayesian results. Constraints: format: double | | data.bayesianPriors | object[] | No | — | Bayesian prior settings by metric. | | data.bayesianPriors.metric | object | Yes | — | — | | data.bayesianPriors.metric.name | string | Yes | — | — | | data.bayesianPriors.metric.type | string | Yes | — | — | | data.bayesianPriors.priorMean | number | Yes | — | — | | data.bayesianPriors.priorStdDev | number | Yes | — | Constraints: min: 0 | | data.manualQualityScores | object[] | No | — | Up to 10 manually set quality scores for an experiment. The scores and weights will be added to the existing weights and scores, and then weights will be renormalized to 100. This can be set via the Statsig Console API. If targeting a default check, the weight of the check will be updated, but not the status or description. A default score can be removed by setting the weight to 0. The default score identifiers are one of: HYPOTHESIS_LENGTH, BALANCED_EXPOSURE, PRIMARY_METRICS_LENGTH, COMPARISON_CORRECTION, GUARDRAIL_METRIC_TAGS, SUFFICIENT_SAMPLE, POWER_ANALYSIS, SEQUENTIAL_TESTING | | data.manualQualityScores.criteriaName | oneOf | Yes | — | Constraints: string | | data.manualQualityScores.status | string | Yes | — | Allowed values: PASSED, FAILED, WARNING | | data.manualQualityScores.criteriaDescription | string | Yes | — | — | | data.manualQualityScores.score | number | Yes | — | — | | data.manualQualityScores.weight | number | Yes | — | — | | data.status | string | Yes | — | The current status of the experiment Allowed values: active, setup, decision_made, abandoned, archived, experiment_stopped, assignment_stopped | | data.launchedGroupID | string | No | — | ID of the launched group, null otherwise Constraints: nullable | | data.assignmentSourceName | string | No | — | — | | data.assignmentSourceExperimentName | string | No | — | Name of the source experiment for assignment | | data.isAnalysisOnly | boolean | No | — | — | | data.allocationDuration | integer | No | — | Warehouse Native Only - Allocation duration in days Constraints: format: int64, nullable, min: 1 | | data.cohortedAnalysisDuration | integer | No | — | Warehouse Native Only - Cohorted analysis duration in days Constraints: format: int64, min: 1 | | data.cohortedMetricsMatureAfterEnd | boolean | No | — | Warehouse Native Only - Allow cohort metrics to mature after experiment end | | data.cohortWaitUntilEndToInclude | boolean | No | — | Warehouse Native Only - Whether to filter to units whose experiment cohort analysis duration is complete, if cohortedAnalysisDuration exists | | data.fixedAnalysisDuration | integer | No | — | Fixed analysis duration in days Constraints: format: int64, min: 1 | | data.scheduledReloadHour | integer | No | — | Warehouse Native only - UTC hour at which to run scheduled pulse loads Constraints: format: int64, nullable, min: 0, max: 23 | | data.scheduledReloadType | string | No | — | Warehouse Native only - reload type for scheduled reloads Allowed values: full, incremental | | data.scheduledReloadDays | integer[] | No | — | Warehouse Native only - days on which to run scheduled reloads from 0 to 6, 0 meaning Sunday. Null to run reloads on all days. Constraints: nullable | | data.turboMode | boolean | No | — | Warehouse Native only - whether to run scheduled reloads with Turbo mode. | | data.autoLoadToplineImpact | boolean | No | — | Warehouse Native only - whether to automatically run topline and projected launch impact calculations when reloading experiments. | | data.analysisEndTime | string | No | — | — | | data.assignmentSourceFilters | object[] | No | — | Array of criteria for filtering assignment sources. | | data.assignmentSourceFilters.column | string | No | — | Column to filter on. | | data.assignmentSourceFilters.condition | string | Yes | — | Allowed values: in, not_in, =, >, <, >=, <=, is_null, non_null, contains, not_contains, sql_filter, starts_with, ends_with, after_exposure, before_exposure, is_true, is_false | | data.assignmentSourceFilters.values | string[] | No | — | Optional array of values for the criterion to match against. | | data.analyticsType | string | No | — | Constraints: nullable | | data.defaultSPRTPowerParam | number | No | — | Constraints: format: double | | data.defaultSPRTMDE | number | No | — | Constraints: format: double | | data.sprtBaselineMode | string | No | — | Allowed values: manual, in_experiment_control | | data.sprtMDESettings | object[] | No | — | — | | data.sprtMDESettings.metricKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings | object[] | Yes | — | — | | data.sprtMDESettings.groupSettings.groupKey | string | Yes | — | — | | data.sprtMDESettings.groupSettings.mde | number | Yes | — | — | | data.sprtMDESettings.groupSettings.mean | number | No | — | — | | data.sprtMDESettings.groupSettings.stdDev | number | No | — | — | | data.isSidecar | boolean | No | — | Whether this is a Statsig Sidecar experiment. `sidecarEditorURL`, `sidecarURLFilters`, `sidecarDisableAutoRun`, and `sidecarPrerunScript` are saved only when this is `true`. | | data.sidecarEditorURL | string | No | — | Sidecar (Visual Editor) only: the URL of the page being modified. The Visual Editor cannot open without it, and it must be an `http` or `https` URL. | | data.sidecarURLFilters | object[] | No | — | Sidecar (Visual Editor) only: filters on the current URL used to determine whether the experiment should be applied. Each entry looks like `{ "type": "contains", "value": "/pricing" }`, where `type` is `contains`, `equals`, `regex`, or `path`. Put `type` inside each filter object, not alongside the array. | | data.sidecarURLFilters.type | string | Yes | — | Allowed values: contains, equals, regex, path | | data.sidecarURLFilters.value | string | Yes | — | — | | data.sidecarDisableAutoRun | boolean | No | — | Sidecar (Visual Editor) only: whether to disable auto-running the experiment on page load. By default the experiment auto runs. | | data.sidecarPrerunScript | string | No | — | Sidecar (Visual Editor) only: a script to run before the experiment starts. Send `null` to clear it. Constraints: nullable | | data.decisionReason | string | Yes | — | Constraints: nullable | | data.preComputedUserDimensions | object[] | No | — | User dimensions that will be computed for every metric in WHN | | data.preComputedUserDimensions.propertySource | string | No | — | — | | data.preComputedUserDimensions.name | string | Yes | — | — | | data.cureCovariates | object[] | No | — | CURE Covariates to use in this experiment | | data.cureCovariates.name | string | Yes | — | — | | data.cureCovariates.type | string | Yes | — | — | | data.stratifiedSampling | object | No | — | The stratified sampling settings for the experiment Constraints: nullable | | data.stratifiedSampling.status | string | Yes | — | Allowed values: pending, success, error | | data.stratifiedSampling.metric | object | No | — | — | | data.stratifiedSampling.metric.name | string | Yes | — | — | | data.stratifiedSampling.metric.type | string | No | — | — | | data.stratifiedSampling.metric.startDate | string | Yes | — | — | | data.stratifiedSampling.metric.endDate | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource | object | No | — | — | | data.stratifiedSampling.entityPropertySource.propertySourceName | string | Yes | — | — | | data.stratifiedSampling.entityPropertySource.column | string | Yes | — | — | | data.stratifiedSampling.csv | object | No | — | — | | data.stratifiedSampling.csv.original | string | Yes | — | — | | data.stratifiedSampling.csv.identifier | string | Yes | — | — | | data.stratifiedSampling.useStratifiedSalt | boolean | No | — | Whether successful stratified sampling is currently used for experiment assignment. | | data.stratifiedSampling.useUnits | boolean | No | — | Whether stratified sampling was configured to use allocated units directly. | | data.stratifiedSampling.deltaReduction | number | No | — | Observed reduction in delta after running stratified sampling. Constraints: format: double | | data.stratifiedSampling.spreadReduction | number | No | — | Observed reduction in spread after running stratified sampling. Constraints: format: double | | data.enabledNonProdEnvironments | string[] | No | — | — | | data.subtype | string | No | — | Allowed values: conversion, reactivation, retention | | data.externalExperimentName | string | No | — | — | | data.rolloutPhaseData | object[] | No | — | Saved gradual-rollout phases. Read-only; configure rollout phases in the Console. | | data.rolloutPhaseData.percentage | number | Yes | — | Target rollout percentage for this phase. | | data.rolloutPhaseData.time | number | No | — | Scheduled phase time in Unix milliseconds. | | data.rolloutPhaseData.timeString | string | No | — | Display label for the phase time. | | data.rolloutPhaseData.isComplete | boolean | Yes | — | Whether this phase has completed. | | data.rolloutPhaseData.phaseDurationMs | number | No | — | Duration before the next progressive rollout phase can start, in milliseconds. | | data.rolloutGroupID | string | No | — | ID of the group being rolled out. Omitted when no rollout group is saved. | | data.rolloutPercentage | number | No | — | Saved rollout percentage for the selected group. Constraints: format: double | | data.preRolloutSnapshotID | string | No | — | Experiment snapshot ID saved before the rollout started. | | data.salt | string | No | — | The salt used to bucket units for this experiment. Read-only; needed to reproduce assignment outside Statsig. | | data.scheduledStartTime | number | No | — | Epoch millis at which the experiment is scheduled to start, if a start has been scheduled via `POST /experiments/{id}/schedule_start`. Constraints: format: double | | data.scheduledStopTime | number | No | — | Epoch millis at which a pending scheduled stop will run. Omitted when no stop is scheduled. Constraints: format: double | | data.scheduledStopActionType | string | No | — | What the pending scheduled stop does: `pause` stops new assignments (Stop New Assignments); `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Omitted when no stop is scheduled. Allowed values: pause, stop | | data.restartReason | string | No | — | Why the experiment was restarted, if it was restarted as new. Null otherwise. Constraints: nullable | | data.originalTargetDuration | number | No | — | The originally configured target duration in days, retained when `duration` is later changed. Constraints: format: double, nullable | | data.wasAutoDisabled | boolean | No | — | Whether the experiment was automatically disabled (e.g. by an auto-disable rule) rather than stopped by a user. | | data.isPromptExperiment | boolean | No | — | Whether this experiment is a prompt experiment. | | data.isTemplate | boolean | No | — | Whether this experiment is a template that other experiments can be created from. | | data.allowOverridesInPulse | boolean | No | — | Whether units assigned by an override are included in results. Affects how results should be interpreted. | | data.excludePausedExposuresAndEvents | boolean | No | — | Whether exposures and events recorded while the experiment was paused are excluded from analysis. | | data.defaultImpactMultiplier | number | No | — | Multiplier applied to reported impact figures for this experiment. Constraints: format: double | | data.bonferroniPrimaryMetricWeight | number | No | — | The share of α allocated to primary metrics for the Bonferroni-per-metric correction. Matches the `bonferroniPrimaryMetricWeight` query parameter on the pulse endpoints, which previously accepted this value without exposing the experiment’s configured one. Constraints: format: double | | data.defaultSPRTTestDelta | number | No | — | Default SPRT test-group delta. Constraints: format: double | | data.defaultSPRTControlDelta | number | No | — | Default SPRT control-group delta. Constraints: format: double | | data.isImpactBankEnabled | boolean | No | — | Whether Impact Bank is enabled for this experiment. | | data.originalTargetExposures | number | No | — | The originally configured target exposures, retained when `targetExposures` is later changed. Counterpart to `originalTargetDuration`. Constraints: format: double, nullable | | data.reviewsRequiredLocally | boolean | No | — | Whether a review requirement is set on this experiment itself, as opposed to being inherited from project or team settings. `reviewSettings.requiredReview` reports the effective requirement. | | data.isHistoricalCloudExperiment | boolean | No | — | Whether this is a pre-existing cloud (non-warehouse-native) experiment inside a warehouse-native project. | | data.originalScheduledReloadHour | number | No | — | The originally configured scheduled reload hour, retained when `scheduledReloadHour` is later changed. Constraints: format: double, nullable | | data.layerID | string | Yes | — | Constraints: nullable | | data.startTime | number | Yes | — | Constraints: format: double, nullable | | data.endTime | number | Yes | — | Constraints: format: double, nullable | | data.decisionTime | number | Yes | — | Constraints: format: double, nullable | | data.healthChecks | object[] | No | — | — | | data.healthChecks.name | string | Yes | — | — | | data.healthChecks.description | string | Yes | — | — | | data.healthChecks.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata | object | No | — | — | | data.healthChecks.metadata.type | string | Yes | — | — | | data.healthChecks.metadata.lastPulseLoadTime | number | No | — | — | | data.healthChecks.metadata.crossoverPercent | number | No | — | — | | data.healthChecks.metadata.p_value | number | No | — | — | | data.healthChecks.metadata.assignmentSourceID | string | No | — | — | | data.healthChecks.metadata.assignmentSourceName | string | No | — | — | | data.healthChecks.metadata.foreignExperimentID | string | No | — | — | | data.healthChecks.metadata.deduplication_rate | number | No | — | — | | data.healthChecks.metadata.deduplication_rates | object[] | No | — | — | | data.healthChecks.metadata.deduplication_rates.group_id | string | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.rate | number | Yes | — | — | | data.healthChecks.metadata.deduplication_rates.group_name | string | Yes | — | — | | data.healthChecks.metadata.primary_id_type | string | Yes | — | — | | data.healthChecks.metadata.secondary_id_type | string | No | — | — | | data.healthChecks.metadata.missingMetrics | string[] | No | — | — | | data.healthChecks.metadata.metrics | object[] | No | — | — | | data.healthChecks.metadata.metrics.metric_name | string | Yes | — | — | | data.healthChecks.metadata.metrics.earliest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.metrics.latest_date | string | Yes | — | Constraints: format: date-time, nullable | | data.healthChecks.metadata.lastUpdatedDs | string | No | — | — | | data.healthChecks.metadata.groups | object[] | No | — | — | | data.healthChecks.metadata.groups.groupID | string | Yes | — | — | | data.healthChecks.metadata.groups.groupName | string | Yes | — | — | | data.healthChecks.metadata.groups.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groups.metrics | object[] | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricKey | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.metricTitle | string | Yes | — | — | | data.healthChecks.metadata.groups.metrics.status | string | Yes | — | Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.healthChecks.metadata.groupBucketInfo | object[] | No | — | — | | data.healthChecks.metadata.groupBucketInfo.groupID | string | Yes | — | — | | data.healthChecks.metadata.groupBucketInfo.averageBucketSize | number | Yes | — | — | | data.healthChecks.type | string | No | — | Allowed values: has_checks, has_valid_unit_type, has_balanced_exposures, has_event_metrics, has_pulse_metrics, assignment_health, has_crossover, has_exposures, has_recent_exposures_for_analyze_whn, user_metrics_exist, deduplication_rate, deduplication_rate_group_level, windowed_metrics_have_outliers, exposures_data_is_behind, pre_experimental_bias_check, segments_of_interest_analysis, has_changed_parameter, metric_history_for_topline_impact, default_value_mismatch, has_data_gaps, has_correct_target_app, has_dag_failures, has_exploration_completed, autotune_has_outcomes, metric_stability, has_balanced_exposures | | data.healthCheckStatus | string | Yes | — | Overall health check status Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.experimentType | string | Yes | — | The type of experiment Allowed values: BASE, GEO, SWITCHBACK, PROMPT, SIDECAR, GRID_SEARCH | | data.isStale | boolean | Yes | — | Whether the experiment is considered stale (e.g. in progress or decision-made and not modified in 30+ days). | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.inlineTargetingRulesJSON | string | No | — | A raw JSON string of the inline targeting rules Constraints: nullable | | data.inlineTargetingRules | object[] | No | — | A formatted array of the inline targeting rules | | data.inlineTargetingRules.name | string | Yes | — | The name of this rule. | | data.inlineTargetingRules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.inlineTargetingRules.conditions | object[] | Yes | — | An array of Condition objects. | | data.inlineTargetingRules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.inlineTargetingRules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.inlineTargetingRules.conditions.field | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.customID | string | No | — | Constraints: nullable | | data.inlineTargetingRules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.inlineTargetingRules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.inlineTargetingRules.id | string | No | — | The Statsig ID of this rule. | | data.inlineTargetingRules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.inlineTargetingRules.returnValue | object | No | — | The return value of the rule. | | data.inlineTargetingRules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.inlineTargetingRules.completedAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.inlineTargetingRules.pendingAutomatedRollouts.time | number | No | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.inlineTargetingRules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.inlineTargetingRules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.inlineTargetingRules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.inlineTargetingRules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.inlineTargetingRules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.inlineTargetingRules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.inlineTargetingRules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.qualityScore | object | No | — | The experiment quality score and per-criterion breakdown. Constraints: nullable | | data.qualityScore.score | number | Yes | — | The normalized experiment quality score. Constraints: format: double | | data.qualityScore.breakdown | object[] | Yes | — | The per-criterion quality score breakdown. | | data.qualityScore.breakdown.criterion | string | Yes | — | The quality score criterion name. | | data.qualityScore.breakdown.status | string | Yes | — | The quality score status for the criterion. Constraints: nullable Allowed values: PASSED, FAILED, WAITING, WARNING, NOT_APPLIED | | data.qualityScore.breakdown.passingDescription | string | Yes | — | The passing description for the criterion. | | data.qualityScore.breakdown.score | number | Yes | — | The normalized score contribution for this criterion. | | data.qualityScore.breakdown.weight | number | Yes | — | The normalized weight for this criterion. | | data.summarySections | object[] | No | — | Constraints: nullable | | data.summarySections.name | string | Yes | — | — | | data.summarySections.content | string | Yes | — | Constraints: nullable | | data.permalink | string | Yes | — | A permalink to this experiment in the Statsig Console. Constraints: format: uri | | data.shipWithHoldout | object | No | — | Present when the experiment has been shipped with a holdback group via make_decision (i.e. the winning variant is live for most users but a control slice is held back for ongoing measurement). Absent for experiments that have not been shipped, or that were shipped fully without a holdback. | | data.shipWithHoldout.holdoutPercent | integer | Yes | 10 | Integer percentage of users held back when the experiment was shipped with holdback. Each non-shipped group receives this percentage of traffic and the shipped group receives the remainder. Constraints: format: int64 | | data.shipWithHoldout.shippedGroupID | string | Yes | — | ID of the group that was shipped (i.e. the winning variant). | | data.shipWithHoldout.shippedGroupName | string | Yes | — | Name of the group that was shipped. | | data.shipWithHoldout.shippedWithHoldoutTime | number | No | — | Unix timestamp (ms) at which the experiment was shipped with holdback. Constraints: format: double | | data.shipWithHoldout.expectedDuration | number | No | — | Expected duration of the holdback period in days, if specified when shipping. Constraints: format: double | | data.powerAnalyses | object[] | Yes | — | The power analyses linked to this experiment. Empty when no power analysis is linked. | | data.powerAnalyses.id | string | Yes | — | The ID of the linked power analysis report. | | data.powerAnalyses.name | string | Yes | — | The name of the linked power analysis report. Constraints: nullable | | data.powerAnalyses.status | string | Yes | — | The status of the linked power analysis report. Allowed values: pending, failed, ready, expired | | data.powerAnalyses.isPrimary | boolean | Yes | — | Whether this is the experiment's primary attached power analysis report. | | data.geotestData | object | No | — | Geo test settings (geo ID type, treatment window, model and design parameters, and the final treatment geos). Present only for geo test experiments. Read-only; configured in the console. | | data.geotestData.geoIDType | string | Yes | — | — | | data.geotestData.treatmentStartDS | string | Yes | — | — | | data.geotestData.treatmentEndDS | string | Yes | — | — | | data.geotestData.preTreatmentDuration | number | No | — | Constraints: format: double, nullable | | data.geotestData.expectedEffectSize | number | Yes | — | Constraints: format: double | | data.geotestData.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestData.alpha | number | Yes | — | Constraints: format: double | | data.geotestData.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestData.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestData.budgeting | object | No | — | — | | data.geotestData.budgeting.totalBudget | number | Yes | — | Constraints: format: double | | data.geotestData.budgeting.incrementalCost | number | Yes | — | Constraints: format: double | | data.geotestData.conformalGridSize | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestData.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestData.iidResamples | number | No | — | Constraints: format: double, nullable | | data.geotestData.domainSet | string[] | Yes | — | — | | data.geotestData.designStartDS | string | No | — | Constraints: nullable | | data.geotestData.designEndDS | string | No | — | Constraints: nullable | | data.geotestData.groups | object[] | No | — | — | | data.geotestData.groups.name | string | Yes | — | — | | data.geotestData.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestData.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestData.treatmentGeoNumMin | number | No | — | Constraints: format: double, nullable | | data.geotestData.treatmentGeoNumMax | number | No | — | Constraints: format: double, nullable | | data.geotestData.rollingLookbackWindows | number | No | — | Constraints: format: double, nullable | | data.geotestData.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestData.dynamicTimeWarping | number | No | — | Constraints: format: double, nullable | | data.geotestData.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestData.controlShareBounds.lowerBound | number | Yes | — | Constraints: format: double | | data.geotestData.controlShareBounds.upperBound | number | Yes | — | Constraints: format: double | | data.geotestData.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestData.finalGroups.name | string | Yes | — | — | | data.geotestData.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets | object[] | No | — | Geo test design sets generated for this experiment. Present only for geo test experiments. | | data.geotestDesignSets.id | string | Yes | — | — | | data.geotestDesignSets.name | string | Yes | — | — | | data.geotestDesignSets.state | string | Yes | — | Allowed values: loading, success, failed | | data.geotestDesignSets.creatorName | string | Yes | — | — | | data.geotestDesignSets.createdTime | number | Yes | — | Unix timestamp (ms) at which the design set was created. | | data.geotestDesignSets.parameters | object | Yes | — | The geo test settings this design set was run with, including its `designStartDS`/`designEndDS` window. | | data.geotestDesignSets.parameters.geoIDType | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentStartDS | string | Yes | — | — | | data.geotestDesignSets.parameters.treatmentEndDS | string | Yes | — | — | | data.geotestDesignSets.parameters.preTreatmentDuration | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.expectedEffectSize | number | Yes | — | — | | data.geotestDesignSets.parameters.oneSidedDirection | string | No | — | Allowed values: increase, decrease | | data.geotestDesignSets.parameters.alpha | number | Yes | — | — | | data.geotestDesignSets.parameters.model | string | No | — | Constraints: nullable Allowed values: None, GSYN, Ridge, best | | data.geotestDesignSets.parameters.method | string | No | — | Constraints: nullable Allowed values: conformal, jackknife+ | | data.geotestDesignSets.parameters.budgeting | object | No | — | — | | data.geotestDesignSets.parameters.budgeting.totalBudget | number | Yes | — | — | | data.geotestDesignSets.parameters.budgeting.incrementalCost | number | Yes | — | — | | data.geotestDesignSets.parameters.conformalGridSize | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeFixedEffects | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.conformalType | string | No | — | Constraints: nullable Allowed values: iid, block | | data.geotestDesignSets.parameters.iidResamples | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.domainSet | string[] | Yes | — | — | | data.geotestDesignSets.parameters.designStartDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.designEndDS | string | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.groups | object[] | No | — | — | | data.geotestDesignSets.parameters.groups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.groups.includedInTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.groups.excludedFromTreatment | string[] | Yes | — | — | | data.geotestDesignSets.parameters.treatmentGeoNumMin | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.treatmentGeoNumMax | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.rollingLookbackWindows | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.includeCorrelations | boolean | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.dynamicTimeWarping | number | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds | object | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.controlShareBounds.lowerBound | number | Yes | — | — | | data.geotestDesignSets.parameters.controlShareBounds.upperBound | number | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups | object[] | No | — | Constraints: nullable | | data.geotestDesignSets.parameters.finalGroups.name | string | Yes | — | — | | data.geotestDesignSets.parameters.finalGroups.geos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions | object[] | Yes | — | Candidate treatment/control geo splits produced by the design run. Empty while the run is loading or if it failed. | | data.geotestDesignSets.designOptions.power | number | Yes | — | — | | data.geotestDesignSets.designOptions.cost | number | Yes | — | — | | data.geotestDesignSets.designOptions.percentPerGroup | number[] | Yes | — | — | | data.geotestDesignSets.designOptions.geosInGroup | string[][] | Yes | — | — | | data.geotestDesignSets.designOptions.unusedGeos | string[] | Yes | — | — | | data.geotestDesignSets.designOptions.duration | number | Yes | — | — | | data.geotestDesignSets.designOptions.effect_size | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_scaled_l2_imbalance | number | Yes | — | — | | data.geotestDesignSets.designOptions.avg_att | number | Yes | — | — | | data.geotestDesignSets.designOptions.average_mde | number | Yes | — | — | | data.geotestDesignSets.designOptions.abs_lift_in_zero | number | Yes | — | — | | data.geotestDesignSets.designOptions.proportion_total_Y | number | Yes | — | — | | data.geotestDesignSets.designOptions.holdout | number | Yes | — | — | | data.geotestDesignSets.designOptions.rank | number | Yes | — | — | | data.geotestDesignSets.designOptions.correlation | number | No | — | Constraints: nullable | | data.gridSearchData | object | No | — | Grid search settings: the parameters being searched, excluded combinations, and the group bucket and drop mappings. Present only for grid search experiments. Read-only; configured in the console. | | data.gridSearchData.desiredTargetGroups | number | Yes | — | Constraints: format: double | | data.gridSearchData.parameters | object[] | Yes | — | — | | data.gridSearchData.parameters.name | string | Yes | — | — | | data.gridSearchData.parameters.type | string | Yes | — | Allowed values: string, number, boolean | | data.gridSearchData.parameters.baseline | string | Yes | — | — | | data.gridSearchData.parameters.values | string[] | Yes | — | — | | data.gridSearchData.exclusions | object[] | Yes | — | — | | data.gridSearchData.bucketMapping | object | No | — | — | | data.gridSearchData.dropMapping | object | No | — | — | ```json { "message": "Restart As New Experiment Success", "data": { "id": "a_experiment", "permalink": "https://console.statsig.com/company_id/experiments/a_experiment", "description": "", "lastModifiedTime": 1707427635442, "lastModifierEmail": null, "createdTime": 1707427634717, "creatorName": "CONSOLE API", "lastModifierName": "CONSOLE API", "lastModifierID": "4FKF0sUbi1D7xZFW5vcHWB", "idType": "userID", "status": "setup", "experimentType": "BASE", "launchedGroupID": null, "layerID": "statsig::a_experiment_layer", "hypothesis": "", "primaryMetrics": [], "primaryMetricTags": [], "secondaryMetrics": [], "secondaryMetricTags": [], "startTime": null, "endTime": null, "decisionTime": null, "groups": [ { "name": "Control", "id": "4HbgLdfqlIeN3sHkyMG1qC", "size": 50, "parameterValues": {}, "isControl": true }, { "name": "Test", "size": 50, "parameterValues": {}, "isControl": false } ], "allocation": 100, "duration": 14, "targetingGateID": "", "defaultConfidenceInterval": "95", "bonferroniCorrection": false, "tags": [ "* Core" ], "decisionReason": "", "owner": { "ownerType": "USER", "ownerName": "Test User" }, "healthCheckStatus": "PASSED", "isStale": false, "inlineTargetingRulesJSON": "{}", "powerAnalyses": [] } } ``` **400** — Experiment has not yet started | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/restart_as_new" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/restart_as_new", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/restart_as_new", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/restart_as_new"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/restart_as_new", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/restart_as_new")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/restart_as_new") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve cumulative exposures URL: https://docs.statsig.com/api-reference/experiments/retrieve-cumulative-exposures ================================================================================ # Retrieve cumulative exposures ## Retrieve cumulative exposures **GET** `/console/v1/experiments/{id}/cumulative_exposures` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures` Retrieve cumulative exposures ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Get cumulative exposures success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.groupID | string | Yes | — | — | | data.groupName | string | Yes | — | — | | data.results | object[] | Yes | — | — | | data.results.date | string | Yes | — | — | | data.results.exposures | number | Yes | — | — | ```json { "message": "Successfully loaded Cumulative Exposures", "data": [ { "groupID": "6pY4WNHgJu1sqAyApUZuaa", "groupName": "Daily Deals", "results": [ { "date": "2024-12-23", "exposures": 0 }, { "date": "2024-12-24", "exposures": 7407 }, { "date": "2024-12-25", "exposures": 10237 }, { "date": "2024-12-26", "exposures": 10725 }, { "date": "2024-12-27", "exposures": 10906 }, { "date": "2024-12-28", "exposures": 11061 }, { "date": "2024-12-29", "exposures": 11251 }, { "date": "2024-12-30", "exposures": 11412 } ] }, { "groupID": "6pY4WPmjbMaWK06w12V7tc", "groupName": "Items You May Like", "results": [ { "date": "2024-12-23", "exposures": 0 }, { "date": "2024-12-24", "exposures": 7392 }, { "date": "2024-12-25", "exposures": 10239 }, { "date": "2024-12-26", "exposures": 10732 }, { "date": "2024-12-27", "exposures": 10934 }, { "date": "2024-12-28", "exposures": 11108 }, { "date": "2024-12-29", "exposures": 11287 }, { "date": "2024-12-30", "exposures": 11455 } ] }, { "groupID": "6pY4WR1lE4kr3pErCaQKMe", "groupName": "Buy Again", "results": [ { "date": "2024-12-23", "exposures": 0 }, { "date": "2024-12-24", "exposures": 7475 }, { "date": "2024-12-25", "exposures": 10289 }, { "date": "2024-12-26", "exposures": 10774 }, { "date": "2024-12-27", "exposures": 10975 }, { "date": "2024-12-28", "exposures": 11168 }, { "date": "2024-12-29", "exposures": 11321 }, { "date": "2024-12-30", "exposures": 11483 } ] } ] } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/cumulative_exposures") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve Experiment Checks Diagnostics URL: https://docs.statsig.com/api-reference/experiments/retrieve-experiment-checks-diagnostics ================================================================================ # Retrieve Experiment Checks Diagnostics ## Retrieve Experiment Checks Diagnostics **GET** `/console/v1/experiments/{id}/diagnostics_checks` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks` Retrieve Experiment Checks Diagnostics ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | type (query) | string | No | daily_cumulative_checks | Allowed values: daily_cumulative_checks, unique_ids | | startDate (query) | string | No | 2024-01-01 | Start date in YYYY-MM-DD format | | endDate (query) | string | No | 2024-01-01 | End date in YYYY-MM-DD format | | lastDays (query) | integer | No | — | Return the most recent N days instead of an explicit range, e.g. `30`. Ignored when `startDate` or `endDate` is supplied. Defaults to 7 days when neither is given. Constraints: min: 1, max: 90 | ## Response (application/json) **200** — Get Experiment Checks Diagnostics Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.experimentName | string | Yes | — | — | | data.type | string | Yes | — | Allowed values: daily_cumulative_checks, unique_ids | | data.unit_id_type | string | No | — | — | | data.is_realtime | boolean | Yes | — | Whether the final data point covers a still-filling day. False when the last day is complete, and always false for analysis-only experiments, whose counts come from a daily warehouse export. | | data.startDate | string | Yes | — | Start date in YYYY-MM-DD format | | data.endDate | string | Yes | — | End date in YYYY-MM-DD format | | data.data | object[] | Yes | — | — | | data.data.date | string | Yes | — | Date in YYYY-MM-DD format | | data.data.results | object[] | Yes | — | — | | data.data.results.group_name | string | Yes | — | — | | data.data.results.group_id | string | Yes | — | — | | data.data.results.count | number | Yes | — | — | ```json { "message": "string", "data": { "experimentName": "string", "type": "daily_cumulative_checks", "unit_id_type": "string", "is_realtime": true, "startDate": "string", "endDate": "string", "data": [ { "date": "string", "results": [ { "group_name": "string", "group_id": "string", "count": 0 } ] } ] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/diagnostics_checks?type=daily_cumulative_checks&startDate=2024-01-01&endDate=2024-01-01") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve Experiment Summary Charts (Beta) URL: https://docs.statsig.com/api-reference/experiments/retrieve-experiment-summary-charts-beta ================================================================================ # Retrieve Experiment Summary Charts (Beta) ## Retrieve Experiment Summary Charts (Beta) **GET** `/console/v1/experiments/{id}/summary_charts` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/summary_charts` Retrieve Experiment Summary Charts (Beta) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | control (query) | string | No | — | Optional override control group ID | | test (query) | string | No | — | Optional override test group ID. Use "*" to query against all test groups. | ## Response (application/json) **200** — Get Experiment Summary Charts Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.experimentID | string | Yes | — | — | | data.sections | object[] | Yes | — | — | | data.sections.sectionLabel | string | Yes | — | — | | data.sections.charts | object[] | Yes | — | — | | data.sections.charts.chartSource | string | Yes | — | Allowed values: experiment, custom_query, scheduled_custom_query, unsupported | | data.sections.charts.message | string | No | — | — | | data.sections.charts.control | string | No | — | — | | data.sections.charts.test | string | No | — | — | | data.sections.charts.display | string | No | — | Allowed values: cumulative, daily, dx, bar, table | | data.sections.charts.cuped | boolean | No | — | — | | data.sections.charts.sequentialTesting | boolean | No | — | — | | data.sections.charts.metrics | object[] | No | — | — | | data.sections.charts.metrics.metricID | string | Yes | — | — | | data.sections.charts.metrics.metricName | string | Yes | — | — | | data.sections.charts.metrics.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.sections.charts.metrics.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.sections.charts.metrics.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.sections.charts.metrics.absoluteChange | number | No | — | — | | data.sections.charts.metrics.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.sections.charts.metrics.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.confidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.confidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.percentChange | number | No | — | — | | data.sections.charts.metrics.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.percentConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.percentConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.percentConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.testMean | number | No | — | — | | data.sections.charts.metrics.controlMean | number | No | — | — | | data.sections.charts.metrics.testStd | number | No | — | — | | data.sections.charts.metrics.controlStd | number | No | — | — | | data.sections.charts.metrics.testUnits | number | No | — | — | | data.sections.charts.metrics.controlUnits | number | No | — | — | | data.sections.charts.metrics.pValue | number | No | — | — | | data.sections.charts.metrics.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.sections.charts.metrics.adjustedAlpha | number | No | — | — | | data.sections.charts.metrics.reversePower | number | No | — | — | | data.sections.charts.metrics.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.percentCredibleInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.percentCredibleInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.sections.charts.metrics.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.sections.charts.metrics.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.sections.charts.metrics.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.sections.charts.metrics.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.sections.charts.metrics.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.sections.charts.metrics.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.sections.charts.metrics.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.sections.charts.metrics.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.sections.charts.metrics.absoluteToplineImpact | number | No | — | — | | data.sections.charts.metrics.absoluteToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.relativeToplineImpact | number | No | — | — | | data.sections.charts.metrics.relativeToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.projectedAbsoluteToplineImpact | number | No | — | — | | data.sections.charts.metrics.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.projectedRelativeToplineImpact | number | No | — | — | | data.sections.charts.metrics.projectedRelativeToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown | object[] | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.metricID | string | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.metricName | string | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.sections.charts.metrics.dimensionBreakdown.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.sections.charts.metrics.dimensionBreakdown.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.sections.charts.metrics.dimensionBreakdown.absoluteChange | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.sections.charts.metrics.dimensionBreakdown.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.dimensionBreakdown.confidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.confidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentChange | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.dimensionBreakdown.percentConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.sections.charts.metrics.dimensionBreakdown.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.testMean | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.controlMean | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.testStd | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.controlStd | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.testUnits | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.controlUnits | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.pValue | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.sections.charts.metrics.dimensionBreakdown.adjustedAlpha | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.reversePower | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.dimensionBreakdown.percentCredibleInterval.lower | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.percentCredibleInterval.upper | number | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.dimensionBreakdown.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.sections.charts.metrics.dimensionBreakdown.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.sections.charts.metrics.dimensionBreakdown.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.sections.charts.metrics.dimensionBreakdown.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.sections.charts.metrics.dimensionBreakdown.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.sections.charts.metrics.dimensionBreakdown.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.sections.charts.metrics.dimensionBreakdown.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.sections.charts.metrics.dimensionBreakdown.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.sections.charts.metrics.dimensionBreakdown.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.sections.charts.metrics.dimensionBreakdown.absoluteToplineImpact | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.absoluteToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.relativeToplineImpact | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.relativeToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.projectedAbsoluteToplineImpact | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.projectedRelativeToplineImpact | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.projectedRelativeToplineImpactDelta | number | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.dimensionKey | string | Yes | — | — | | data.sections.charts.metrics.dimensionBreakdown.dimensionType | string | No | — | — | | data.sections.charts.metrics.dimensionBreakdown.dimensionValue | string | Yes | — | — | ```json { "message": "Successfully loaded Experiment Summary Charts", "data": { "experimentID": "my_experiment", "sections": [ { "sectionLabel": "Experiment Notes", "charts": [ { "chartSource": "experiment", "control": "control", "test": "test", "display": "cumulative", "cuped": true, "sequentialTesting": true, "metrics": [ { "metricID": "signup::event_count", "metricName": "Signup", "directionality": "increase", "absoluteChange": 4.5, "confidenceIntervalDelta": 1.8, "percentChange": 5.1, "percentConfidenceIntervalDelta": 2.3, "sequentialTestingConfidenceIntervalDelta": 1.9, "percentSequentialTestingConfidenceIntervalDelta": 2.4, "testMean": 104.5, "controlMean": 100, "testStd": 15, "controlStd": 14.2, "testUnits": 1200, "controlUnits": 1180, "pValue": 0.03, "reversePower": 0.71, "dimensionBreakdown": [ { "metricID": "signup::event_count", "metricName": "Signup", "directionality": "increase", "dimensionKey": "country", "dimensionType": "event", "dimensionValue": "US", "absoluteChange": 5.2, "confidenceIntervalDelta": 2.1, "percentChange": 6.2, "percentConfidenceIntervalDelta": 2.8, "sequentialTestingConfidenceIntervalDelta": 2.2, "percentSequentialTestingConfidenceIntervalDelta": 2.9, "testMean": 88.2, "controlMean": 83, "testStd": 9.4, "controlStd": 9.1, "testUnits": 600, "controlUnits": 590, "pValue": 0.04, "reversePower": 0.64 } ] } ] }, { "chartSource": "scheduled_custom_query", "message": "Not supported at this time" } ] } ] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/summary_charts" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/summary_charts", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/summary_charts", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/summary_charts"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/summary_charts", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/summary_charts")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/summary_charts") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve Exposures By Dimension URL: https://docs.statsig.com/api-reference/experiments/retrieve-exposures-by-dimension ================================================================================ # Retrieve Exposures By Dimension ## Retrieve Exposures By Dimension **GET** `/console/v1/experiments/{id}/dimensional_exposures` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures` Retrieve Exposures By Dimension ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | dimension_type (query) | oneOf | No | — | Optional dimension type(s) to filter by (for example metadata.country). Constraints: string, string[] | | severity (query) | string | No | — | Optional severity filter: warning (p-value < 0.01) or failure (p-value < 0.001). Allowed values: warning, failure | ## Response (application/json) **200** — Get dimensional exposures success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.ds | string | Yes | — | Date in YYYY-MM-DD format Constraints: nullable | | data.dimensions | object[] | Yes | — | — | | data.dimensions.dimension_type | string | Yes | — | — | | data.dimensions.dimension_values | object[] | Yes | — | — | | data.dimensions.dimension_values.dimension_value | string | Yes | — | — | | data.dimensions.dimension_values.srm_pvalue | number | Yes | — | Constraints: nullable | | data.dimensions.dimension_values.unit_count | number | Yes | — | — | | data.dimensions.dimension_values.severity | string | Yes | — | Allowed values: pass, warning, failure | ```json { "message": "Successfully loaded Dimensional Exposures", "data": { "ds": "2026-03-24", "dimensions": [ { "dimension_type": "metadata.country", "dimension_values": [ { "dimension_value": "US", "srm_pvalue": 0.8124, "unit_count": 30723, "severity": "pass" } ] }, { "dimension_type": "metadata.app_version", "dimension_values": [ { "dimension_value": "1.2.3", "srm_pvalue": 0.0342, "unit_count": 2235, "severity": "pass" } ] } ] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/dimensional_exposures") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve Pulse Metric Result URL: https://docs.statsig.com/api-reference/experiments/retrieve-pulse-metric-result ================================================================================ # Retrieve Pulse Metric Result ## Retrieve Pulse Metric Result **GET** `/console/v1/experiments/{id}/pulse_metric_result` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result` Retrieve Pulse Metric Result ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | control (query) | string | Yes | — | Control Group ID | | test (query) | string | Yes | — | Test Group ID | | cuped (query) | string | No | — | Whether to apply CUPED. Allowed values are "true" or "false". | | confidence (query) | string | No | — | Confidence interval (0-100) | | applyBonferroniPerVariant (query) | string | No | — | Whether to apply Bonferroni Per Variant. Allowed values are "true" or "false". | | applyBonferroniPerMetric (query) | string | No | — | Whether to apply Bonferroni Per Metric. Allowed values are "true" or "false". | | bonferroniPrimaryMetricWeight (query) | string | No | — | α allocated to primary metrics | | applyBenjaminiHochbergPerMetric (query) | string | No | — | Whether to apply Benjamini-Hochberg Correction Per Metric. Allowed values are "true" or "false". | | applyBenjaminiHochbergPerVariant (query) | string | No | — | Whether to apply Benjamini-Hochberg Correction Per Variant. Allowed values are "true" or "false". | | benjaminiPrimaryMetricsOnly (query) | string | No | — | Whether Benjamini-Hochberg correction should apply only to primary metrics. Allowed values are "true" or "false". | | date (query) | string | No | — | Date for pulse results. format must be YYYY-MM-DD | | benjaminiAcrossAllTestGroups (query) | string | No | — | Whether to compute the Benjamini-Hochberg / Bonferroni-per-group correction across all of the experiment's test groups (matching the Console Results tab default for multi-group experiments) rather than only the requested test-vs-control pair. The returned results are always scoped to the requested pair; this controls only the correction family. Allowed values are "true" or "false". Defaults to "true". | | metricID (query) | string | Yes | — | Metric ID in format <metric_name>::<metric_type> | ## Response (application/json) **200** — Get Pulse Metric Result Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.ds | string | Yes | — | — | | data.dimensionResults | object[] | Yes | — | — | | data.dimensionResults.dimension | string | Yes | — | — | | data.dimensionResults.dimension_value | string | Yes | — | — | | data.dimensionResults.metric | object | Yes | — | Constraints: nullable | | data.dimensionResults.metric.metricID | string | Yes | — | — | | data.dimensionResults.metric.metricName | string | Yes | — | — | | data.dimensionResults.metric.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.dimensionResults.metric.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.dimensionResults.metric.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.dimensionResults.metric.absoluteChange | number | No | — | — | | data.dimensionResults.metric.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.dimensionResults.metric.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.dimensionResults.metric.confidenceInterval.lower | number | Yes | — | — | | data.dimensionResults.metric.confidenceInterval.upper | number | Yes | — | — | | data.dimensionResults.metric.percentChange | number | No | — | — | | data.dimensionResults.metric.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.dimensionResults.metric.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.dimensionResults.metric.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.dimensionResults.metric.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.dimensionResults.metric.percentConfidenceIntervalDelta | number | No | — | — | | data.dimensionResults.metric.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.dimensionResults.metric.percentConfidenceInterval.lower | number | Yes | — | — | | data.dimensionResults.metric.percentConfidenceInterval.upper | number | Yes | — | — | | data.dimensionResults.metric.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.dimensionResults.metric.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.dimensionResults.metric.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.dimensionResults.metric.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.dimensionResults.metric.testMean | number | No | — | — | | data.dimensionResults.metric.controlMean | number | No | — | — | | data.dimensionResults.metric.testStd | number | No | — | — | | data.dimensionResults.metric.controlStd | number | No | — | — | | data.dimensionResults.metric.testUnits | number | No | — | — | | data.dimensionResults.metric.controlUnits | number | No | — | — | | data.dimensionResults.metric.pValue | number | No | — | — | | data.dimensionResults.metric.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.dimensionResults.metric.adjustedAlpha | number | No | — | — | | data.dimensionResults.metric.reversePower | number | No | — | — | | data.dimensionResults.metric.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.dimensionResults.metric.percentCredibleInterval.lower | number | Yes | — | — | | data.dimensionResults.metric.percentCredibleInterval.upper | number | Yes | — | — | | data.dimensionResults.metric.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.dimensionResults.metric.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.dimensionResults.metric.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.dimensionResults.metric.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.dimensionResults.metric.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.dimensionResults.metric.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.dimensionResults.metric.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.dimensionResults.metric.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.dimensionResults.metric.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.dimensionResults.metric.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.dimensionResults.metric.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.dimensionResults.metric.absoluteToplineImpact | number | No | — | — | | data.dimensionResults.metric.absoluteToplineImpactDelta | number | No | — | — | | data.dimensionResults.metric.relativeToplineImpact | number | No | — | — | | data.dimensionResults.metric.relativeToplineImpactDelta | number | No | — | — | | data.dimensionResults.metric.projectedAbsoluteToplineImpact | number | No | — | — | | data.dimensionResults.metric.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.dimensionResults.metric.projectedRelativeToplineImpact | number | No | — | — | | data.dimensionResults.metric.projectedRelativeToplineImpactDelta | number | No | — | — | ```json { "message": "string", "data": { "ds": "string", "dimensionResults": [ { "dimension": "string", "dimension_value": "string", "metric": { "metricID": "string", "metricName": "string", "directionality": "increase", "error": "no_data", "warnings": [ "string" ], "absoluteChange": 0, "confidenceIntervalDelta": 0, "confidenceInterval": { "lower": -1.33, "upper": 1.33 }, "percentChange": 0, "sequentialTestingConfidenceIntervalDelta": 0, "sequentialTestingConfidenceInterval": { "lower": -1.33, "upper": 1.33 }, "percentConfidenceIntervalDelta": 0, "percentConfidenceInterval": { "lower": -1.33, "upper": 1.33 }, "percentSequentialTestingConfidenceIntervalDelta": 0, "percentSequentialTestingConfidenceInterval": { "lower": -1.33, "upper": 1.33 }, "testMean": 0, "controlMean": 0, "testStd": 0, "controlStd": 0, "testUnits": 0, "controlUnits": 0, "pValue": 0, "sequentialTestingPValue": 0, "adjustedAlpha": 0, "reversePower": 0, "percentCredibleInterval": { "lower": -1.33, "upper": 1.33 }, "expectedLoss": 0, "chanceToBeat": 0, "sequentialTestingLikelihoodRatio": 0, "sequentialTestingLogLikelihoodRatio": 0, "sprtLowerLimit": 0, "sprtUpperLimit": 0, "sprtLogLowerLimit": 0, "sprtLogUpperLimit": 0, "sprtDecision": "alternative", "isSprtSignificant": true, "sprtStatsigness": "positive", "absoluteToplineImpact": 0, "absoluteToplineImpactDelta": 0, "relativeToplineImpact": 0, "relativeToplineImpactDelta": 0, "projectedAbsoluteToplineImpact": 0, "projectedAbsoluteToplineImpactDelta": 0, "projectedRelativeToplineImpact": 0, "projectedRelativeToplineImpactDelta": 0 } } ] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/pulse_metric_result") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Retrieve Pulse Results (Beta) URL: https://docs.statsig.com/api-reference/experiments/retrieve-pulse-results-beta ================================================================================ # Retrieve Pulse Results (Beta) ## Retrieve Pulse Results (Beta) **GET** `/console/v1/experiments/{id}/pulse_results` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/pulse_results` Retrieve Pulse Results (Beta) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | control (query) | string | Yes | — | Control Group ID | | test (query) | string | Yes | — | Test Group ID | | cuped (query) | string | No | — | Whether to apply CUPED. Allowed values are "true" or "false". | | confidence (query) | string | No | — | Confidence interval (0-100) | | applyBonferroniPerVariant (query) | string | No | — | Whether to apply Bonferroni Per Variant. Allowed values are "true" or "false". | | applyBonferroniPerMetric (query) | string | No | — | Whether to apply Bonferroni Per Metric. Allowed values are "true" or "false". | | bonferroniPrimaryMetricWeight (query) | string | No | — | α allocated to primary metrics | | applyBenjaminiHochbergPerMetric (query) | string | No | — | Whether to apply Benjamini-Hochberg Correction Per Metric. Allowed values are "true" or "false". | | applyBenjaminiHochbergPerVariant (query) | string | No | — | Whether to apply Benjamini-Hochberg Correction Per Variant. Allowed values are "true" or "false". | | benjaminiPrimaryMetricsOnly (query) | string | No | — | Whether Benjamini-Hochberg correction should apply only to primary metrics. Allowed values are "true" or "false". | | date (query) | string | No | — | Date for pulse results. format must be YYYY-MM-DD | | benjaminiAcrossAllTestGroups (query) | string | No | — | Whether to compute the Benjamini-Hochberg / Bonferroni-per-group correction across all of the experiment's test groups (matching the Console Results tab default for multi-group experiments) rather than only the requested test-vs-control pair. The returned results are always scoped to the requested pair; this controls only the correction family. Allowed values are "true" or "false". Defaults to "true". | ## Response (application/json) **200** — Get Pulse Results Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.ds | string | Yes | — | — | | data.primaryMetrics | object[] | Yes | — | — | | data.primaryMetrics.metricID | string | Yes | — | — | | data.primaryMetrics.metricName | string | Yes | — | — | | data.primaryMetrics.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.primaryMetrics.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.primaryMetrics.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.primaryMetrics.absoluteChange | number | No | — | — | | data.primaryMetrics.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.primaryMetrics.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.primaryMetrics.confidenceInterval.lower | number | Yes | — | — | | data.primaryMetrics.confidenceInterval.upper | number | Yes | — | — | | data.primaryMetrics.percentChange | number | No | — | — | | data.primaryMetrics.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.primaryMetrics.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.primaryMetrics.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.primaryMetrics.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.primaryMetrics.percentConfidenceIntervalDelta | number | No | — | — | | data.primaryMetrics.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.primaryMetrics.percentConfidenceInterval.lower | number | Yes | — | — | | data.primaryMetrics.percentConfidenceInterval.upper | number | Yes | — | — | | data.primaryMetrics.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.primaryMetrics.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.primaryMetrics.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.primaryMetrics.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.primaryMetrics.testMean | number | No | — | — | | data.primaryMetrics.controlMean | number | No | — | — | | data.primaryMetrics.testStd | number | No | — | — | | data.primaryMetrics.controlStd | number | No | — | — | | data.primaryMetrics.testUnits | number | No | — | — | | data.primaryMetrics.controlUnits | number | No | — | — | | data.primaryMetrics.pValue | number | No | — | — | | data.primaryMetrics.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.primaryMetrics.adjustedAlpha | number | No | — | — | | data.primaryMetrics.reversePower | number | No | — | — | | data.primaryMetrics.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.primaryMetrics.percentCredibleInterval.lower | number | Yes | — | — | | data.primaryMetrics.percentCredibleInterval.upper | number | Yes | — | — | | data.primaryMetrics.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.primaryMetrics.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.primaryMetrics.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.primaryMetrics.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.primaryMetrics.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.primaryMetrics.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.primaryMetrics.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.primaryMetrics.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.primaryMetrics.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.primaryMetrics.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.primaryMetrics.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.primaryMetrics.absoluteToplineImpact | number | No | — | — | | data.primaryMetrics.absoluteToplineImpactDelta | number | No | — | — | | data.primaryMetrics.relativeToplineImpact | number | No | — | — | | data.primaryMetrics.relativeToplineImpactDelta | number | No | — | — | | data.primaryMetrics.projectedAbsoluteToplineImpact | number | No | — | — | | data.primaryMetrics.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.primaryMetrics.projectedRelativeToplineImpact | number | No | — | — | | data.primaryMetrics.projectedRelativeToplineImpactDelta | number | No | — | — | | data.secondaryMetrics | object[] | Yes | — | — | | data.secondaryMetrics.metricID | string | Yes | — | — | | data.secondaryMetrics.metricName | string | Yes | — | — | | data.secondaryMetrics.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.secondaryMetrics.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.secondaryMetrics.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.secondaryMetrics.absoluteChange | number | No | — | — | | data.secondaryMetrics.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.secondaryMetrics.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.secondaryMetrics.confidenceInterval.lower | number | Yes | — | — | | data.secondaryMetrics.confidenceInterval.upper | number | Yes | — | — | | data.secondaryMetrics.percentChange | number | No | — | — | | data.secondaryMetrics.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.secondaryMetrics.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.secondaryMetrics.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.secondaryMetrics.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.secondaryMetrics.percentConfidenceIntervalDelta | number | No | — | — | | data.secondaryMetrics.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.secondaryMetrics.percentConfidenceInterval.lower | number | Yes | — | — | | data.secondaryMetrics.percentConfidenceInterval.upper | number | Yes | — | — | | data.secondaryMetrics.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.secondaryMetrics.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.secondaryMetrics.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.secondaryMetrics.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.secondaryMetrics.testMean | number | No | — | — | | data.secondaryMetrics.controlMean | number | No | — | — | | data.secondaryMetrics.testStd | number | No | — | — | | data.secondaryMetrics.controlStd | number | No | — | — | | data.secondaryMetrics.testUnits | number | No | — | — | | data.secondaryMetrics.controlUnits | number | No | — | — | | data.secondaryMetrics.pValue | number | No | — | — | | data.secondaryMetrics.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.secondaryMetrics.adjustedAlpha | number | No | — | — | | data.secondaryMetrics.reversePower | number | No | — | — | | data.secondaryMetrics.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.secondaryMetrics.percentCredibleInterval.lower | number | Yes | — | — | | data.secondaryMetrics.percentCredibleInterval.upper | number | Yes | — | — | | data.secondaryMetrics.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.secondaryMetrics.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.secondaryMetrics.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.secondaryMetrics.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.secondaryMetrics.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.secondaryMetrics.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.secondaryMetrics.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.secondaryMetrics.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.secondaryMetrics.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.secondaryMetrics.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.secondaryMetrics.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.secondaryMetrics.absoluteToplineImpact | number | No | — | — | | data.secondaryMetrics.absoluteToplineImpactDelta | number | No | — | — | | data.secondaryMetrics.relativeToplineImpact | number | No | — | — | | data.secondaryMetrics.relativeToplineImpactDelta | number | No | — | — | | data.secondaryMetrics.projectedAbsoluteToplineImpact | number | No | — | — | | data.secondaryMetrics.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.secondaryMetrics.projectedRelativeToplineImpact | number | No | — | — | | data.secondaryMetrics.projectedRelativeToplineImpactDelta | number | No | — | — | | data.otherMetrics | object[] | No | — | — | | data.otherMetrics.metricID | string | Yes | — | — | | data.otherMetrics.metricName | string | Yes | — | — | | data.otherMetrics.directionality | string | Yes | increase | Indicates the desired change direction for the metric. Use "increase" for positive changes and "decrease" for negative changes. Allowed values: increase, decrease | | data.otherMetrics.error | oneOf | No | no_data | Machine-readable reason when pulse statistics are unavailable. Common values include no_data (insufficient data), echidna_unripe (not yet loaded), and setup_incomplete (misconfigured metric source). Additional string values may appear for cohort/bake windows or other load failures. Constraints: nullable, string | | data.otherMetrics.warnings | string[] | No | — | Human-readable warnings about metric data quality, load state, or partial pipeline failures. | | data.otherMetrics.absoluteChange | number | No | — | — | | data.otherMetrics.confidenceIntervalDelta | number | No | — | Absolute confidence interval delta | | data.otherMetrics.confidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.otherMetrics.confidenceInterval.lower | number | Yes | — | — | | data.otherMetrics.confidenceInterval.upper | number | Yes | — | — | | data.otherMetrics.percentChange | number | No | — | — | | data.otherMetrics.sequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.otherMetrics.sequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.otherMetrics.sequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.otherMetrics.sequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.otherMetrics.percentConfidenceIntervalDelta | number | No | — | — | | data.otherMetrics.percentConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.otherMetrics.percentConfidenceInterval.lower | number | Yes | — | — | | data.otherMetrics.percentConfidenceInterval.upper | number | Yes | — | — | | data.otherMetrics.percentSequentialTestingConfidenceIntervalDelta | number | No | — | — | | data.otherMetrics.percentSequentialTestingConfidenceInterval | object | No | {"lower":-1.33,"upper":1.33} | Confidence interval bounds | | data.otherMetrics.percentSequentialTestingConfidenceInterval.lower | number | Yes | — | — | | data.otherMetrics.percentSequentialTestingConfidenceInterval.upper | number | Yes | — | — | | data.otherMetrics.testMean | number | No | — | — | | data.otherMetrics.controlMean | number | No | — | — | | data.otherMetrics.testStd | number | No | — | — | | data.otherMetrics.controlStd | number | No | — | — | | data.otherMetrics.testUnits | number | No | — | — | | data.otherMetrics.controlUnits | number | No | — | — | | data.otherMetrics.pValue | number | No | — | — | | data.otherMetrics.sequentialTestingPValue | number | No | — | Constraints: nullable | | data.otherMetrics.adjustedAlpha | number | No | — | — | | data.otherMetrics.reversePower | number | No | — | — | | data.otherMetrics.percentCredibleInterval | object | No | {"lower":-1.33,"upper":1.33} | Bayesian credible interval for the percent change. Only returned when results are computed with Bayesian analysis. | | data.otherMetrics.percentCredibleInterval.lower | number | Yes | — | — | | data.otherMetrics.percentCredibleInterval.upper | number | Yes | — | — | | data.otherMetrics.expectedLoss | number | No | — | Bayesian expected loss. Only returned when results are computed with Bayesian analysis. | | data.otherMetrics.chanceToBeat | number | No | — | Bayesian probability that the test beats the control. Only returned when results are computed with Bayesian analysis. | | data.otherMetrics.sequentialTestingLikelihoodRatio | number | No | — | SPRT likelihood ratio of the observed data under the alternative vs the null. This is the same value Pulse uses. | | data.otherMetrics.sequentialTestingLogLikelihoodRatio | number | No | — | Natural log of the SPRT likelihood ratio Pulse uses. Compare this to `sprtLogLowerLimit` and `sprtLogUpperLimit`. | | data.otherMetrics.sprtLowerLimit | number | No | — | Lower SPRT decision boundary on the likelihood-ratio scale. Crossing below this accepts the null. | | data.otherMetrics.sprtUpperLimit | number | No | — | Upper SPRT decision boundary on the likelihood-ratio scale. Crossing above this accepts the alternative. | | data.otherMetrics.sprtLogLowerLimit | number | No | — | Lower SPRT decision boundary on the log-likelihood-ratio scale. Crossing below this accepts the null. | | data.otherMetrics.sprtLogUpperLimit | number | No | — | Upper SPRT decision boundary on the log-likelihood-ratio scale. Crossing above this accepts the alternative. | | data.otherMetrics.sprtDecision | string | No | — | SPRT decision from the log likelihood ratio. `alternative` accepts H1, `null` accepts H0, and `continue` means the ratio is still between the boundaries. Allowed values: alternative, null, continue | | data.otherMetrics.isSprtSignificant | boolean | No | — | True when the SPRT decision is `alternative`, meaning the result is statistically significant. | | data.otherMetrics.sprtStatsigness | string | No | — | Direction of the SPRT decision relative to the metric's desired direction. `neutral` when the test has not accepted the alternative. Allowed values: positive, negative, neutral | | data.otherMetrics.absoluteToplineImpact | number | No | — | — | | data.otherMetrics.absoluteToplineImpactDelta | number | No | — | — | | data.otherMetrics.relativeToplineImpact | number | No | — | — | | data.otherMetrics.relativeToplineImpactDelta | number | No | — | — | | data.otherMetrics.projectedAbsoluteToplineImpact | number | No | — | — | | data.otherMetrics.projectedAbsoluteToplineImpactDelta | number | No | — | — | | data.otherMetrics.projectedRelativeToplineImpact | number | No | — | — | | data.otherMetrics.projectedRelativeToplineImpactDelta | number | No | — | — | ```json { "message": "Successfully loaded Pulse Results", "data": { "primaryMetrics": [ { "metricID": "Purchase::user_warehouse", "value": -0.5656598720428505, "confidence_interval_delta": 1.3331521511820725, "confidence_interval": { "lower": -1.8988120232249, "upper": 0.7674922791392 }, "percent_change": -0.9104559464139017, "percent_confidence_interval_delta": 2.145770565507353, "percent_confidence_interval": { "lower": -3.0562265119213, "upper": 1.2353146190935 }, "percent_sequential_testing_confidence_interval_delta": -1.6095466399726037, "percent_sequential_testing_confidence_interval": { "lower": 0.6990906935587, "upper": -2.5200025863865 }, "test_mean": 61.56363636363636, "control_mean": 62.12929623567921, "test_std": 0.7461734327711735, "control_std": 0.7248273669644147, "test_units": 1669, "control_units": 1589, "p_value": 0.7066986120589813, "sequentialTestingPValue": 0.7066986120589813, "adjustedAlpha": 0.05 } ], "secondaryMetrics": [ { "metricID": "Support Success Rate::user_warehouse", "value": 0.0032568848232868985, "confidence_interval_delta": 0.009120368109978388, "confidence_interval": { "lower": -0.00586348328669149, "upper": 0.012377252933265286 }, "percent_change": 0.4569873400680713, "percent_confidence_interval_delta": 1.2797175795779019, "percent_confidence_interval": { "lower": -0.8227302395098306, "upper": 1.736704919646 }, "percent_sequential_testing_confidence_interval_delta": -140.31424654645156, "percent_sequential_testing_confidence_interval": { "lower": 140.77123388651964, "upper": -139.8572592063835 }, "test_mean": 0.7159428911362284, "control_mean": 0.7126860063129415, "test_std": 0.0038882253564431193, "control_std": 0.003953024266669566, "test_units": 4696, "control_units": 4690, "p_value": 0.5569502167465609, "sequentialTestingPValue": 0.5569502167465609, "adjustedAlpha": 0.05 } ] } } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/pulse_results" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/pulse_results", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/pulse_results", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/pulse_results"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/pulse_results", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/pulse_results")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/pulse_results") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Schedule Experiment Start URL: https://docs.statsig.com/api-reference/experiments/schedule-experiment-start ================================================================================ # Schedule Experiment Start ## Schedule Experiment Start **POST** `/console/v1/experiments/{id}/schedule_start` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/schedule_start` Schedule Experiment Start ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | scheduledTime | number | Yes | — | Unix timestamp (in milliseconds) to schedule the experiment to start Constraints: format: double | ## Response (application/json) **200** — Schedule Experiment Start Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Successfully scheduled experiment start" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/schedule_start" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/schedule_start", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/schedule_start", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/schedule_start"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/schedule_start", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/schedule_start")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/schedule_start") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Schedule Experiment Stop URL: https://docs.statsig.com/api-reference/experiments/schedule-experiment-stop ================================================================================ # Schedule Experiment Stop ## Schedule Experiment Stop **POST** `/console/v1/experiments/{id}/schedule_stop` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/schedule_stop` Schedule Experiment Stop ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | scheduledTime | integer | Yes | — | Unix timestamp (in milliseconds) at which to stop the experiment Constraints: format: int64 | | actionType | string | Yes | — | `pause` stops new assignments (Stop New Assignments). `stop` concludes the experiment and defers the decision (Conclude & Defer Decision). Allowed values: pause, stop | ## Response (application/json) **200** — Schedule Experiment Stop Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Successfully scheduled experiment stop" } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/schedule_stop" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/schedule_stop", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/schedule_stop", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/schedule_stop"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/schedule_stop", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/schedule_stop")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/schedule_stop") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Start Experiment URL: https://docs.statsig.com/api-reference/experiments/start-experiment ================================================================================ # Start Experiment ## Start Experiment **PUT** `/console/v1/experiments/{id}/start` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/start` Start Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | analysisStartTime | string | No | 2024-10-01 | For Warehouse Native analysis-only experiments; start time of experiment analysis. | | analysisEndTime | string | No | 2024-10-30 | For Warehouse Native analysis-only experiments; end time of experiment analysis. | | turboMode | boolean | No | false | For Warehouse Native analysis-only experiments; whether to run the initial analysis in turbo mode | ## Response (application/json) **200** — Start Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully started." } ``` **400** — Experiment has not yet started | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/start" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/start", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/start", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/start"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/start", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/start")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/start") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Start Experiment Code Cleanup URL: https://docs.statsig.com/api-reference/experiments/start-experiment-code-cleanup ================================================================================ # Start Experiment Code Cleanup ## Start Experiment Code Cleanup **POST** `/console/v1/experiments/{id}/code_cleanup` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/code_cleanup` Start Experiment Code Cleanup ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Start experiment code cleanup | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment code cleanup started." } ``` **400** — Experiment is not stale. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/code_cleanup" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/code_cleanup", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/code_cleanup", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/code_cleanup"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/code_cleanup", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/code_cleanup")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/code_cleanup") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Unarchive Experiment URL: https://docs.statsig.com/api-reference/experiments/unarchive-experiment ================================================================================ # Unarchive Experiment ## Unarchive Experiment **PUT** `/console/v1/experiments/{id}/unarchive` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/unarchive` Unarchive Experiment ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Response (application/json) **200** — Unarchive Experiment Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment successfully unarchived." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/experiments/{id}/unarchive" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/experiments/{id}/unarchive", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/unarchive", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/unarchive"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/experiments/{id}/unarchive", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/unarchive")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/unarchive") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Experiment Overrides URL: https://docs.statsig.com/api-reference/experiments/update-experiment-overrides ================================================================================ # Update Experiment Overrides ## Update Experiment Overrides **POST** `/console/v1/experiments/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/overrides` Update Experiment Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | overrides.type | string | Yes | — | Allowed values: gate, segment | | overrides.id | string | Yes | — | The id of the segment or gate | | overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ## Response (application/json) **200** — Update Experiment Overrides Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.overrides | object[] | Yes | — | Array of experiment overrides, each specifying type, ID, and group ID. | | data.overrides.type | string | Yes | — | Allowed values: gate, segment | | data.overrides.id | string | Yes | — | The id of the segment or gate | | data.overrides.groupID | string | Yes | — | The experiment group which user will be forced into | | data.overrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides | object[] | Yes | — | Array of user ID overrides, specifying which users to force into experiment groups. | | data.userIDOverrides.groupID | string | Yes | — | The experiment group the user will be forced into. | | data.userIDOverrides.ids | string[] | Yes | — | Array of user IDs to be assigned to the specified experiment group. | | data.userIDOverrides.environment | string | No | — | Optional environment designation (e.g., production, staging) for the experiment. Constraints: nullable | | data.userIDOverrides.unitType | string | No | — | Optional type of unit for the experiment, defining the scope of the override. Constraints: nullable | ```json { "overrides": [ { "type": "segment", "id": "a_segment", "groupID": "Control" }, { "type": "gate", "id": "a_gate", "groupID": "Test" } ], "userIDOverrides": [ { "groupID": "Control", "ids": [ "updated_control_id_list" ] }, { "groupID": "Test", "ids": [ "updated_test_id_list" ] } ] } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Experiment not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/overrides", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/overrides")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/overrides") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Qualifying Event URL: https://docs.statsig.com/api-reference/experiments-warehouse-native/create-qualifying-event ================================================================================ # Create Qualifying Event ## Create Qualifying Event **POST** `/console/v1/experiments/qualifying_events` Full URL: `https://statsigapi.net/console/v1/experiments/qualifying_events` Create Qualifying Event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | The name of the source, serving as its primary identifier. | | description | string | No | — | An optional description for the source, providing context and details about its purpose and usage. | | tags | string[] | No | — | Optional array of tags to categorize the source, facilitating easier organization and retrieval. | | sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | tableName | string | No | — | The name of the database table if the source type is "table". | | datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | | dryRun | boolean | No | — | Skips persisting the source (used to validate that inputs are correct) | | skip_validation | boolean | No | — | Skips running SQL validation for the source. Requires all_columns and column_types when true. Availability is gated. | | all_columns | string[] | No | — | Column names to persist when skip_validation is true. Optional otherwise. | | column_types | string[] | No | — | Column types aligned with all_columns when skip_validation is true. Optional otherwise. | ## Response (application/json) **201** — Create qualifying event response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | The name of the source, serving as its primary identifier. | | data.description | string | Yes | — | A detailed description of the source, providing context and usage information. | | data.tags | string[] | No | — | Optional tags for categorizing the source and improving searchability. | | data.sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | data.timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | data.timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | data.idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | data.idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | data.sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | data.tableName | string | No | — | The name of the database table if the source type is "table". | | data.datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | data.customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | data.customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | data.customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | data.disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Qualifying event created successfully.", "data": { "name": "test_qualifying_event", "description": "Test description for qualifying event", "tags": [ "non_production" ], "sql": "SELECT * FROM `shoppy-sales.logging.events`", "timestampColumn": "ts", "timestampAsDay": true, "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" } ], "sourceType": "table", "tableName": "shoppy-sales.logging.events" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/qualifying_events" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/qualifying_events", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/qualifying_events", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/qualifying_events"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/qualifying_events", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/qualifying_events")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/qualifying_events") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Qualifying Event URL: https://docs.statsig.com/api-reference/experiments-warehouse-native/delete-qualifying-event ================================================================================ # Delete Qualifying Event ## Delete Qualifying Event **DELETE** `/console/v1/experiments/qualifying_events/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/qualifying_events/{name}` Delete Qualifying Event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Delete Qualifying Event response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Qualifying event deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The qualifying event remains intact until the review is approved and committed. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List qualifying event URL: https://docs.statsig.com/api-reference/experiments-warehouse-native/list-qualifying-event ================================================================================ # List qualifying event ## List qualifying event **GET** `/console/v1/experiments/qualifying_events` Full URL: `https://statsigapi.net/console/v1/experiments/qualifying_events` List qualifying event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List metric source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.name | string | Yes | — | The name of the source, serving as its primary identifier. | | data.description | string | Yes | — | A detailed description of the source, providing context and usage information. | | data.tags | string[] | No | — | Optional tags for categorizing the source and improving searchability. | | data.sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | data.timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | data.timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | data.idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | data.idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | data.sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | data.tableName | string | No | — | The name of the database table if the source type is "table". | | data.datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | data.customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | data.customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | data.customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | data.disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Qualifying events listed successfully.", "data": [ { "name": "Log Events", "description": "all app events including add to cart, purchase, page view, checkout", "tags": [], "sql": "SELECT *\nFROM shoppy-sales.logging.events\nwhere DATE(ts) between {statsig_start_date} and {statsig_end_date}\n", "timestampColumn": "ts", "timestampAsDay": false, "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" }, { "statsigUnitID": "deviceID", "column": "device_id" } ], "tableName": "", "customFieldMapping": [ { "key": "", "formula": "" } ] } ], "pagination": { "itemsPerPage": 1, "pageNumber": 1, "totalItems": 14, "nextPage": "/console/v1/metrics/qualifying_event/list?page=2&limit=1", "previousPage": null, "all": "/console/v1/metrics/qualifying_event/list" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/qualifying_events?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Read Qualifying Event URL: https://docs.statsig.com/api-reference/experiments-warehouse-native/read-qualifying-event ================================================================================ # Read Qualifying Event ## Read Qualifying Event **GET** `/console/v1/experiments/qualifying_events/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/qualifying_events/{name}` Read Qualifying Event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Read Qualifying Event response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | The name of the source, serving as its primary identifier. | | data.description | string | Yes | — | A detailed description of the source, providing context and usage information. | | data.tags | string[] | No | — | Optional tags for categorizing the source and improving searchability. | | data.sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | data.timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | data.timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | data.idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | data.idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | data.sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | data.tableName | string | No | — | The name of the database table if the source type is "table". | | data.datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | data.customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | data.customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | data.customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | data.disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Qualifying event read successfully.", "data": { "name": "test_qualifying_event", "description": "Test description for qualifying event", "tags": [ "non_production" ], "sql": "SELECT * FROM `shoppy-sales.logging.events`", "timestampColumn": "ts", "timestampAsDay": true, "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" } ], "sourceType": "table", "tableName": "shoppy-sales.logging.events" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Update Qualifying Event URL: https://docs.statsig.com/api-reference/experiments-warehouse-native/update-qualifying-event ================================================================================ # Update Qualifying Event ## Update Qualifying Event **POST** `/console/v1/experiments/qualifying_events/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/qualifying_events/{name}` Update Qualifying Event ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | The name of the source cannot be changed in this update, ensuring the identity remains consistent. | | description | string | No | — | An optional updated description for the source, providing additional context or changes. | | tags | string[] | No | — | Optional array of tags for categorizing the source, allowing for updates to its categorization. | | sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | tableName | string | No | — | The name of the database table if the source type is "table". | | datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | | dryRun | boolean | No | — | Skips persisting updates to the source (used to validate that inputs are correct) | | skip_validation | boolean | No | — | Skips running SQL validation for the source. Requires all_columns and column_types when true. Availability is gated. | | all_columns | string[] | No | — | Column names to persist when skip_validation is true. Optional otherwise. | | column_types | string[] | No | — | Column types aligned with all_columns when skip_validation is true. Optional otherwise. | ## Response (application/json) **200** — Update Qualifying Event response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | The name of the source, serving as its primary identifier. | | data.description | string | Yes | — | A detailed description of the source, providing context and usage information. | | data.tags | string[] | No | — | Optional tags for categorizing the source and improving searchability. | | data.sql | string | Yes | — | The SQL query or statement used to extract data from the source. | | data.timestampColumn | string | Yes | — | The name of the column containing timestamp data for the source. | | data.timestampAsDay | boolean | No | — | Indicates whether the timestamp should be treated as a day-level granularity. | | data.idTypeMapping | object[] | Yes | — | Array defining the mapping between Statsig unit IDs and their respective source columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | The identifier mapping for Statsig units. | | data.idTypeMapping.column | string | Yes | — | The corresponding column name in the source that relates to the Statsig unit ID. | | data.sourceType | string | No | — | The type of source, indicating whether it is a database table or a custom query. Allowed values: table, query | | data.tableName | string | No | — | The name of the database table if the source type is "table". | | data.datePartitionColumn | string | No | — | The name of the date partition column if the source type is "table". Can be undefined. | | data.customFieldMapping | object[] | No | — | Optional array defining mappings for custom fields using specific formulas. | | data.customFieldMapping.key | string | Yes | — | The identifier for the custom field mapping. | | data.customFieldMapping.formula | string | Yes | — | The formula or expression used to compute the custom field value. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.isVerified | boolean | No | false | Marks the metric source as verified, indicating trustworthiness within the organization. | | data.disableCURE | boolean | No | — | Disable CURE for all metrics built from this metric source | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the metric source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the metric source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Qualifying event updated successfully.", "data": { "name": "test_qualifying_event", "description": "Test description for qualifying event", "tags": [ "non_production" ], "sql": "SELECT * FROM `shoppy-sales.logging.events`", "timestampColumn": "ts", "timestampAsDay": true, "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" } ], "sourceType": "table", "tableName": "shoppy-sales.logging.events" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/qualifying_events/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/qualifying_events/{name}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Pulse Load (Warehouse Native) URL: https://docs.statsig.com/api-reference/experiments/cancel-pulse-load-warehouse-native ================================================================================ # Cancel Pulse Load (Warehouse Native) ## Cancel Pulse Load (Warehouse Native) **POST** `/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel` Cancel Pulse Load (Warehouse Native) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | | dagID (path) | string | Yes | — | dagID | ## Response (application/json) **200** — Cancel Pulse Load Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Pulse load cancelled successfully." } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Pulse load history not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}/cancel") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Assignment Source URL: https://docs.statsig.com/api-reference/experiments/create-assignment-source ================================================================================ # Create Assignment Source ## Create Assignment Source **POST** `/console/v1/experiments/assignment_sources` Full URL: `https://statsigapi.net/console/v1/experiments/assignment_sources` Create Assignment Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Unique identifier for the assignment source. | | description | string | No | — | Optional detailed context for the assignment source. | | isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | tags | string[] | No | — | Optional tags for categorization. | | sql | string | Yes | — | SQL query defining the data source for assignments. | | timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | | dryRun | boolean | No | — | Skips persisting the assignment source (used to validate that inputs are correct) | ## Response (application/json) **201** — Create Assignment Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the assignment source. | | data.description | string | Yes | — | Detailed context and purpose of the assignment source. | | data.isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source for assignments. | | data.timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | data.experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | data.groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | data.groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | ```json { "message": "Assignment Source created successfully", "data": { "name": "exposures4", "description": "", "tags": [], "sql": "SELECT * FROM shoppy-sales.experiment_data.exposures", "timestampColumn": "ts", "groupIDColumn": "group_id", "experimentIDColumn": "experiment_name", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/assignment_sources" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/assignment_sources", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/assignment_sources", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/assignment_sources"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/assignment_sources", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/assignment_sources")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/assignment_sources") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Entity Property Source URL: https://docs.statsig.com/api-reference/experiments/create-entity-property-source ================================================================================ # Create Entity Property Source ## Create Entity Property Source **POST** `/console/v1/experiments/entity_properties` Full URL: `https://statsigapi.net/console/v1/experiments/entity_properties` Create Entity Property Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | Unique identifier for the entity property source. | | description | string | No | — | Optional detailed context for the entity property source. | | tags | string[] | No | — | Optional tags for categorization. | | sql | string | Yes | — | SQL query defining the data source. | | timestampColumn | string | No | — | Optional column name for timestamp. | | timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | dryRun | boolean | No | — | Skips persisting the entity property source (used to validate that inputs are correct) | ## Response (application/json) **201** — Create Entity Property Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the entity property source. | | data.description | string | Yes | — | Detailed context and purpose of the entity property source. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source. | | data.timestampColumn | string | No | — | Optional column name for timestamp. | | data.timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Entity Property Source created successfully", "data": { "name": "Location", "description": "", "tags": [], "sql": "SELECT * FROM shoppy-sales.setup.user_properties", "timestampColumn": "timestamp", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ], "timestampAsDay": true } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/entity_properties" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/entity_properties", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_properties", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_properties"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/entity_properties", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_properties")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_properties") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Assignment Source URL: https://docs.statsig.com/api-reference/experiments/delete-assignment-source ================================================================================ # Delete Assignment Source ## Delete Assignment Source **DELETE** `/console/v1/experiments/assignment_source/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/assignment_source/{name}` Delete Assignment Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Name of the assignment source | ## Response (application/json) **200** — Delete Assignment Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Assignment source deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The entity remains intact until the existing review workflow applies the deletion. Returns the review ID and status. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **400** — Assignment source is referenced by active experiments. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/assignment_source/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/assignment_source/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/assignment_source/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/assignment_source/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/assignment_source/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Delete Entity Property Source URL: https://docs.statsig.com/api-reference/experiments/delete-entity-property-source ================================================================================ # Delete Entity Property Source ## Delete Entity Property Source **DELETE** `/console/v1/experiments/entity_property/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/entity_property/{name}` Delete Entity Property Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Response (application/json) **200** — Delete Entity Property Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Entity property source deleted successfully." } ``` **201** — Creates a deletion review when review enforcement applies. The entity remains intact until the existing review workflow applies the deletion. Returns the review ID and status. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | ID of the deletion review. | | data.status | string | Yes | — | Review status. Creating the review does not delete the entity. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | The proposed action. Allowed values: delete | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "delete" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/experiments/entity_property/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/experiments/entity_property/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_property/{name}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_property/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/experiments/entity_property/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_property/{name}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_property/{name}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Entity Property Source URL: https://docs.statsig.com/api-reference/experiments/get-entity-property-source ================================================================================ # Get Entity Property Source ## Get Entity Property Source **GET** `/console/v1/experiments/entity_property/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/entity_property/{name}` Get Entity Property Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Name of entity property source | ## Response (application/json) **200** — Get Entity Property Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the entity property source. | | data.description | string | Yes | — | Detailed context and purpose of the entity property source. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source. | | data.timestampColumn | string | No | — | Optional column name for timestamp. | | data.timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Entity Property Source read successfully.", "data": { "name": "Location", "description": "This is the the location description", "tags": [], "sql": "SELECT * FROM shoppy-sales.setup.user_properties", "timestampColumn": "timestamp", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ], "timestampAsDay": true } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/entity_property/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/entity_property/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_property/{name}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_property/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/entity_property/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_property/{name}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_property/{name}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Get Pulse Load History Details (Warehouse Native) URL: https://docs.statsig.com/api-reference/experiments/get-pulse-load-history-details-warehouse-native ================================================================================ # Get Pulse Load History Details (Warehouse Native) ## Get Pulse Load History Details (Warehouse Native) **GET** `/console/v1/experiments/{id}/pulse_load_history/{dagID}` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}` Get Pulse Load History Details (Warehouse Native) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | | dagID (path) | string | Yes | — | dagID | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | fields (query) | string[] | No | — | Comma-separated list of job fields to return (sparse fieldset), e.g. `jobType,jobIDs,startTime,endTime`. `jobType` is always included. Leave out `sql` to keep the response small for DAGs with many jobs. When `fields` is not set, every job field is returned. | ## Response (application/json) **200** — Get Pulse Load History Details | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.dagID | string | Yes | — | — | | data.jobs | object[] | Yes | — | — | | data.jobs.jobType | string | Yes | — | The Echidna job type. | | data.jobs.jobIDs | string[] | Yes | — | Warehouse execution IDs for this job. | | data.jobs.startTime | number | Yes | — | Unix timestamp in milliseconds when this job started. Constraints: nullable | | data.jobs.endTime | number | Yes | — | Unix timestamp in milliseconds when this job ended, when available. Constraints: nullable | | data.jobs.sql | string | Yes | — | The SQL executed for this job. Constraints: nullable | | data.jobs.metricSourceName | string | No | — | Present for user-metrics style jobs and names the metric source used by the job. Constraints: nullable | | data.jobs.rollup | string | No | — | Present for pulse-style jobs and indicates the rollup used for the calculation. Constraints: nullable Allowed values: 7, 14, 28, cumulative, dx, daily, pre_exposure | ```json { "message": "Pulse load history read successfully.", "data": { "dagID": "dag_123", "jobs": [ { "jobType": "user_metrics", "jobIDs": [ "01af9f89-b55d-4d5a-80a6-410d5bd5d04d" ], "startTime": 1718042400000, "endTime": 1718046000000, "sql": "select * from metric_source_table", "metricSourceName": "Warehouse Metrics" }, { "jobType": "pulse", "jobIDs": [ "01af9f89-b55d-4d5a-80a6-410d5bd5d04e", "01af9f89-b55d-4d5a-80a6-410d5bd5d04f" ], "startTime": 1718046000000, "endTime": 1718047200000, "sql": "select * from pulse_rollup_table", "rollup": "daily" } ] } } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Pulse load history not found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history/{dagID}") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Assignment Sources URL: https://docs.statsig.com/api-reference/experiments/list-assignment-sources ================================================================================ # List Assignment Sources ## List Assignment Sources **GET** `/console/v1/experiments/assignment_sources` Full URL: `https://statsigapi.net/console/v1/experiments/assignment_sources` List Assignment Sources ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Assignment Sources response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the assignment source. | | data.description | string | Yes | — | Detailed context and purpose of the assignment source. | | data.isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source for assignments. | | data.timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | data.experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | data.groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | data.groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Entity Property Sources listed successfully.", "data": [ { "name": "Exposures", "description": "", "tags": [], "sql": "SELECT * FROM shoppy-sales.experiment_data.exposures", "timestampColumn": "ts", "groupIDColumn": "group_id", "experimentIDColumn": "experiment_name", "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" }, { "statsigUnitID": "deviceID", "column": "device_id" } ] } ], "pagination": { "itemsPerPage": 1, "pageNumber": 1, "totalItems": 13, "nextPage": "/console/v1/experiments/assignment_sources?page=2&limit=1", "previousPage": null, "all": "/console/v1/experiments/assignment_sources" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/assignment_sources?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List Entity Property Sources URL: https://docs.statsig.com/api-reference/experiments/list-entity-property-sources ================================================================================ # List Entity Property Sources ## List Entity Property Sources **GET** `/console/v1/experiments/entity_properties` Full URL: `https://statsigapi.net/console/v1/experiments/entity_properties` List Entity Property Sources ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Entity Property Sources response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the entity property source. | | data.description | string | Yes | — | Detailed context and purpose of the entity property source. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source. | | data.timestampColumn | string | No | — | Optional column name for timestamp. | | data.timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Entity Property Sourcess listed successfully.", "data": [ { "name": "Segmentation Models", "description": "", "tags": [ "★ Core", "Growth" ], "sql": "SELECT\n user_id, ds, spend_segment\nFROM shoppy-sales.setup.segments", "timestampColumn": "ds", "timestampAsDay": true, "idTypeMapping": [ { "statsigUnitID": "userID", "column": "user_id" } ] } ], "pagination": { "itemsPerPage": 1, "pageNumber": 1, "totalItems": 5, "nextPage": "/console/v1/experiments/entity_properties?page=2&limit=1", "previousPage": null, "all": "/console/v1/experiments/entity_properties" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_properties?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Load Pulse (Warehouse Native) URL: https://docs.statsig.com/api-reference/experiments/load-pulse-warehouse-native ================================================================================ # Load Pulse (Warehouse Native) ## Load Pulse (Warehouse Native) **POST** `/console/v1/experiments/{id}/load_pulse` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/load_pulse` Load Pulse (Warehouse Native) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | refresh (query) | string | No | full | Allowed values: full, incremental, metric | | metricIDs (query) | string[] | No | — | — | | turboMode (query) | boolean | No | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | refresh | string | No | full | Allowed values: full, incremental, metric | | metricIDs | string[] | No | — | — | | turboMode | boolean | No | — | — | ## Response (application/json) **200** — Load Pulse Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Experiment is loading." } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/load_pulse?refresh=full") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Patch Assignment Source URL: https://docs.statsig.com/api-reference/experiments/patch-assignment-source ================================================================================ # Patch Assignment Source ## Patch Assignment Source **PATCH** `/console/v1/experiments/assignment_source/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/assignment_source/{name}` Patch Assignment Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Name of the assignment source | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Unique identifier for the assignment source. | | description | string | No | — | Detailed context and purpose of the assignment source. | | isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | tags | string[] | No | — | Tags for categorization and search. | | sql | string | No | — | SQL query defining the data source for assignments. | | timestampColumn | string | No | — | Column name representing the timestamp of assignments. | | experimentIDColumn | string | No | — | Column name for the experiment ID associated with the assignments. | | groupIDColumn | string | No | — | Column name for the group ID linked to the assignments. | | groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | idTypeMapping | object[] | No | — | Mappings of Statsig units to their respective columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | | dryRun | boolean | No | — | Skips persisting the assignment source (used to validate that inputs are correct) | ## Response (application/json) **200** — Patch Assignment Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the assignment source. | | data.description | string | Yes | — | Detailed context and purpose of the assignment source. | | data.isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source for assignments. | | data.timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | data.experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | data.groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | data.groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | ```json { "message": "Assignment Source updated successfully", "data": { "name": "exposures3", "description": "qweqwe", "tags": [], "sql": "SELECT * FROM shoppy-sales.experiment_data.exposures", "timestampColumn": "ts", "groupIDColumn": "group_id", "experimentIDColumn": "experiment_name", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/experiments/assignment_source/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/assignment_source/{name}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/assignment_source/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/assignment_source/{name}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/assignment_source/{name}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Patch Entity Property Source URL: https://docs.statsig.com/api-reference/experiments/patch-entity-property-source ================================================================================ # Patch Entity Property Source ## Patch Entity Property Source **PATCH** `/console/v1/experiments/entity_property/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/entity_property/{name}` Patch Entity Property Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Name of entity property source | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Unique identifier for the entity property source. | | description | string | No | — | Detailed context and purpose of the entity property source. | | tags | string[] | No | — | Tags for categorization and search. | | sql | string | No | — | SQL query defining the data source | | timestampColumn | string | No | — | Optional column name for timestamp. | | timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | idTypeMapping | object[] | No | — | Mappings of Statsig units to their columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | dryRun | boolean | No | — | Skips persisting the entity property source (used to validate that inputs are correct) | ## Response (application/json) **200** — Patch Entity Property Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the entity property source. | | data.description | string | Yes | — | Detailed context and purpose of the entity property source. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source. | | data.timestampColumn | string | No | — | Optional column name for timestamp. | | data.timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Entity Property Source updated successfully", "data": { "name": "Location", "description": "This is the the location description", "tags": [], "sql": "SELECT * FROM shoppy-sales.setup.user_properties", "timestampColumn": "timestamp", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ], "timestampAsDay": true } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/experiments/entity_property/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/experiments/entity_property/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_property/{name}", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_property/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/experiments/entity_property/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_property/{name}")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_property/{name}") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Post Assignment Source URL: https://docs.statsig.com/api-reference/experiments/post-assignment-source ================================================================================ # Post Assignment Source ## Post Assignment Source **POST** `/console/v1/experiments/assignment_source/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/assignment_source/{name}` Post Assignment Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | Name of the assignment source | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Optional new name for the assignment source. | | description | string | No | — | Optional updated context for the assignment source. | | isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | tags | string[] | No | — | Optional updated tags for categorization. | | sql | string | Yes | — | SQL query defining the data source for assignments. | | timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | owner.ownerID | string | No | abc123 | ID of the owner | | owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | | dryRun | boolean | No | — | Skips persisting the assignment source (used to validate that inputs are correct) | ## Response (application/json) **200** — Post Assignment Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the assignment source. | | data.description | string | Yes | — | Detailed context and purpose of the assignment source. | | data.isVerified | boolean | No | — | Marks the assignment source as verified for internal trustworthiness. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source for assignments. | | data.timestampColumn | string | Yes | — | Column name representing the timestamp of assignments. | | data.experimentIDColumn | string | Yes | — | Column name for the experiment ID associated with the assignments. | | data.groupIDColumn | string | Yes | — | Column name for the group ID linked to the assignments. | | data.groupNameColumn | string | No | — | Optional column name for the group name linked to the assignments. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their respective columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name associated with the ID type mapping. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the assignment source, aiding in accountability and management. Constraints: nullable | | data.scheduledReloadHour | integer | No | — | Optional field indicating what UTC hour to run a scheduled scan for the assignment source. Constraints: format: int64, nullable, min: 0, max: 23 | ```json { "message": "Assignment Source updated successfully", "data": { "name": "exposures3", "description": "qweqwe", "tags": [], "sql": "SELECT * FROM shoppy-sales.experiment_data.exposures", "timestampColumn": "ts", "groupIDColumn": "group_id", "experimentIDColumn": "experiment_name", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ] } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/assignment_source/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/assignment_source/{name}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/assignment_source/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/assignment_source/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/assignment_source/{name}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/assignment_source/{name}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Post Entity Property Source URL: https://docs.statsig.com/api-reference/experiments/post-entity-property-source ================================================================================ # Post Entity Property Source ## Post Entity Property Source **POST** `/console/v1/experiments/entity_property/{name}` Full URL: `https://statsigapi.net/console/v1/experiments/entity_property/{name}` Post Entity Property Source ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name (path) | string | Yes | — | name | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | Optional new name for the entity property source. | | description | string | No | — | Optional updated context for the entity property source. | | tags | string[] | No | — | Optional updated tags for categorization. | | sql | string | Yes | — | SQL query defining the data source. | | timestampColumn | string | No | — | Optional column name for timestamp. | | timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | dryRun | boolean | No | — | Skips persisting the entity property source (used to validate that inputs are correct) | ## Response (application/json) **200** — Post Entity Property Source response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.name | string | Yes | — | Unique identifier for the entity property source. | | data.description | string | Yes | — | Detailed context and purpose of the entity property source. | | data.tags | string[] | Yes | — | Tags for categorization and search. | | data.sql | string | Yes | — | SQL query defining the data source. | | data.timestampColumn | string | No | — | Optional column name for timestamp. | | data.timestampAsDay | boolean | No | — | Indicates if the timestamp is treated as a day. | | data.idTypeMapping | object[] | Yes | — | Mappings of Statsig units to their columns. | | data.idTypeMapping.statsigUnitID | string | Yes | — | ID for the Statsig unit. | | data.idTypeMapping.column | string | Yes | — | Column name linked to the ID. | | data.isReadOnly | boolean | No | — | Specifies if the source can only be edited via the Console API. | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.team | string | No | — | Optional field indicating the team name responsible for the entity property source, aiding in accountability and management. Constraints: nullable | | data.teamID | string | No | — | Optional field indicating the team ID responsible for the entity property source, aiding in accountability and management. Constraints: nullable | ```json { "message": "Entity Property Sources updated successfully.", "data": { "name": "Location", "description": "This is the the location description", "tags": [], "sql": "SELECT * FROM shoppy-sales.setup.user_properties", "timestampColumn": "", "idTypeMapping": [ { "statsigUnitID": "stableID", "column": "user_id" } ], "timestampAsDay": true } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` **404** — Not Found. The requested resource could not be found. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 404 | | message | string | Yes | — | — | ```json { "status": 404, "message": "Not Found. The requested resource could not be found." } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/experiments/entity_property/{name}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/experiments/entity_property/{name}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/entity_property/{name}", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/entity_property/{name}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/experiments/entity_property/{name}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/entity_property/{name}")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/entity_property/{name}") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Pulse Load History (Warehouse Native) URL: https://docs.statsig.com/api-reference/experiments/pulse-load-history-warehouse-native ================================================================================ # Pulse Load History (Warehouse Native) ## Pulse Load History (Warehouse Native) **GET** `/console/v1/experiments/{id}/pulse_load_history` Full URL: `https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history` Pulse Load History (Warehouse Native) ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List Pulse Load History | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.creatorName | string | No | — | — | | data.createdTime | number | Yes | — | Constraints: format: double | | data.finishedTime | number | No | — | Constraints: format: double | | data.finishedState | string | No | — | Allowed values: success, failure, partial_failure, cancelled, timeout | | data.startDs | string | Yes | — | — | | data.endDs | string | Yes | — | — | | data.reloadType | string | Yes | — | Allowed values: incremental, full, metric | | data.turboMode | boolean | Yes | — | — | | data.dagID | string | Yes | — | — | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "string", "data": [ { "creatorName": "string", "createdTime": 0, "finishedTime": 0, "finishedState": "success", "startDs": "string", "endDs": "string", "reloadType": "incremental", "turboMode": true, "dagID": "string" } ], "pagination": { "itemsPerPage": 0, "pageNumber": 0, "nextPage": "string", "previousPage": "string", "totalItems": 0, "all": "string" } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "Invalid request. Please check the request input and try again." } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/experiments/{id}/pulse_load_history?limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # List warehouse export status URL: https://docs.statsig.com/api-reference/exports/list-warehouse-export-status ================================================================================ # List warehouse export status ## List warehouse export status **GET** `/console/v1/exports/status` Full URL: `https://statsigapi.net/console/v1/exports/status` List warehouse export status Returns daily warehouse export runs for this project. A missing date means the job did not run or exported 0 rows that day. Prefer this over GET /console/v1/ingestion/status for export_exposures / export_events. ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | startDate (query) | string | Yes | 2026-09-16 | Inclusive start date (YYYY-MM-DD, UTC). Must be a real calendar date. Range with endDate cannot exceed 90 days. | | endDate (query) | string | Yes | 2026-09-23 | Inclusive end date (YYYY-MM-DD, UTC). Must be a real calendar date and >= startDate. Range cannot exceed 90 days. | | dataset (query) | string | No | — | Warehouse export dataset. Omit to return both exposures and events. A missing day is either not run or exported 0 rows that day. Allowed values: exposures, events | | status (query) | string | No | — | Uses the same rule as each row. success = ROWS_INSERTED/FILE_CREATED/%Other, or any unknown code that does not contain "error". failed = ERROR/EXPORT_ERROR/INTERNAL_SERVER_ERROR, or any unknown code that contains "error". Allowed values: success, failed | | limit (query) | integer | No | 10 | Results per page Constraints: string, number | | page (query) | integer | No | 1 | Page number Constraints: string, number | ## Response (application/json) **200** — List export status success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object[] | Yes | — | — | | data.date | string | Yes | 2026-09-21 | Export date stamp (YYYY-MM-DD, UTC). | | data.dataset | string | Yes | — | Allowed values: exposures, events | | data.destination | object | Yes | — | — | | data.destination.type | string | Yes | athena | Warehouse family derived from the stored integration type (athena-echidna → athena, s3-export → s3). Constraints: nullable | | data.status | string | Yes | — | Allowed values: success, failed | | data.status_code | string | Yes | ERROR | Raw pipeline status (ROWS_INSERTED, ERROR, EXPORT_ERROR, …). | | data.rows_exported | number | No | — | Constraints: format: double | | data.message | string | Yes | — | Customer-safe sentence from ExportJobStatusNotificationHandler. Never includes rawMessage. Constraints: nullable | | data.reported_at | string | Yes | — | Constraints: format: date-time, nullable | | pagination | object | Yes | — | Pagination metadata for checking if there is next page for example. | | pagination.itemsPerPage | number | Yes | — | Constraints: format: double | | pagination.pageNumber | number | Yes | — | Constraints: format: double | | pagination.nextPage | string | Yes | — | Constraints: nullable | | pagination.previousPage | string | Yes | — | Constraints: nullable | | pagination.totalItems | number | No | — | Constraints: format: double | | pagination.all | string | No | — | — | ```json { "message": "Export statuses listed successfully.", "data": [ { "date": "2026-09-21", "dataset": "exposures", "destination": { "type": "athena" }, "status": "failed", "status_code": "ERROR", "message": "Your Athena export_exposures export for 2026-09-21 failed. There was an error exporting exposures to your Athena warehouse: TABLE_NOT_FOUND: table exposures does not exist", "reported_at": "2026-09-21T00:00:00.000Z" } ], "pagination": { "itemsPerPage": 10, "pageNumber": 1, "nextPage": null, "previousPage": null, "totalItems": 1 } } ``` **400** — Invalid request. Please check the request input and try again. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 400 | | message | string | Yes | — | — | ```json { "status": 400, "message": "expected valid date in the form of YYYY-MM-DD, received: not-a-date" } ``` **401** — This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | status | integer | Yes | — | Allowed values: 401 | | message | string | Yes | — | — | ```json { "status": 401, "message": "This endpoint only accepts an active CONSOLE key, but an invalid key was sent. Key: console-xxxXXXxxxXXXxxx" } ``` ## Code samples ### cURL ```bash curl -X GET "https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.get( "https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1", { method: "GET", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("GET", "https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1")) .method("GET", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/exports/status?startDate=2026-09-16&endDate=2026-09-23&limit=10&page=1") request = Net::HTTP::Get.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Add Gate Overrides URL: https://docs.statsig.com/api-reference/gates/add-gate-overrides ================================================================================ # Add Gate Overrides ## Add Gate Overrides **PATCH** `/console/v1/gates/{id}/overrides` Full URL: `https://statsigapi.net/console/v1/gates/{id}/overrides` Add Gate Overrides ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | environmentOverrides | object[] | No | — | — | | environmentOverrides.environment | string | No | staging | Environment Constraints: nullable | | environmentOverrides.unitID | string | Yes | unit123 | Unit ID Constraints: nullable | | environmentOverrides.passingIDs | string[] | Yes | ["id1","id2"] | List of passing IDs | | environmentOverrides.failingIDs | string[] | Yes | ["id3","id4"] | List of failing IDs | | passingUserIDs | string[] | No | ["user123","user456","user789"] | List of user IDs | | failingUserIDs | string[] | No | ["user123","user456","user789"] | List of user IDs | | passingCustomIDs | string[] | No | ["custom123","custom456"] | Optional list of custom IDs | | failingCustomIDs | string[] | No | ["custom123","custom456"] | Optional list of custom IDs | ## Response (application/json) **201** — Add Gate Override Success | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | Contract for overrides | | data.passingUserIDs | string[] | Yes | ["user123","user456","user789"] | List of user IDs | | data.failingUserIDs | string[] | Yes | ["user123","user456","user789"] | List of user IDs | | data.passingCustomIDs | string[] | No | ["custom123","custom456"] | Optional list of custom IDs | | data.failingCustomIDs | string[] | No | ["custom123","custom456"] | Optional list of custom IDs | | data.environmentOverrides | object[] | Yes | — | — | | data.environmentOverrides.environment | string | No | staging | Environment Constraints: nullable | | data.environmentOverrides.unitID | string | Yes | unit123 | Unit ID Constraints: nullable | | data.environmentOverrides.passingIDs | string[] | Yes | ["id1","id2"] | List of passing IDs | | data.environmentOverrides.failingIDs | string[] | Yes | ["id3","id4"] | List of failing IDs | ```json { "passingUserIDs": [ "passing-user" ], "failingUserIDs": [ "failing-user" ] } ``` ## Code samples ### cURL ```bash curl -X PATCH "https://statsigapi.net/console/v1/gates/{id}/overrides" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.patch( "https://statsigapi.net/console/v1/gates/{id}/overrides", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/overrides", { method: "PATCH", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/overrides"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PATCH", "https://statsigapi.net/console/v1/gates/{id}/overrides", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/overrides")) .method("PATCH", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/overrides") request = Net::HTTP::Patch.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Add Gate Rule URL: https://docs.statsig.com/api-reference/gates/add-gate-rule ================================================================================ # Add Gate Rule ## Add Gate Rule **POST** `/console/v1/gates/{id}/rule` Full URL: `https://statsigapi.net/console/v1/gates/{id}/rule` Add Gate Rule ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeArchiveMetadata (query) | string | No | — | When "true", populate archivedAt / archivedBy* / archiveReason on the gate when it is currently archived. When omitted or "false", those fields are absent from the response. Allowed values: true, false | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | Yes | — | The name of this rule. | | passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: format: double, min: 0, max: 100 | | conditions | object[] | Yes | — | An array of Condition objects. | | conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | conditions.field | string | No | — | Constraints: nullable | | conditions.customID | string | No | — | Constraints: nullable | | conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | id | string | No | — | The Statsig ID of this rule. | | baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | returnValue | object | No | — | The return value of the rule. | | completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | completedAutomatedRollouts.time | number | No | — | — | | completedAutomatedRollouts.passPercent | number | Yes | — | — | | completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | pendingAutomatedRollouts.time | number | No | — | — | | pendingAutomatedRollouts.passPercent | number | Yes | — | — | | pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | safeguard.guardrailAlerts | string[] | Yes | — | — | | safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: format: int64, nullable | ## Response (application/json) **200** — Add Gate Rule Response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The gate display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | — | — | | data.description | string | Yes | — | Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | — | — | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Constraints: nullable | | data.teamID | string | No | — | Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.checksPerHour | number | Yes | — | Constraints: format: double, nullable | | data.status | string | Yes | — | Allowed values: In Progress, Launched, Disabled, Archived | | data.type | string | Yes | — | Allowed values: TEMPORARY, PERMANENT, STALE, TEMPLATE | | data.typeReason | string | Yes | — | Allowed values: NONE, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED, STALE_PROBABLY_FORGOTTEN, STALE_NO_RULES, STALE_PROBABLY_DEAD_CHECK, STALE_EMPTY_CHECKS, STALE_ALL_TRUE, STALE_ALL_FALSE | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.isTemplate | boolean | No | — | — | | data.store0100Exposures | boolean | No | — | Whether this gate stores 0/100 exposures for monitoring/analysis. | | data.permalink | string | Yes | — | A permalink to this gate in the Statsig Console. Constraints: format: uri | | data.archivedAt | number | No | — | Timestamp (ms) of the most recent archive event when the gate is currently archived; null otherwise. May be null for gates archived before audit logging existed. Constraints: format: double, nullable | | data.archivedByID | string | No | — | ID of the user who archived this gate, when known and the gate is currently archived; null otherwise (e.g. automated archives have no user). Constraints: nullable | | data.archivedByName | string | No | — | Name of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archivedByEmail | string | No | — | Email of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archiveReason | string | No | — | Free-text reason supplied when the gate was most recently archived; null when the gate is not currently archived or no reason was given. Constraints: nullable | | data.isEnabled | boolean | Yes | — | — | | data.rules | object[] | Yes | — | — | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | The return value of the rule. | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.measureMetricLifts | boolean | No | — | — | | data.monitoringMetrics | object[] | No | — | — | | data.monitoringMetrics.name | string | Yes | — | — | | data.monitoringMetrics.type | string | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.releasePipelineID | string | No | — | Constraints: nullable | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | ```json { "message": "Gate rules added successfully.", "data": { "id": "gate1", "name": "gate1", "description": "", "idType": "userID", "lastModifierID": "65pqqzT46Kl7lHnd2JCmgH", "lastModifiedTime": 1721435847251, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "3exemrfZ5pwOk6qyDH0dhP", "createdTime": 1721242681598, "creatorName": "Jathu Theivikaran", "creatorEmail": "jathurshan@statsig.com", "targetApps": [], "holdoutIDs": [], "tags": [], "team": null, "isEnabled": true, "status": "In Progress", "rules": [ { "id": "LcDWo6mFrWaS3DtoKtEAfg1", "baseID": "LcDWo6mFrWaS3DtoKtEAfg1", "name": "NA", "passPercentage": 90, "conditions": [ { "type": "country", "targetValue": [ "CA" ], "operator": "any" } ], "environments": null }, { "id": "1RoFk5jjnNpF2HZD5oQOeY", "baseID": "1RoFk5jjnNpF2HZD5oQOeY", "name": "NA2", "passPercentage": 80, "conditions": [ { "type": "country", "targetValue": [ "US" ], "operator": "any" } ], "environments": null } ], "checksPerHour": 0, "type": "TEMPORARY", "typeReason": "NONE", "reviewSettings": { "requiredReview": false, "allowedReviewers": [] }, "measureMetricLifts": true } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/gates/{id}/rule" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/gates/{id}/rule", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/rule", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/rule"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/gates/{id}/rule", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/rule")) .method("POST", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/rule") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Approve Gate Review URL: https://docs.statsig.com/api-reference/gates/approve-gate-review ================================================================================ # Approve Gate Review ## Approve Gate Review **PUT** `/console/v1/gates/{id}/reviews/{reviewID}/approve` Full URL: `https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve` Approve Gate Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | reason | string | No | — | Optional comment recorded with the approval. Constraints: max length: 2000 | ## Response (application/json) **200** — The approved gate review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.proposed.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.proposed.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.proposed.schema | string | No | — | Constraints: nullable | | data.content.proposed.monitoring_metrics | object[] | No | — | — | | data.content.proposed.monitoring_metrics.name | string | Yes | — | — | | data.content.proposed.monitoring_metrics.type | string | Yes | — | — | | data.content.proposed.monitoring_metric_tags | object[] | No | — | — | | data.content.proposed.monitoring_metric_tags.id | string | Yes | — | — | | data.content.proposed.real_time_metrics | object[] | No | — | — | | data.content.proposed.real_time_metrics.name | string | Yes | — | — | | data.content.proposed.real_time_metrics.type | string | Yes | — | — | | data.content.proposed.overrides | object | No | — | — | | data.content.proposed.overrides.id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.proposed.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.proposed.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.unavailable_reason | string | No | — | Present ONLY when the change could not be read back, in which case `current` and `proposed` are both empty objects and carry no meaning. This exists so that "this review type has nothing to propose" (`content: null`) is never confused with "we could not tell you what this review would do". `snapshot_not_found`: the review's snapshot no longer exists — expected for old reviews, whose snapshots are pruned as the config accumulates newer ones. `snapshot_unreadable`: the snapshot exists but could not be read or serialized; that is a server-side fault and is logged. Allowed values: snapshot_not_found, snapshot_unreadable | ```json { "message": "string", "data": { "review_id": "string", "status": "pending", "type": "rules", "author": { "id": "string", "email": "string" }, "reviewers": [ { "id": "string", "kind": "user" } ], "description": "string", "created_at": "string", "content": { "type": "rules", "current": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "proposed": { "rules": [ { "name": "string", "passPercentage": 0, "conditions": [ { "targetValue": [ null ], "operator": "any", "field": "string", "customID": "string", "type": "app_version" } ], "environments": [ "string" ], "id": "string", "baseID": "string", "returnValue": {}, "completedAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "pendingAutomatedRollouts": [ { "time": 0, "passPercent": 0, "phaseDurationMs": 0 } ], "safeguard": { "alertAction": "rollback_to_0", "guardrailAlerts": [ "string" ], "toplineAlerts": [ "string" ], "toplineEvaluationPeriodInMs": 0, "manualEvaluationRenewalTimeInMs": 0 }, "returnValueJson5": "string", "variants": [ { "id": "string", "name": "string", "passPercentage": 0, "returnValue": {}, "returnValueJson5": "string" } ] } ], "is_enabled": true, "default_value": null, "is_launched": true, "launched_payload": null, "default_value_gradual_rollout": { "id": "string", "target_value": null, "percentage_pass": 0, "salt": "string", "rollouts": [ { "time": 0, "pass_percent": 0, "is_complete": true } ] }, "salt": "string", "description": "string", "show_dev_rules": true, "show_staging_rules": true, "subscribers": [ { "type": "string", "id": "string" } ], "analytics_enabled": true, "scheduled_reload": { "hour": 0, "days": [ 0 ], "reload_type": "incremental", "turbo_mode": true }, "is_archived": true, "id_type": "string", "secondary_id_type": "string", "identity_resolution_source_id": "string", "target_app_ids": [ "string" ], "owners": [ { "owner_id": "string", "owner_type": "string" } ], "team_id": "string", "allow_self_approval": true, "release_pipeline_id": "string", "allowed_reviewers": { "user_ids": [ "string" ], "group_ids": [ "string" ] }, "schema": "string", "monitoring_metrics": [ { "name": "string", "type": "string" } ], "monitoring_metric_tags": [ { "id": "string" } ], "real_time_metrics": [ { "name": "string", "type": "string" } ], "overrides": { "id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ], "custom_id_overrides": [ { "ids": [ "string" ], "groupID": "string", "environment": "string", "unitID": "string" } ] } }, "unavailable_reason": "snapshot_not_found" } } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/approve") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Archive Gate URL: https://docs.statsig.com/api-reference/gates/archive-gate ================================================================================ # Archive Gate ## Archive Gate **PUT** `/console/v1/gates/{id}/archive` Full URL: `https://statsigapi.net/console/v1/gates/{id}/archive` Archive Gate ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | id | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeArchiveMetadata (query) | string | No | — | When "true", populate archivedAt / archivedBy* / archiveReason on the gate when it is currently archived. When omitted or "false", those fields are absent from the response. Allowed values: true, false | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | forceArchive | boolean | No | — | — | | archiveReason | string | No | The gate is no longer needed | The reason for archiving the gate | ## Response (application/json) **200** — Archive gate response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The gate display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | — | — | | data.description | string | Yes | — | Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | — | — | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Constraints: nullable | | data.teamID | string | No | — | Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.checksPerHour | number | Yes | — | Constraints: format: double, nullable | | data.status | string | Yes | — | Allowed values: In Progress, Launched, Disabled, Archived | | data.type | string | Yes | — | Allowed values: TEMPORARY, PERMANENT, STALE, TEMPLATE | | data.typeReason | string | Yes | — | Allowed values: NONE, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED, STALE_PROBABLY_FORGOTTEN, STALE_NO_RULES, STALE_PROBABLY_DEAD_CHECK, STALE_EMPTY_CHECKS, STALE_ALL_TRUE, STALE_ALL_FALSE | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.isTemplate | boolean | No | — | — | | data.store0100Exposures | boolean | No | — | Whether this gate stores 0/100 exposures for monitoring/analysis. | | data.permalink | string | Yes | — | A permalink to this gate in the Statsig Console. Constraints: format: uri | | data.archivedAt | number | No | — | Timestamp (ms) of the most recent archive event when the gate is currently archived; null otherwise. May be null for gates archived before audit logging existed. Constraints: format: double, nullable | | data.archivedByID | string | No | — | ID of the user who archived this gate, when known and the gate is currently archived; null otherwise (e.g. automated archives have no user). Constraints: nullable | | data.archivedByName | string | No | — | Name of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archivedByEmail | string | No | — | Email of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archiveReason | string | No | — | Free-text reason supplied when the gate was most recently archived; null when the gate is not currently archived or no reason was given. Constraints: nullable | | data.isEnabled | boolean | Yes | — | — | | data.rules | object[] | Yes | — | — | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | The return value of the rule. | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.measureMetricLifts | boolean | No | — | — | | data.monitoringMetrics | object[] | No | — | — | | data.monitoringMetrics.name | string | Yes | — | — | | data.monitoringMetrics.type | string | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.releasePipelineID | string | No | — | Constraints: nullable | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | ```json { "message": "Gate updated successfully.", "data": { "id": "a_gate", "name": "A Gate", "description": "description", "idType": "userID", "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifiedTime": 1705691355849, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "1vaQaBoLlkauH9iiuOSBP2", "createdTime": 1705691325569, "creatorName": "CONSOLE API", "creatorEmail": null, "targetApps": [], "holdoutIDs": [], "tags": [], "isEnabled": true, "status": "Archived", "rules": [], "checksPerHour": 0, "type": "PERMANENT", "typeReason": "NONE", "team": null, "reviewSettings": { "requiredReview": false, "allowedReviewers": [] }, "measureMetricLifts": true, "store0100Exposures": false, "owner": { "ownerID": "user123", "ownerName": "CONSOLE API", "ownerType": "SDK_KEY", "ownerEmail": "" }, "monitoringMetrics": [], "version": 2, "permalink": "https://console.statsig.com/company_id/gates/a_gate" } } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/gates/{id}/archive" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/gates/{id}/archive", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/archive", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/archive"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/gates/{id}/archive", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/archive")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/archive") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Cancel Gate Review URL: https://docs.statsig.com/api-reference/gates/cancel-gate-review ================================================================================ # Cancel Gate Review ## Cancel Gate Review **DELETE** `/console/v1/gates/{id}/reviews/{reviewID}` Full URL: `https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}` Cancel Gate Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Response (application/json) **200** — Cancel an in-flight gate review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | No | — | — | ```json { "message": "Gate review cancelled successfully" } ``` ## Code samples ### cURL ```bash curl -X DELETE "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.delete( "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}", { method: "DELETE", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("DELETE", "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}")) .method("DELETE", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}") request = Net::HTTP::Delete.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Commit Gate Review URL: https://docs.statsig.com/api-reference/gates/commit-gate-review ================================================================================ # Commit Gate Review ## Commit Gate Review **PUT** `/console/v1/gates/{id}/reviews/{reviewID}/commit` Full URL: `https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit` Commit Gate Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | | reviewID (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | bypass_webhook | boolean | No | — | Skip the configured pre-commit webhook and apply the reviewed change immediately. Personal keys require the `bypass_precommit_webhook` permission. An omitted value bypasses automatically for ownerless `omni_read_write` Console API keys; set to `false` to run the configured webhook workflow. | ## Response (application/json) **200** — Commit a gate review. Unless `bypass_webhook` is authorized, a configured pre-commit webhook must validate the review before a later commit applies the change. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | — | | status | string | Yes | — | Current review status after the commit attempt. A non-final webhook status means the reviewed change was not applied. Allowed values: pending_webhook_validation, failed_webhook_validation, approved_webhook_validation, committed | ```json { "message": "Gate review committed successfully", "status": "committed" } ``` ## Code samples ### cURL ```bash curl -X PUT "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" ``` ### Python ```python import requests response = requests.put( "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit", { method: "PUT", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" } }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { req, _ := http.NewRequest("PUT", "https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit", nil) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit")) .method("PUT", HttpRequest.BodyPublishers.noBody()) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates/{id}/reviews/{reviewID}/commit") request = Net::HTTP::Put.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Gate URL: https://docs.statsig.com/api-reference/gates/create-gate ================================================================================ # Create Gate ## Create Gate **POST** `/console/v1/gates` Full URL: `https://statsigapi.net/console/v1/gates` Create Gate ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Query parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | includeArchiveMetadata (query) | string | No | — | When "true", populate archivedAt / archivedBy* / archiveReason on the gate when it is currently archived. When omitted or "false", those fields are absent from the response. Allowed values: true, false | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | name | string | No | — | The gate display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | isEnabled | boolean | No | — | — | | description | string | No | — | Constraints: max length: 1000 | | rules | object[] | No | — | — | | rules.name | string | Yes | — | The name of this rule. | | rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | rules.conditions | object[] | Yes | — | An array of Condition objects. | | rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | rules.conditions.field | string | No | — | Constraints: nullable | | rules.conditions.customID | string | No | — | Constraints: nullable | | rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | rules.id | string | No | — | The Statsig ID of this rule. | | rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | rules.returnValue | object | No | — | The return value of the rule. | | rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | rules.completedAutomatedRollouts.time | number | No | — | — | | rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | rules.pendingAutomatedRollouts.time | number | No | — | — | | rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | tags | string[] | No | — | — | | type | string | No | — | Allowed values: PERMANENT, TEMPORARY | | idType | string | No | — | — | | targetApps | oneOf | No | — | Constraints: string, string[] | | creatorID | string | No | — | Constraints: nullable | | creatorEmail | string | No | — | Constraints: nullable | | team | string | No | — | Constraints: nullable | | teamID | string | No | — | Constraints: nullable | | measureMetricLifts | boolean | No | — | — | | monitoringMetrics | object[] | No | — | — | | monitoringMetrics.name | string | Yes | — | — | | monitoringMetrics.type | string | Yes | — | — | | reviewSettings | object | No | — | Whether reviews are required for this gate. If a gate has reviews required due to a project-level or team-level setting, setting this will have no effect. | | reviewSettings.requiredReview | boolean | Yes | — | — | | releasePipelineID | string | No | — | Constraints: nullable | | gradual_rollout_strategy | object | No | — | Optional safe-change strategy for risky gate rule increases. When required by policy, clients should retry with this field set after user confirmation. | | gradual_rollout_strategy.type | string | Yes | — | Use "gradual" to apply a gradual rollout to risky gate rule increases, or "bypass" to explicitly apply the direct change. Allowed values: gradual, bypass | | gradual_rollout_strategy.phases | object[] | No | — | Optional rollout phases in the same shape used by the product rollout editor. If omitted for "gradual", the server default schedule is used. | | gradual_rollout_strategy.phases.time | number | No | — | — | | gradual_rollout_strategy.phases.pass_percent | number | Yes | — | — | | gradual_rollout_strategy.phases.isComplete | boolean | Yes | — | — | | gradual_rollout_strategy.phases.timeString | string | No | — | — | | gradual_rollout_strategy.phases.phaseDurationMs | number | No | — | Used for progressive rollouts to calculate when the next phase can start | | id | string | No | — | The gate name ID Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-.]*$ | | isTemplate | boolean | No | — | — | ## Response (application/json) **201** — Create gate response | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.id | string | Yes | — | ID | | data.name | string | No | — | The gate display name Constraints: min length: 3, max length: 100, pattern: ^[a-zA-Z0-9_\-. ]*$ | | data.idType | string | No | — | — | | data.description | string | Yes | — | Constraints: max length: 1000 | | data.lastModifierID | string | Yes | — | ID of the last modifier. Constraints: nullable | | data.lastModifiedTime | number | Yes | — | Time of the last modification. Constraints: format: double, nullable | | data.lastModifierEmail | string | Yes | — | Email of the last modifier. Constraints: nullable | | data.lastModifierName | string | Yes | — | Name of the last modifier. Constraints: nullable | | data.creatorID | string | No | — | Constraints: nullable | | data.createdTime | number | Yes | — | Timestamp when the entity was created. Constraints: format: double | | data.creatorName | string | Yes | — | Name of the creator. Constraints: nullable | | data.creatorEmail | string | No | — | Constraints: nullable | | data.tags | string[] | No | — | — | | data.targetApps | oneOf | No | — | Constraints: string, string[] | | data.holdoutIDs | string[] | No | — | Holdouts applied to this configuration. | | data.team | string | No | — | Constraints: nullable | | data.teamID | string | No | — | Constraints: nullable | | data.version | number | No | — | Version number Constraints: format: double | | data.checksPerHour | number | Yes | — | Constraints: format: double, nullable | | data.status | string | Yes | — | Allowed values: In Progress, Launched, Disabled, Archived | | data.type | string | Yes | — | Allowed values: TEMPORARY, PERMANENT, STALE, TEMPLATE | | data.typeReason | string | Yes | — | Allowed values: NONE, STALE_PROBABLY_LAUNCHED, STALE_PROBABLY_UNLAUNCHED, STALE_PROBABLY_FORGOTTEN, STALE_NO_RULES, STALE_PROBABLY_DEAD_CHECK, STALE_EMPTY_CHECKS, STALE_ALL_TRUE, STALE_ALL_FALSE | | data.owner | object | No | {"ownerID":"user123","ownerType":"USER","ownerName":"John Doe","ownerEmail":"owner123@test.com"} | Schema for owner data including ID, type, name. Constraints: nullable | | data.owner.ownerID | string | No | abc123 | ID of the owner | | data.owner.ownerType | string | No | USER | Type of the owner (e.g., SDK_KEY or USER) | | data.owner.ownerName | string | No | John Doe | The name of the owner. This field is optional. | | data.owner.ownerEmail | string | No | — | The email of the owner. This field is optional. | | data.isTemplate | boolean | No | — | — | | data.store0100Exposures | boolean | No | — | Whether this gate stores 0/100 exposures for monitoring/analysis. | | data.permalink | string | Yes | — | A permalink to this gate in the Statsig Console. Constraints: format: uri | | data.archivedAt | number | No | — | Timestamp (ms) of the most recent archive event when the gate is currently archived; null otherwise. May be null for gates archived before audit logging existed. Constraints: format: double, nullable | | data.archivedByID | string | No | — | ID of the user who archived this gate, when known and the gate is currently archived; null otherwise (e.g. automated archives have no user). Constraints: nullable | | data.archivedByName | string | No | — | Name of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archivedByEmail | string | No | — | Email of the user who archived this gate, when known and the gate is currently archived; null otherwise. Constraints: nullable | | data.archiveReason | string | No | — | Free-text reason supplied when the gate was most recently archived; null when the gate is not currently archived or no reason was given. Constraints: nullable | | data.isEnabled | boolean | Yes | — | — | | data.rules | object[] | Yes | — | — | | data.rules.name | string | Yes | — | The name of this rule. | | data.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.rules.conditions.field | string | No | — | Constraints: nullable | | data.rules.conditions.customID | string | No | — | Constraints: nullable | | data.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | data.rules.id | string | No | — | The Statsig ID of this rule. | | data.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.rules.returnValue | object | No | — | The return value of the rule. | | data.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.rules.completedAutomatedRollouts.time | number | No | — | — | | data.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.measureMetricLifts | boolean | No | — | — | | data.monitoringMetrics | object[] | No | — | — | | data.monitoringMetrics.name | string | Yes | — | — | | data.monitoringMetrics.type | string | Yes | — | — | | data.reviewSettings | object | No | — | — | | data.reviewSettings.requiredReview | boolean | Yes | — | — | | data.reviewSettings.allowedReviewers | object[] | No | — | Constraints: nullable | | data.reviewSettings.allowedReviewers.id | string | Yes | — | — | | data.reviewSettings.allowedReviewers.name | string | Yes | — | — | | data.reviewSettings.allowedReviewers.email | string | Yes | — | — | | data.releasePipelineID | string | No | — | Constraints: nullable | | data.activeReview | object | No | — | — | | data.activeReview.reviewID | string | Yes | — | — | | data.activeReview.reviewStatus | string | Yes | — | — | | data.activeReview.description | string | Yes | — | — | ```json { "message": "Gate created successfully.", "data": { "id": "a_gate", "permalink": "https://console.statsig.com/company_id/gates/a_gate", "name": "A Gate", "description": "description", "idType": "userID", "lastModifierID": "1vaQaBoLlkauH9iiuOSBP2", "lastModifiedTime": 1704929983827, "lastModifierName": "CONSOLE API", "lastModifierEmail": null, "creatorID": "1vaQaBoLlkauH9iiuOSBP2", "createdTime": 1704929979761, "creatorName": "CONSOLE API", "creatorEmail": null, "targetApps": [], "holdoutIDs": [], "tags": [], "isEnabled": true, "status": "In Progress", "rules": [], "checksPerHour": 0, "type": "PERMANENT", "typeReason": "NONE", "team": null, "reviewSettings": { "requiredReview": false, "allowedReviewers": [] }, "measureMetricLifts": true, "owner": { "ownerID": "user123", "ownerName": "CONSOLE API", "ownerType": "SDK_KEY", "ownerEmail": "" }, "monitoringMetrics": [], "version": 1 } } ``` ## Code samples ### cURL ```bash curl -X POST "https://statsigapi.net/console/v1/gates" \ -H "Content-Type: application/json" \ -H "STATSIG-API-KEY: YOUR_API_KEY" \ -d '{ "name": "a_verbose_gate", "isEnabled": false, "description": "helpful summary of what this gate does", "rules": [ { "name": "All Conditions", "passPercentage": 10, "conditions": [ { "type": "public" }, { "type": "user_id", "targetValue": [ "111", "222" ], "operator": "any" }, { "type": "email", "targetValue": [ "@outlook.com", "@gmail.com" ], "operator": "str_contains_any" }, { "type": "custom_field", "targetValue": 31, "operator": "gt", "field": "age" }, { "type": "app_version", "targetValue": "1.1.1", "operator": "version_gt" }, { "type": "browser_name", "targetValue": [ "Android", "Chrome" ], "operator": "any" }, { "type": "browser_version", "targetValue": [ "94.0.4606.81", "94.0.4606.92" ], "operator": "any" }, { "type": "os_name", "targetValue": [ "Android", "Windows" ], "operator": "none" }, { "type": "os_version", "targetValue": "11.0.0", "operator": "version_lte" }, { "type": "country", "targetValue": [ "NZ", "US" ], "operator": "any" }, { "type": "passes_gate", "targetValue": "my_gate_2" }, { "type": "fails_gate", "targetValue": "my_gate_2" }, { "type": "time", "targetValue": 1643070357193, "operator": "after" }, { "type": "environment_tier", "targetValue": [ "production" ], "operator": "any" }, { "type": "passes_segment", "targetValue": "growth_org" }, { "type": "fails_segment", "targetValue": "growth_org" }, { "type": "ip_address", "targetValue": [ "1.1.1.1", "8.8.8.8" ], "operator": "any" } ], "environment": null } ], "idType": "userID", "targetApps": [ "my_app" ], "team": "team", "monitoringMetrics": [ { "name": "dau", "type": "user" } ] }' ``` ### Python ```python import requests response = requests.post( "https://statsigapi.net/console/v1/gates", headers={ "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, json={ "name": "a_verbose_gate", "isEnabled": false, "description": "helpful summary of what this gate does", "rules": [ { "name": "All Conditions", "passPercentage": 10, "conditions": [ { "type": "public" }, { "type": "user_id", "targetValue": [ "111", "222" ], "operator": "any" }, { "type": "email", "targetValue": [ "@outlook.com", "@gmail.com" ], "operator": "str_contains_any" }, { "type": "custom_field", "targetValue": 31, "operator": "gt", "field": "age" }, { "type": "app_version", "targetValue": "1.1.1", "operator": "version_gt" }, { "type": "browser_name", "targetValue": [ "Android", "Chrome" ], "operator": "any" }, { "type": "browser_version", "targetValue": [ "94.0.4606.81", "94.0.4606.92" ], "operator": "any" }, { "type": "os_name", "targetValue": [ "Android", "Windows" ], "operator": "none" }, { "type": "os_version", "targetValue": "11.0.0", "operator": "version_lte" }, { "type": "country", "targetValue": [ "NZ", "US" ], "operator": "any" }, { "type": "passes_gate", "targetValue": "my_gate_2" }, { "type": "fails_gate", "targetValue": "my_gate_2" }, { "type": "time", "targetValue": 1643070357193, "operator": "after" }, { "type": "environment_tier", "targetValue": [ "production" ], "operator": "any" }, { "type": "passes_segment", "targetValue": "growth_org" }, { "type": "fails_segment", "targetValue": "growth_org" }, { "type": "ip_address", "targetValue": [ "1.1.1.1", "8.8.8.8" ], "operator": "any" } ], "environment": null } ], "idType": "userID", "targetApps": [ "my_app" ], "team": "team", "monitoringMetrics": [ { "name": "dau", "type": "user" } ] } ) data = response.json() ``` ### JavaScript ```javascript const response = await fetch("https://statsigapi.net/console/v1/gates", { method: "POST", headers: { "Content-Type": "application/json", "STATSIG-API-KEY": "YOUR_API_KEY" }, body: JSON.stringify({ "name": "a_verbose_gate", "isEnabled": false, "description": "helpful summary of what this gate does", "rules": [ { "name": "All Conditions", "passPercentage": 10, "conditions": [ { "type": "public" }, { "type": "user_id", "targetValue": [ "111", "222" ], "operator": "any" }, { "type": "email", "targetValue": [ "@outlook.com", "@gmail.com" ], "operator": "str_contains_any" }, { "type": "custom_field", "targetValue": 31, "operator": "gt", "field": "age" }, { "type": "app_version", "targetValue": "1.1.1", "operator": "version_gt" }, { "type": "browser_name", "targetValue": [ "Android", "Chrome" ], "operator": "any" }, { "type": "browser_version", "targetValue": [ "94.0.4606.81", "94.0.4606.92" ], "operator": "any" }, { "type": "os_name", "targetValue": [ "Android", "Windows" ], "operator": "none" }, { "type": "os_version", "targetValue": "11.0.0", "operator": "version_lte" }, { "type": "country", "targetValue": [ "NZ", "US" ], "operator": "any" }, { "type": "passes_gate", "targetValue": "my_gate_2" }, { "type": "fails_gate", "targetValue": "my_gate_2" }, { "type": "time", "targetValue": 1643070357193, "operator": "after" }, { "type": "environment_tier", "targetValue": [ "production" ], "operator": "any" }, { "type": "passes_segment", "targetValue": "growth_org" }, { "type": "fails_segment", "targetValue": "growth_org" }, { "type": "ip_address", "targetValue": [ "1.1.1.1", "8.8.8.8" ], "operator": "any" } ], "environment": null } ], "idType": "userID", "targetApps": [ "my_app" ], "team": "team", "monitoringMetrics": [ { "name": "dau", "type": "user" } ] }) }); const data = await response.json(); ``` ### PHP ```php <?php $ch = curl_init("https://statsigapi.net/console/v1/gates"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "STATSIG-API-KEY: YOUR_API_KEY" ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $body = json_encode({ "name": "a_verbose_gate", "isEnabled": false, "description": "helpful summary of what this gate does", "rules": [ { "name": "All Conditions", "passPercentage": 10, "conditions": [ { "type": "public" }, { "type": "user_id", "targetValue": [ "111", "222" ], "operator": "any" }, { "type": "email", "targetValue": [ "@outlook.com", "@gmail.com" ], "operator": "str_contains_any" }, { "type": "custom_field", "targetValue": 31, "operator": "gt", "field": "age" }, { "type": "app_version", "targetValue": "1.1.1", "operator": "version_gt" }, { "type": "browser_name", "targetValue": [ "Android", "Chrome" ], "operator": "any" }, { "type": "browser_version", "targetValue": [ "94.0.4606.81", "94.0.4606.92" ], "operator": "any" }, { "type": "os_name", "targetValue": [ "Android", "Windows" ], "operator": "none" }, { "type": "os_version", "targetValue": "11.0.0", "operator": "version_lte" }, { "type": "country", "targetValue": [ "NZ", "US" ], "operator": "any" }, { "type": "passes_gate", "targetValue": "my_gate_2" }, { "type": "fails_gate", "targetValue": "my_gate_2" }, { "type": "time", "targetValue": 1643070357193, "operator": "after" }, { "type": "environment_tier", "targetValue": [ "production" ], "operator": "any" }, { "type": "passes_segment", "targetValue": "growth_org" }, { "type": "fails_segment", "targetValue": "growth_org" }, { "type": "ip_address", "targetValue": [ "1.1.1.1", "8.8.8.8" ], "operator": "any" } ], "environment": null } ], "idType": "userID", "targetApps": [ "my_app" ], "team": "team", "monitoringMetrics": [ { "name": "dau", "type": "user" } ] }); curl_setopt($ch, CURLOPT_POSTFIELDS, $body); $response = curl_exec($ch); curl_close($ch); ``` ### Go ```go package main import ( "bytes" "net/http" ) func main() { body := []byte("{\"name\":\"a_verbose_gate\",\"isEnabled\":false,\"description\":\"helpful summary of what this gate does\",\"rules\":[{\"name\":\"All Conditions\",\"passPercentage\":10,\"conditions\":[{\"type\":\"public\"},{\"type\":\"user_id\",\"targetValue\":[\"111\",\"222\"],\"operator\":\"any\"},{\"type\":\"email\",\"targetValue\":[\"@outlook.com\",\"@gmail.com\"],\"operator\":\"str_contains_any\"},{\"type\":\"custom_field\",\"targetValue\":31,\"operator\":\"gt\",\"field\":\"age\"},{\"type\":\"app_version\",\"targetValue\":\"1.1.1\",\"operator\":\"version_gt\"},{\"type\":\"browser_name\",\"targetValue\":[\"Android\",\"Chrome\"],\"operator\":\"any\"},{\"type\":\"browser_version\",\"targetValue\":[\"94.0.4606.81\",\"94.0.4606.92\"],\"operator\":\"any\"},{\"type\":\"os_name\",\"targetValue\":[\"Android\",\"Windows\"],\"operator\":\"none\"},{\"type\":\"os_version\",\"targetValue\":\"11.0.0\",\"operator\":\"version_lte\"},{\"type\":\"country\",\"targetValue\":[\"NZ\",\"US\"],\"operator\":\"any\"},{\"type\":\"passes_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"fails_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"time\",\"targetValue\":1643070357193,\"operator\":\"after\"},{\"type\":\"environment_tier\",\"targetValue\":[\"production\"],\"operator\":\"any\"},{\"type\":\"passes_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"fails_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"ip_address\",\"targetValue\":[\"1.1.1.1\",\"8.8.8.8\"],\"operator\":\"any\"}],\"environment\":null}],\"idType\":\"userID\",\"targetApps\":[\"my_app\"],\"team\":\"team\",\"monitoringMetrics\":[{\"name\":\"dau\",\"type\":\"user\"}]}") req, _ := http.NewRequest("POST", "https://statsigapi.net/console/v1/gates", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") req.Header.Set("STATSIG-API-KEY", "YOUR_API_KEY") client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() } ``` ### Java ```java HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://statsigapi.net/console/v1/gates")) .method("POST", HttpRequest.BodyPublishers.ofString("{\"name\":\"a_verbose_gate\",\"isEnabled\":false,\"description\":\"helpful summary of what this gate does\",\"rules\":[{\"name\":\"All Conditions\",\"passPercentage\":10,\"conditions\":[{\"type\":\"public\"},{\"type\":\"user_id\",\"targetValue\":[\"111\",\"222\"],\"operator\":\"any\"},{\"type\":\"email\",\"targetValue\":[\"@outlook.com\",\"@gmail.com\"],\"operator\":\"str_contains_any\"},{\"type\":\"custom_field\",\"targetValue\":31,\"operator\":\"gt\",\"field\":\"age\"},{\"type\":\"app_version\",\"targetValue\":\"1.1.1\",\"operator\":\"version_gt\"},{\"type\":\"browser_name\",\"targetValue\":[\"Android\",\"Chrome\"],\"operator\":\"any\"},{\"type\":\"browser_version\",\"targetValue\":[\"94.0.4606.81\",\"94.0.4606.92\"],\"operator\":\"any\"},{\"type\":\"os_name\",\"targetValue\":[\"Android\",\"Windows\"],\"operator\":\"none\"},{\"type\":\"os_version\",\"targetValue\":\"11.0.0\",\"operator\":\"version_lte\"},{\"type\":\"country\",\"targetValue\":[\"NZ\",\"US\"],\"operator\":\"any\"},{\"type\":\"passes_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"fails_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"time\",\"targetValue\":1643070357193,\"operator\":\"after\"},{\"type\":\"environment_tier\",\"targetValue\":[\"production\"],\"operator\":\"any\"},{\"type\":\"passes_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"fails_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"ip_address\",\"targetValue\":[\"1.1.1.1\",\"8.8.8.8\"],\"operator\":\"any\"}],\"environment\":null}],\"idType\":\"userID\",\"targetApps\":[\"my_app\"],\"team\":\"team\",\"monitoringMetrics\":[{\"name\":\"dau\",\"type\":\"user\"}]}")) .header("Content-Type", "application/json") .header("STATSIG-API-KEY", "YOUR_API_KEY") .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); ``` ### Ruby ```ruby require "net/http" require "json" uri = URI("https://statsigapi.net/console/v1/gates") request = Net::HTTP::Post.new(uri) request["Content-Type"] = "application/json" request["STATSIG-API-KEY"] = "YOUR_API_KEY" request.body = "{\"name\":\"a_verbose_gate\",\"isEnabled\":false,\"description\":\"helpful summary of what this gate does\",\"rules\":[{\"name\":\"All Conditions\",\"passPercentage\":10,\"conditions\":[{\"type\":\"public\"},{\"type\":\"user_id\",\"targetValue\":[\"111\",\"222\"],\"operator\":\"any\"},{\"type\":\"email\",\"targetValue\":[\"@outlook.com\",\"@gmail.com\"],\"operator\":\"str_contains_any\"},{\"type\":\"custom_field\",\"targetValue\":31,\"operator\":\"gt\",\"field\":\"age\"},{\"type\":\"app_version\",\"targetValue\":\"1.1.1\",\"operator\":\"version_gt\"},{\"type\":\"browser_name\",\"targetValue\":[\"Android\",\"Chrome\"],\"operator\":\"any\"},{\"type\":\"browser_version\",\"targetValue\":[\"94.0.4606.81\",\"94.0.4606.92\"],\"operator\":\"any\"},{\"type\":\"os_name\",\"targetValue\":[\"Android\",\"Windows\"],\"operator\":\"none\"},{\"type\":\"os_version\",\"targetValue\":\"11.0.0\",\"operator\":\"version_lte\"},{\"type\":\"country\",\"targetValue\":[\"NZ\",\"US\"],\"operator\":\"any\"},{\"type\":\"passes_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"fails_gate\",\"targetValue\":\"my_gate_2\"},{\"type\":\"time\",\"targetValue\":1643070357193,\"operator\":\"after\"},{\"type\":\"environment_tier\",\"targetValue\":[\"production\"],\"operator\":\"any\"},{\"type\":\"passes_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"fails_segment\",\"targetValue\":\"growth_org\"},{\"type\":\"ip_address\",\"targetValue\":[\"1.1.1.1\",\"8.8.8.8\"],\"operator\":\"any\"}],\"environment\":null}],\"idType\":\"userID\",\"targetApps\":[\"my_app\"],\"team\":\"team\",\"monitoringMetrics\":[{\"name\":\"dau\",\"type\":\"user\"}]}" response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http| http.request(request) end ``` ================================================================================ # Create Gate Review URL: https://docs.statsig.com/api-reference/gates/create-gate-review ================================================================================ # Create Gate Review ## Create Gate Review **POST** `/console/v1/gates/{id}/reviews` Full URL: `https://statsigapi.net/console/v1/gates/{id}/reviews` Create Gate Review ## Authorizations | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | STATSIG-API-KEY | string | Yes | — | apiKey (header) | ## Path parameters | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | id (path) | string | Yes | — | — | ## Body (application/json) | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | description | string | Yes | — | Human-readable description of the proposed change. Constraints: min length: 1, max length: 2000 | | reviewer_ids | string[] | No | [] | User IDs to request review from. | | reviewer_group_ids | string[] | No | [] | Reviewer group IDs to request review from. | | change | object | Yes | — | The proposed change. Provide exactly one of `rules`, `is_enabled`, `is_archived`, `delete`, `resalt`, `disable_reviews_locally`, `team_id`, `release_pipeline_id`, `id_type`, `allow_self_approval`, `target_app_ids`, `owners`, or `allowed_reviewers`. | | change.rules | object[] | No | — | Proposed full rule set for the gate. Same shape as the gate update contract. | | change.rules.name | string | Yes | — | The name of this rule. | | change.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | change.rules.conditions | object[] | Yes | — | An array of Condition objects. | | change.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | change.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | change.rules.conditions.field | string | No | — | Constraints: nullable | | change.rules.conditions.customID | string | No | — | Constraints: nullable | | change.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | change.rules.environments | string[] | No | — | The environments this rule is enabled for. Constraints: nullable | | change.rules.id | string | No | — | The Statsig ID of this rule. | | change.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | change.rules.returnValue | object | No | — | The return value of the rule. | | change.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | change.rules.completedAutomatedRollouts.time | number | No | — | — | | change.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | change.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | change.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | change.rules.pendingAutomatedRollouts.time | number | No | — | — | | change.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | change.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | change.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | change.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | change.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | change.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | change.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | change.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | change.is_enabled | boolean | No | — | Proposed enabled state for the gate. An explicit target, not a toggle. | | change.is_archived | boolean | No | — | Proposed archived state for the gate. `true` archives, `false` unarchives. | | change.delete | boolean | No | — | Delete the gate. Set to `true`. Allowed values: true | | change.resalt | boolean | No | — | Re-randomize the gate's salt. Set to `true`. Allowed values: true | | change.disable_reviews_locally | boolean | No | — | Stop requiring review on this gate. Set to `true`. Allowed values: true | | change.team_id | string | No | — | Reassign the gate to this team (review type `update_team`). Constraints: min length: 1 | | change.release_pipeline_id | string | No | — | Set the gate's release pipeline (review type `update_release_pipeline`). Constraints: min length: 1 | | change.id_type | string | No | — | Change the gate's primary unit ID type (review type `edit_id_type`). Constraints: min length: 1 | | change.allow_self_approval | boolean | No | — | Whether this gate's reviews may be self-approved (review type `update_allow_self_approval`). | | change.target_app_ids | string[] | No | — | Replace the gate's target applications (review type `update_target_applications`). | | change.owners | object[] | No | — | Replace the gate's owners (review type `update_owners`). | | change.owners.owner_id | string | Yes | — | User ID (or SDK key ID) of the owner. Constraints: min length: 1 | | change.owners.owner_type | string | No | — | Owner kind. Defaults to `user`. Allowed values: user, sdk_key | | change.allowed_reviewers | object | No | — | Set who may review this gate (review type `allowed_reviewers`). | | change.allowed_reviewers.user_ids | string[] | No | — | User IDs allowed to review. Replaces the existing set. | | change.allowed_reviewers.group_ids | string[] | No | — | Reviewer group IDs allowed to review. Replaces the existing set. | ## Response (application/json) **201** — The created gate review. | Name | Type | Required | Default | Description | | --- | --- | --- | --- | --- | | message | string | Yes | — | A simple string explaining the result of the operation. | | data | object | Yes | — | — | | data.review_id | string | Yes | — | Unique ID of the review. | | data.status | string | Yes | — | Lifecycle status of the review. Allowed values: pending, accepted, rejected, committed, changes_requested, pending_webhook_validation, failed_webhook_validation, approved_webhook_validation | | data.type | string | Yes | — | Kind of change the review proposes. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.author | object | Yes | — | The user who created the review. | | data.author.id | string | Yes | — | — | | data.author.email | string | Yes | — | Constraints: nullable | | data.reviewers | object[] | Yes | — | Requested reviewers (users and groups). | | data.reviewers.id | string | Yes | — | — | | data.reviewers.kind | string | Yes | — | Allowed values: user, group | | data.description | string | Yes | — | Human-readable description of the proposed change. | | data.created_at | string | Yes | — | ISO-8601 timestamp of when the review was created. | | data.content | object | No | — | The proposed change, as a `current` / `proposed` pair over only the fields this review type updates. `null` means — and only ever means — that this review type carries no proposed value (`delete`, `resalt`, `disable_reviews_locally`); those are fully described by `type`. When the change exists but could not be read back, `content` is present with an `unavailable_reason` instead, so the two cases stay distinguishable. Only populated on single-review responses (get / create / edit / approve / reject); the list endpoint omits it entirely rather than paying a snapshot read per row. Constraints: nullable | | data.content.type | string | Yes | — | Same value as the envelope `type`, repeated for self-containment. Allowed values: rules, toggle_enabled, archive, delete, resalt, disable_reviews_locally, update_team, update_release_pipeline, edit_id_type, update_allow_self_approval, update_target_applications, update_owners, allowed_reviewers | | data.content.current | object | Yes | — | The entity's live value at read time, for each field this review type updates. Matches the Console's "Original Version (Before)" column for pending reviews. This is NOT status-dependent: for a committed or rejected review it is still the live entity as it stands now, which for a committed review normally equals `proposed`. | | data.content.current.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.current.rules.name | string | Yes | — | The name of this rule. | | data.content.current.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.current.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.current.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.current.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.current.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.current.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.current.rules.environments | string[] | No | — | Constraints: nullable | | data.content.current.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.current.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.current.rules.returnValue | object | No | — | — | | data.content.current.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.current.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.current.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.current.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.current.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.current.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.current.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.current.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.current.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.current.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.current.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.current.rules.returnValueJson5 | string | No | — | — | | data.content.current.rules.variants | object[] | No | — | — | | data.content.current.rules.variants.id | string | No | — | — | | data.content.current.rules.variants.name | string | Yes | — | — | | data.content.current.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.current.rules.variants.returnValue | object | No | — | — | | data.content.current.rules.variants.returnValueJson5 | string | No | — | — | | data.content.current.is_enabled | boolean | No | — | — | | data.content.current.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.current.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.current.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.current.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.current.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.current.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.current.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.current.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.current.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.current.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.current.description | string | No | — | — | | data.content.current.show_dev_rules | boolean | No | — | — | | data.content.current.show_staging_rules | boolean | No | — | — | | data.content.current.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.current.subscribers.type | string | Yes | — | — | | data.content.current.subscribers.id | string | Yes | — | — | | data.content.current.analytics_enabled | boolean | No | — | — | | data.content.current.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.current.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.current.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.current.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.current.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.current.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.current.id_type | string | No | — | — | | data.content.current.secondary_id_type | string | No | — | Constraints: nullable | | data.content.current.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.current.target_app_ids | string[] | No | — | — | | data.content.current.owners | object[] | No | — | — | | data.content.current.owners.owner_id | string | Yes | — | — | | data.content.current.owners.owner_type | string | Yes | — | — | | data.content.current.team_id | string | No | — | Constraints: nullable | | data.content.current.allow_self_approval | boolean | No | — | — | | data.content.current.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.current.allowed_reviewers | object | No | — | Who may approve reviews on this config. Carried by `allowed_reviewers` reviews, which set it outright, and ALSO by `update_team` reviews, which can widen it as a side effect: moving a config onto a team whose review-approval mode is `admin_only` appends that team's admins to `user_ids`, and `team_only` appends the team itself to `group_ids`. Identical values on both sides of an `update_team` review mean that move grants no new approval rights. | | data.content.current.allowed_reviewers.user_ids | string[] | Yes | — | — | | data.content.current.allowed_reviewers.group_ids | string[] | Yes | — | — | | data.content.current.schema | string | No | — | Constraints: nullable | | data.content.current.monitoring_metrics | object[] | No | — | — | | data.content.current.monitoring_metrics.name | string | Yes | — | — | | data.content.current.monitoring_metrics.type | string | Yes | — | — | | data.content.current.monitoring_metric_tags | object[] | No | — | — | | data.content.current.monitoring_metric_tags.id | string | Yes | — | — | | data.content.current.real_time_metrics | object[] | No | — | — | | data.content.current.real_time_metrics.name | string | Yes | — | — | | data.content.current.real_time_metrics.type | string | Yes | — | — | | data.content.current.overrides | object | No | — | — | | data.content.current.overrides.id_overrides | object[] | Yes | — | — | | data.content.current.overrides.id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides | object[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.ids | string[] | Yes | — | — | | data.content.current.overrides.custom_id_overrides.groupID | string | Yes | — | — | | data.content.current.overrides.custom_id_overrides.environment | string | No | — | Constraints: nullable | | data.content.current.overrides.custom_id_overrides.unitID | string | No | — | Constraints: nullable | | data.content.proposed | object | Yes | — | The value this review proposes — what commit will apply. Carries exactly the same keys as `current`. Array-valued fields carry the full array on both sides, never only the changed elements. | | data.content.proposed.rules | object[] | No | — | The FULL rule array for this side, not just the rules that changed — commit replaces the array wholesale and rule order is evaluation-significant. Rules are serialized exactly as the entity's own read endpoint returns them, so this can be diffed against it with no translation: gates match `GET /gates/{id}` (no `returnValue`/`returnValueJson5`/`variants` — a gate rule has no return value), dynamic configs match `GET /dynamic_configs/{id}` and do carry those three. | | data.content.proposed.rules.name | string | Yes | — | The name of this rule. | | data.content.proposed.rules.passPercentage | number | Yes | — | Of the users that meet the conditions of this rule, what percent should return true. Constraints: min: 0, max: 100 | | data.content.proposed.rules.conditions | object[] | Yes | — | An array of Condition objects. | | data.content.proposed.rules.conditions.targetValue | oneOf | No | — | Constraints: nullable, string[], number[], string, number | | data.content.proposed.rules.conditions.operator | string | No | — | Allowed values: any, none, any_case_sensitive, none_case_sensitive, str_contains_any, str_contains_none, gt, lt, lte, gte, version_gt, version_lt, version_gte, version_lte, version_eq, after, before, on, is_null, is_not_null, str_matches, encoded_any, array_contains_any, array_contains_none, array_contains_all, not_array_contains_all | | data.content.proposed.rules.conditions.field | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.customID | string | No | — | Constraints: nullable | | data.content.proposed.rules.conditions.type | string | Yes | — | Allowed values: app_version, browser_name, browser_version, country, custom_field, email, environment_tier, fails_gate, fails_segment, ip_address, locale, os_name, os_version, passes_gate, passes_segment, public, time, unit_id, user_id, user_agent, url, javascript, device_model, target_app, experiment_group | | data.content.proposed.rules.environments | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.id | string | No | — | The Statsig ID of this rule. | | data.content.proposed.rules.baseID | string | No | — | The base ID of this rule, i.e. without any added metadata. Will remain the exact same throughout | | data.content.proposed.rules.returnValue | object | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts | object[] | No | — | Read-only: Automated rollout phases that have already completed. | | data.content.proposed.rules.completedAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.completedAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.completedAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.pendingAutomatedRollouts | object[] | No | — | Automated rollout phases that are scheduled but not yet complete. Writable on create/update; also returned on read. `time` is an epoch-seconds timestamp and is required unless `phaseDurationMs` is set. `phaseDurationMs` schedules the phase relative to the previous one. A `time` in the past is accepted so a read-modify-write round trip succeeds; that phase advances on the next automated rollout run. | | data.content.proposed.rules.pendingAutomatedRollouts.time | number | No | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.passPercent | number | Yes | — | — | | data.content.proposed.rules.pendingAutomatedRollouts.phaseDurationMs | integer | No | — | Constraints: min: 0 | | data.content.proposed.rules.safeguard | object | No | — | Safeguard configuration for automated rollback/pause actions when linked alerts fire. Constraints: nullable | | data.content.proposed.rules.safeguard.alertAction | string | Yes | — | Allowed values: rollback_to_0, rollout_to_100, pause | | data.content.proposed.rules.safeguard.guardrailAlerts | string[] | Yes | — | — | | data.content.proposed.rules.safeguard.toplineAlerts | string[] | No | — | Constraints: nullable | | data.content.proposed.rules.safeguard.toplineEvaluationPeriodInMs | oneOf | No | — | Constraints: number (nullable, min: 0), number | | data.content.proposed.rules.safeguard.manualEvaluationRenewalTimeInMs | integer | No | — | Constraints: nullable | | data.content.proposed.rules.returnValueJson5 | string | No | — | — | | data.content.proposed.rules.variants | object[] | No | — | — | | data.content.proposed.rules.variants.id | string | No | — | — | | data.content.proposed.rules.variants.name | string | Yes | — | — | | data.content.proposed.rules.variants.passPercentage | number | Yes | — | Constraints: min: 0, max: 100 | | data.content.proposed.rules.variants.returnValue | object | No | — | — | | data.content.proposed.rules.variants.returnValueJson5 | string | No | — | — | | data.content.proposed.is_enabled | boolean | No | — | — | | data.content.proposed.default_value | unknown | No | — | The config's default value. Parsed JSON when parseable, otherwise the raw stored string. For a gate this is the launch flag: `true` means "launched" (serve the gate to everyone), `false` means plain enabled/disabled. | | data.content.proposed.is_launched | boolean | No | — | Dynamic configs only. Whether the config is serving its launched payload to every user, bypassing rules. Derived: a dynamic config is launched when it is disabled AND has a launched payload. This is the dynamic-config equivalent of a gate's `default_value: true`, and it is what a dynamic config `toggle_enabled` review actually moves — `default_value` plays no part in that decision. | | data.content.proposed.launched_payload | unknown | No | — | Dynamic configs only. The value served to every user while the config is launched; `null` when it is not launched. Parsed JSON when parseable. Omitted entirely for secret dynamic configs — unlike `default_value`, the launched payload has no ciphertext-preserving accessor, so surfacing it would put a secret in cleartext on a response that `GET /console/v1/dynamic_configs/{id}` never returns it on. Use `is_launched` to see the state change for those. | | data.content.proposed.default_value_gradual_rollout | object | No | — | Dynamic configs only. The in-progress partial rollout of a new default value, or `null` when there is none. Omitted for secret dynamic configs: the target value is stored unencrypted inside the snapshot, so it is suppressed for the same reason as `launched_payload`. Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.id | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.target_value | unknown | No | — | — | | data.content.proposed.default_value_gradual_rollout.percentage_pass | number | Yes | — | Constraints: format: double | | data.content.proposed.default_value_gradual_rollout.salt | string | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts | object[] | Yes | — | Constraints: nullable | | data.content.proposed.default_value_gradual_rollout.rollouts.time | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.pass_percent | number | Yes | — | — | | data.content.proposed.default_value_gradual_rollout.rollouts.is_complete | boolean | Yes | — | — | | data.content.proposed.salt | string | No | — | The bucketing salt. Present when committing would change it — which re-buckets every user in every percentage rollout on this config, even though no rule text moved. A `restore` review that reverts past a resalt is the case to watch for. | | data.content.proposed.description | string | No | — | — | | data.content.proposed.show_dev_rules | boolean | No | — | — | | data.content.proposed.show_staging_rules | boolean | No | — | — | | data.content.proposed.subscribers | object[] | No | — | Who is notified about alerts on this config (users, teams, Slack channels, PagerDuty on-calls). | | data.content.proposed.subscribers.type | string | Yes | — | — | | data.content.proposed.subscribers.id | string | Yes | — | — | | data.content.proposed.analytics_enabled | boolean | No | — | — | | data.content.proposed.scheduled_reload | object | No | — | Gates only. The DWH-native scheduled-reload settings, which commit writes as a unit. Absent on non-warehouse-native projects, where none of it is set on either side. | | data.content.proposed.scheduled_reload.hour | number | Yes | — | Constraints: format: double, nullable | | data.content.proposed.scheduled_reload.days | number[] | Yes | — | Constraints: nullable | | data.content.proposed.scheduled_reload.reload_type | string | Yes | — | Allowed values: incremental, full | | data.content.proposed.scheduled_reload.turbo_mode | boolean | Yes | — | Constraints: nullable | | data.content.proposed.is_archived | boolean | No | — | Present on `archive` reviews. Archive and unarchive share the external type `archive`, so this field is what distinguishes them. | | data.content.proposed.id_type | string | No | — | — | | data.content.proposed.secondary_id_type | string | No | — | Constraints: nullable | | data.content.proposed.identity_resolution_source_id | string | No | — | Constraints: nullable | | data.content.proposed.target_app_ids | string[] | No | — | — | | data.content.proposed.owners | object[] | No | — | — | | data.content.proposed.owners.owner_id | string | Yes | — | — | | data.content.proposed.owners.owner_type | string | Yes | — | — | | data.content.proposed.team_id | string | No | — | Constraints: nullable | | data.content.proposed.allow_self_approval | boolean | No | — | — | | data.content.proposed.release_pipeline_id | string | No | — | Constraints: nullable | | data.content.proposed.allowed_reviewers | object | No | — | Who may approve reviews o