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

# Policy Operations

> Policy versioning, testing, troubleshooting, and performance considerations

## Policy Versioning

Every time you update a policy's code, Formal automatically creates a new version. This gives you a full audit trail and the ability to roll back to any previous version.

### How Versioning Works

* Each policy starts at **version 1** on creation.
* Every code update increments the version number.
* All versions are stored permanently for compliance and auditing.
* Version history includes the code and timestamp of each change.

### Viewing Version History

> [tab] Control Plane
>
> 1. Navigate to [Policies](https://app.formal.ai/policies)
> 2. Select the policy
> 3. Click **Show Version History**
> 4. Use **Previous** / **Next** to browse versions with their timestamps and code

> [tab] API
>
> ```bash theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> # List all versions of a policy
> curl -X POST "https://api.formal.ai/core.v1.PoliciesService/ListPolicyVersions" \
>   -H "X-API-KEY: YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"policy_id": "policy_abc123"}'
>
> # Get a specific version
> curl -X POST "https://api.formal.ai/core.v1.PoliciesService/GetPolicyVersion" \
>   -H "X-API-KEY: YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{"id": "policy_xyz789"}'
> ```

> [!TIP]
>
> We recommend storing your policy code in version control (e.g., Git) alongside your Terraform configuration. This gives you both Formal's built-in version history and your team's standard code review workflow.

### Rolling Back to a Previous Version

You can apply any previous version of a policy:

1. Navigate to the policy in the Control Plane
2. Click **Show Version History**
3. Browse to the version you want with **Previous** / **Next**
4. Click **Apply** to load that version's code into the editor, then save the policy

Applying a previous version and saving creates a **new version** (the version number increments), preserving the full history. For example, applying version 3 when the current version is 5 and saving creates version 6 with version 3's code.

> [!TIP]
>
> For critical rollbacks, you can also set the policy to **draft** or **dry-run** first, apply the version, verify it works as expected, then re-activate.

## Testing Policies

Formal provides several ways to test policies before they affect production traffic.

### 1. Syntax Validation

Formal validates your Rego code before saving. If there's a syntax error, the policy cannot be created or updated, and you'll receive a detailed error message.

Common validation errors:

| Error | Cause | Fix |
| - | - | - |
| `rego_parse_error` | Invalid Rego syntax | Check for missing brackets, commas, or keywords |
| `rego_compile_error` | Undefined variable or function | Ensure all referenced variables exist in the policy scope |
| `undefined function` | The policy calls a built-in function Formal doesn't allow, such as `http.send` | Use a function from [Rego Built-in Functions](https://docs.formal.ai/docs/guides/policies/rego-builtins.md), or fetch external data with a [Hook](https://docs.formal.ai/docs/guides/policies/hooks.md) |
| Wrong package name | Package is not `formal.v2` | Use `package formal.v2` as the first line |
| Empty module | Policy contains only the package declaration | Add at least one rule (session, request, or response) |

### 2. Dry-Run Mode

Deploy a policy in **dry-run** mode to see what it *would* do without actually enforcing it:

1. Set the policy status to **Dry-run**
2. Monitor the [Logs](https://app.formal.ai/logs) page for policy trigger events
3. Dry-run events show what action the policy would have taken (block, mask, filter, etc.)
4. Once satisfied, switch to **Active**

> [!TIP]
>
> Dry-run policies are logged with full context, including the action that would have been taken and the reason. Use the Logs page to filter by policy name.

### 3. Impact Reports (Backtesting)

Test a policy against **historical log data** to understand its impact before activating it. Impact reports evaluate your policy code against real past traffic.

1. Navigate to [Policies](https://app.formal.ai/policies)
2. Select a policy or create a new one
3. Click **Backtest**
4. Choose the time window to backtest against (up to 31 days)
5. Review the results: which queries would have been affected, and what actions would have been taken

> [!WARNING]
>
> Impact reports require [Policy Evaluation Input Retention](https://docs.formal.ai/docs/guides/observability/logs.md#policy-evaluation-input-retention) to be enabled. Without retained inputs, there is no historical data to backtest against.

### 4. Stage-Based Rollout

You can turn off policy evaluation at specific stages (session, request, or response) for a Resource or a Connector. This lets you roll out policies one stage at a time:

1. Deploy the policy in **active** mode
2. Turn off evaluation at the stages you're not ready to test yet
3. Verify the enabled stage works correctly
4. Gradually turn on the remaining stages

> [!NOTE]
>
> Connectors currently apply stage configurations to S3 Resources only. See
> [Policy Stage Configuration](https://docs.formal.ai/docs/guides/policies/stage-configuration.md) for
> the API and the precedence rules.

### 5. Local Testing with Formal Endpoint

The [Formal Endpoint](https://docs.formal.ai/docs/guides/client-apps/desktop-app.md) lets you test policy evaluation locally. Connect to a resource through the Formal Endpoint and run queries to see how policies evaluate in real time.

### Recommended Testing Workflow

1. **Write** the policy code
2. **Validate** syntax (automatic on save)
3. **Backtest** with an impact report against historical data
4. **Dry-run** against live traffic
5. **Review** logs for unexpected triggers
6. **Activate** when confident

## Policy Suspensions

Temporarily suspend a policy for specific users without deactivating it entirely.

### Time-Based Suspension

Grant a user temporary exemption from a policy for a defined duration (default: 24 hours). This is useful for break-glass scenarios where a user needs emergency access.

### One-Off Suspension

Grant a single-use exemption that expires after one matching request. This is useful for controlled exceptions — for example, allowing a single DELETE statement that would otherwise be blocked.

See [Triggered Policies and Policy Suspensions](https://docs.formal.ai/docs/guides/policies/suspensions.md) to create and manage suspensions from the Control Plane.

> [!TIP]
>
> Policy suspensions can be integrated with approval workflows. See [Workflows](https://docs.formal.ai/docs/guides/configuration/workflows.md) for examples of Slack-based suspension request flows, or [Access Requests](https://docs.formal.ai/docs/guides/ai-governance/access-requests.md) for the in-app approval queue.

## Performance Considerations

### How Policy Evaluation Works

* Policies are evaluated **in parallel** across a worker pool sized to the number of CPU cores on the Connector.
* Each policy is evaluated independently with its own context, so policies cannot interfere with each other.
* Results are merged after all policies complete, following the [conflict resolution rules](https://docs.formal.ai/docs/guides/policies/enforcement.md#rule-conflicts-and-precedence).

### Writing Performant Policies

> [accordion] Keep Rego rules simple
>
> Avoid deeply nested iterations or complex comprehensions over large datasets. Rego is optimized for set-based operations — prefer `in` checks over loops where possible.
>
> ```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> # Preferred: set membership check
> session := {"action": "allow"} if {
>   "admin" in input.user.groups
> }
>
> # Avoid: iterating and comparing
> session := {"action": "allow"} if {
>   some group in input.user.groups
>   group == "admin"
> }
> ```

> [accordion] Scope policies to specific resources
>
> Use `included_connectors` or `included_resources` to limit which traffic a policy evaluates against. Unscoped policies run on every request across all resources.
>
> ```rego theme={"languages":{"custom":["/languages/cel.json","/languages/rego.json"]}}
> # Only evaluate for production databases
> included_resources := ["prod-postgres", "prod-mysql"]
> ```

> [accordion] Use the right evaluation stage
>
> Choose the most efficient stage for your use case:
>
> * **Session**: Cheapest — evaluated once per connection
> * **Request**: Evaluated per query, but before data is fetched
> * **Response**: Most expensive — evaluated per query after data returns, with access to row/column data
>
> If you can enforce a rule at the session stage, prefer that over request or response.

> [accordion] Keep hooks fast and small
>
> [Hooks](https://docs.formal.ai/docs/guides/policies/hooks.md) run in the access path, and their results are added to the policy input. Slow hooks add latency and large results increase memory usage. Return only the data your policies need.

> [accordion] Consolidate related rules
>
> Multiple policies that check similar conditions create redundant evaluation work. Where possible, combine related rules into a single policy to reduce overhead.

### Scaling the Connector

If policy evaluation latency becomes a concern:

* **Scale vertically**: More CPU cores = more parallel policy evaluation workers.
* **Scale horizontally**: Add more Connector instances with [clustering](https://docs.formal.ai/docs/guides/core-concepts/connectors/clustering.md) enabled.
* **Monitor metrics**: Use the Connector's [health metrics](https://docs.formal.ai/docs/guides/core-concepts/connectors/health.md) to track evaluation latency.

## Troubleshooting

### Policy Not Triggering

> [accordion] Check policy status
>
> Ensure the policy is in **active** (or **dry-run**) status. Policies in **draft** status are never evaluated.

> [accordion] Check the evaluation stage
>
> Verify your rule uses the correct stage name:
>
> * `session` — connection-time rules
> * `request` — before query execution
> * `response` — after data returns
>
> A `response` rule won't fire on connection, and a `session` rule won't have access to query data.

> [accordion] Check resource/connector/space scoping
>
> If the policy uses `included_resources`, `excluded_resources`, `included_connectors`, `excluded_connectors`, `included_spaces`, or `excluded_spaces`, verify that the target resource, connector, or space is in scope.

> [accordion] Check input conditions
>
> Use dry-run mode or impact reports to verify what `input` data the policy receives. Common issues:
>
> * `input.user.groups` may be empty if the user isn't assigned to any groups
> * `input.resource.environment` may not be set if the resource has no environment tag
> * `input.sql_query.statement_type` values are uppercase (e.g., `"SELECT"`, `"DELETE"`)

> [accordion] Check for conflicting policies
>
> Another policy may be overriding yours. Remember: **block wins over allow**, and **higher privacy masking wins**. Check the Logs page for which policies were evaluated on a given request.

### Policy Blocking Unexpectedly

> [accordion] Check for default deny rules
>
> If you have a `default session := {"action": "block", ...}` policy, it applies to **all** connections unless an explicit `allow` rule matches. Verify the allow conditions are correct.

> [accordion] Check precedence rules
>
> When multiple policies apply, block always wins over allow. If any active policy returns `block`, the request is blocked regardless of other policies returning `allow`.

> [accordion] Use dry-run to debug
>
> 1. Set the problematic policy to **dry-run**
> 2. Check the logs to see when it triggers
> 3. Review the `input` data to understand why the conditions matched
> 4. Adjust the policy logic and repeat

> [accordion] Suspend the policy temporarily
>
> If a policy is blocking critical operations, use a [policy suspension](#policy-suspensions) to temporarily exempt specific users while you investigate.

### Masking Not Working as Expected

> [accordion] Check data labels
>
> Masking policies that use `col.data_label` require [data discovery](https://docs.formal.ai/docs/guides/core-concepts/satellites.md) to have classified the columns. If labels aren't assigned, the masking condition won't match.

> [accordion] Check column paths
>
> When matching by column path, use the full path format: `database.schema.table.column` (e.g., `main.public.users.email`).

> [accordion] Check privacy level precedence
>
> If multiple masking policies target the same column, the one with the **highest privacy level** wins. See [Masking Types](https://docs.formal.ai/docs/guides/policies/enforcement.md#masking-types) for the privacy level hierarchy.

> [accordion] Check typesafe settings
>
> If masking results in type errors in your application, set `"typesafe_fallback"` to `"fallback_to_null"` or `"fallback_to_default"`. Setting it turns on type safety.

> [accordion] Check mask type and subtype names
>
> Formal doesn't validate mask names. An unknown `sub_type` leaves the value unmasked, and an unknown `type` drops the mask, with no error. `type: "fake"` and `type: "redact.partial"` also need an explicit `sub_type`. Compare your policy against [Masking Subtypes](https://docs.formal.ai/docs/guides/policies/enforcement.md#masking-subtypes).

### Common Rego Mistakes

| Mistake | Symptom | Fix |
| - | - | - |
| Wrong package name | Policy never evaluates | Use `package formal.v2` |
| Missing `import future.keywords.if` | Rego parse error | Add the import statement |
| Using `=` instead of `==` | Assignment instead of comparison | Use `==` for equality checks inside rule bodies |
| `input.sql_query` in session stage | Undefined variable error | Query data is only available in request and response stages |
| Case-sensitive comparisons | Policy doesn't match | SQL statement types are uppercase (`"SELECT"`, not `"select"`) |
| `not` without parentheses on complex expressions | Unexpected evaluation | Use `not (expr)` for compound negations |


## Related topics

- [Policies](https://docs.formal.ai/docs/guides/policies/introduction.md)
- [Triggered Policies and Policy Suspensions](https://docs.formal.ai/docs/guides/policies/suspensions.md)
- [Policy Enforcement](https://docs.formal.ai/docs/guides/policies/enforcement.md)
- [Policy Examples](https://docs.formal.ai/docs/guides/policies/examples.md)
- [Policy Evaluation](https://docs.formal.ai/docs/guides/policies/evaluation.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.