> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kaireonai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pre-Deployment Intelligence

> Five APIs that let you preview the impact of configuration changes before they go live — policy impact, qualification reach, budget burn, experiment power, and segment overlap.

## Overview

Pre-Deployment Intelligence is a suite of five simulation APIs that answer "what if?" questions about proposed configuration changes. Instead of deploying a new policy, decisioning gate, or experiment and hoping for the best, you can preview its impact on your actual customer data first.

Each API samples real data from your tenant's interaction history, customer segments, and schema tables to produce quantitative impact estimates. No changes are written — these are read-only analytical queries.

<Info>
  All Pre-Deployment Intelligence endpoints require `admin` or `editor` role (except Budget Forecast, Power Calculator, and Segment Overlap, which also allow `viewer`). Responses are computed on-demand from live data, so execution time scales with `sampleSize`.
</Info>

***

## Policy Impact Preview

**Endpoint:** `POST /api/v1/contact-policies/impact-preview`

Previews how a proposed contact policy (frequency cap) would affect your customer base. The API samples recent interaction history and calculates how many customers would hit the frequency cap, which offers would be suppressed, and which segments are most affected.

### Request Body

```json theme={null}
{
  "policyType": "frequency_cap",
  "scope": "global",
  "scopeId": null,
  "config": {
    "maxFrequency": 3,
    "periodDays": 7,
    "outcomeType": "impression"
  },
  "sampleSize": 1000
}
```

| Field                 | Type    | Required | Default    | Description                                                        |
| --------------------- | ------- | -------- | ---------- | ------------------------------------------------------------------ |
| `policyType`          | string  | Yes      | —          | Type of policy being previewed                                     |
| `scope`               | enum    | No       | `"global"` | Scope of the policy: `global`, `offer`, `category`, or `channel`   |
| `scopeId`             | string  | No       | `null`     | ID of the scoped entity (required when scope is not `global`)      |
| `config.maxFrequency` | integer | Yes      | —          | Maximum interactions allowed in the period                         |
| `config.periodDays`   | integer | Yes      | —          | Length of the frequency window in days (1--365)                    |
| `config.outcomeType`  | string  | Yes      | —          | Interaction type to count (e.g., `impression`, `click`, `convert`) |
| `sampleSize`          | integer | No       | 1000       | Number of customers to sample (100--10,000)                        |

### Response

```json theme={null}
{
  "totalCustomersAnalyzed": 1000,
  "customersAffected": 142,
  "affectedPercent": 14.2,
  "offersSuppressed": {
    "Premium Card": 89,
    "Cash Back Card": 53
  },
  "avgOffersBeforePolicy": 4.7,
  "avgOffersAfterPolicy": 3.2,
  "topAffectedSegments": [
    { "segment": "High Value", "affected": 67, "total": 312 },
    { "segment": "Early Adopter", "affected": 41, "total": 198 }
  ]
}
```

| Field                    | Description                                                       |
| ------------------------ | ----------------------------------------------------------------- |
| `totalCustomersAnalyzed` | Number of customers in the sample                                 |
| `customersAffected`      | Customers who would hit the frequency cap                         |
| `affectedPercent`        | Percentage of sampled customers affected                          |
| `offersSuppressed`       | Offers that would be suppressed, with suppression count per offer |
| `avgOffersBeforePolicy`  | Average interactions per customer without the policy              |
| `avgOffersAfterPolicy`   | Average interactions per customer with the policy applied         |
| `topAffectedSegments`    | Segments most impacted, sorted by affected count                  |

***

## Qualification Reach Estimator

**Endpoint:** `POST /api/v1/qualification-rules/reach-estimate`

Estimates how many customers qualify or are excluded by a proposed decisioning gate. Queries your actual schema tables to produce reach percentages and field distribution statistics.

### Request Body

```json theme={null}
{
  "ruleType": "attribute_condition",
  "field": "credit_score",
  "operator": "gte",
  "value": 720,
  "schema": "customers",
  "sampleSize": 5000
}
```

| Field        | Type                              | Required | Default | Description                                                                                            |
| ------------ | --------------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
| `ruleType`   | string                            | Yes      | —       | Type of decisioning gate                                                                               |
| `field`      | string                            | Yes      | —       | Column name in the schema table                                                                        |
| `operator`   | enum                              | Yes      | —       | Comparison operator: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `in`, `not_in`, `contains`, `not_contains` |
| `value`      | string / number / boolean / array | Yes      | —       | Value to compare against                                                                               |
| `schema`     | string                            | Yes      | —       | Name of the data schema to query                                                                       |
| `sampleSize` | integer                           | No       | 1000    | Number of rows to sample (100--10,000)                                                                 |

### Response

```json theme={null}
{
  "totalSampled": 5000,
  "qualifying": 3420,
  "excluded": 1580,
  "qualifyPercent": 68.4,
  "excludedBySegment": [
    { "segment": "Young Adults", "excluded": 892 },
    { "segment": "New Customers", "excluded": 445 }
  ],
  "fieldDistribution": {
    "min": 320.00,
    "max": 850.00,
    "avg": 698.42,
    "median": 712.00,
    "p25": 645.00,
    "p75": 755.00
  }
}
```

| Field               | Description                                                                                    |
| ------------------- | ---------------------------------------------------------------------------------------------- |
| `totalSampled`      | Total rows sampled from the schema table                                                       |
| `qualifying`        | Rows that pass the proposed rule                                                               |
| `excluded`          | Rows that would be excluded                                                                    |
| `qualifyPercent`    | Percentage of sampled rows that qualify                                                        |
| `excludedBySegment` | Breakdown of excluded customers by segment                                                     |
| `fieldDistribution` | Statistical summary of the field values (numeric fields only): min, max, avg, median, p25, p75 |

<Tip>
  Use the `fieldDistribution` statistics to calibrate your threshold. For example, if the median credit score is 712, a rule requiring `gte 720` excludes roughly half your customers. Adjusting to `gte 680` (below p25 at 645) would include about 75%.
</Tip>

***

## Budget Burn Projector

**Endpoint:** `POST /api/v1/offers/budget-forecast`

Projects when a budget will be exhausted based on historical conversion rates. Uses interaction history to estimate daily conversion volume and calculate an exhaustion date with a confidence level.

### Request Body

```json theme={null}
{
  "offerId": "offer_premium_cc",
  "totalBudget": 50000,
  "costPerConversion": 25,
  "lookbackDays": 30
}
```

| Field               | Type    | Required | Default | Description                                                |
| ------------------- | ------- | -------- | ------- | ---------------------------------------------------------- |
| `offerId`           | string  | No       | —       | Specific offer to forecast (omit for tenant-wide forecast) |
| `totalBudget`       | number  | Yes      | —       | Total budget in currency units                             |
| `costPerConversion` | number  | Yes      | —       | Cost per conversion (must be > 0)                          |
| `lookbackDays`      | integer | No       | 30      | Historical window for rate estimation (1--365)             |

### Response

```json theme={null}
{
  "totalBudget": 50000,
  "costPerConversion": 25,
  "maxConversions": 2000,
  "historicalConversionRate": 0.0842,
  "estimatedDailyConversions": 12.3,
  "estimatedDaysUntilExhaustion": 163,
  "exhaustionDate": "2026-09-01",
  "confidenceLevel": "high",
  "recommendation": "Budget will last approximately 5.4 months at current conversion rates."
}
```

| Field                          | Description                                                                                            |
| ------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `totalBudget`                  | The budget provided in the request                                                                     |
| `costPerConversion`            | Cost per conversion provided                                                                           |
| `maxConversions`               | Maximum conversions the budget can support (`totalBudget / costPerConversion`)                         |
| `historicalConversionRate`     | Observed conversion rate from the lookback period                                                      |
| `estimatedDailyConversions`    | Projected daily conversions based on historical data                                                   |
| `estimatedDaysUntilExhaustion` | Days until budget is fully consumed (null if no conversion data)                                       |
| `exhaustionDate`               | Projected date of budget exhaustion                                                                    |
| `confidenceLevel`              | `high` (14+ days, 50+ conversions), `medium` (7+ days, 20+ conversions), `low`, or `insufficient_data` |
| `recommendation`               | Human-readable summary with actionable guidance                                                        |

***

## Experiment Power Calculator

**Endpoint:** `POST /api/v1/experiments/power-calculator`

Calculates the required sample size and estimated duration for an A/B experiment to reach statistical significance. Uses your tenant's actual traffic volume to estimate how long the experiment will need to run.

### Request Body

```json theme={null}
{
  "baselineConversionRate": 0.12,
  "minimumDetectableEffect": 0.02,
  "significanceLevel": 0.05,
  "power": 0.80,
  "trafficSplit": 0.5
}
```

| Field                     | Type   | Required | Default | Description                                                            |
| ------------------------- | ------ | -------- | ------- | ---------------------------------------------------------------------- |
| `baselineConversionRate`  | number | Yes      | —       | Current conversion rate (0.001--1)                                     |
| `minimumDetectableEffect` | number | Yes      | —       | Smallest effect size you want to detect (0.001--1)                     |
| `significanceLevel`       | number | No       | 0.05    | Alpha level for the test (0.01--0.20)                                  |
| `power`                   | number | No       | 0.80    | Statistical power — probability of detecting a true effect (0.5--0.99) |
| `trafficSplit`            | number | No       | 0.5     | Fraction of traffic to the treatment group (0.1--0.9)                  |

### Response

```json theme={null}
{
  "requiredSampleSize": 7842,
  "perVariant": 3921,
  "estimatedDuration": {
    "days": 16,
    "basedOnDailyTraffic": 490
  },
  "recommendation": "With 490 daily decisions, you need ~16 days to reach statistical significance.",
  "sensitivityTable": [
    { "effect": 0.01, "sampleSize": 31368, "days": 64 },
    { "effect": 0.02, "sampleSize": 7842, "days": 16 },
    { "effect": 0.05, "sampleSize": 1254, "days": 3 },
    { "effect": 0.10, "sampleSize": 314, "days": 1 }
  ]
}
```

| Field                                   | Description                                                         |
| --------------------------------------- | ------------------------------------------------------------------- |
| `requiredSampleSize`                    | Total sample size needed across all variants                        |
| `perVariant`                            | Required sample size per variant                                    |
| `estimatedDuration.days`                | Estimated days to reach the required sample size                    |
| `estimatedDuration.basedOnDailyTraffic` | Daily decision volume used for the estimate (from the last 14 days) |
| `recommendation`                        | Human-readable summary                                              |
| `sensitivityTable`                      | Sample size and duration at different effect sizes for comparison   |

<Info>
  The power calculator uses the standard two-proportion z-test formula: `n = (Z_alpha + Z_beta)^2 * (p1(1-p1) + p2(1-p2)) / (p2-p1)^2`. Traffic split adjustments account for uneven splits, which require larger total sample sizes.
</Info>

***

## Segment Overlap Analyzer

**Endpoint:** `POST /api/v1/segments/overlap`

Analyzes overlap between two or more customer segments by querying their underlying PostgreSQL views and computing pairwise set intersections. Helps identify redundant segments and targeting conflicts.

### Request Body

```json theme={null}
{
  "segmentIds": ["seg_high_value", "seg_early_adopter", "seg_premium"],
  "sampleSize": 5000
}
```

| Field        | Type      | Required | Default | Description                                           |
| ------------ | --------- | -------- | ------- | ----------------------------------------------------- |
| `segmentIds` | string\[] | Yes      | —       | Segment IDs to analyze (2--10 segments)               |
| `sampleSize` | integer   | No       | 5000    | Maximum customers to sample per segment (100--50,000) |

### Response

```json theme={null}
{
  "segments": [
    { "id": "seg_high_value", "name": "High Value", "size": 4200 },
    { "id": "seg_early_adopter", "name": "Early Adopter", "size": 1850 },
    { "id": "seg_premium", "name": "Premium Tier", "size": 920 }
  ],
  "overlaps": [
    { "segments": ["seg_high_value", "seg_early_adopter"], "count": 712, "percent": 38 },
    { "segments": ["seg_high_value", "seg_premium"], "count": 890, "percent": 97 },
    { "segments": ["seg_early_adopter", "seg_premium"], "count": 445, "percent": 48 }
  ],
  "totalUniqueCustomers": 5163,
  "overlapWarnings": [
    "97% of Premium Tier customers are also in High Value — consider merging or adjusting targeting",
    "48% of Premium Tier customers are also in Early Adopter — consider merging or adjusting targeting",
    "38% of Early Adopter customers are also in High Value — consider merging or adjusting targeting"
  ]
}
```

| Field                  | Description                                                                                                  |
| ---------------------- | ------------------------------------------------------------------------------------------------------------ |
| `segments`             | Each segment with its ID, name, and sampled size                                                             |
| `overlaps`             | Pairwise overlap: segment pair, intersection count, and overlap percentage (relative to the smaller segment) |
| `totalUniqueCustomers` | Total unique customers across all segments                                                                   |
| `overlapWarnings`      | Warnings for segment pairs with 30%+ overlap, with actionable recommendations                                |

<Warning>
  Segment overlap queries execute against the segments' underlying PostgreSQL views. All segments must have materialized views (created during segment refresh). If a segment view does not exist, the API returns a 400 error with a message to refresh the segment first.
</Warning>

***

## Related

<CardGroup cols={3}>
  <Card title="Contact Policies" icon="clock" href="/decisioning/contact-policies">
    Configure frequency caps and suppression rules previewed by the Policy Impact API.
  </Card>

  <Card title="Decisioning Gates" icon="shield-check" href="/decisioning/qualification-rules">
    Define eligibility rules estimated by the Reach Estimator.
  </Card>

  <Card title="Algorithms & Models" icon="brain" href="/ai-ml/algorithms">
    Scoring models and experiments powered by the Power Calculator.
  </Card>
</CardGroup>
