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

# Execute Rule

> Execute a rule against a specific entity for testing and validation — in the gu1 rules engine for compliance and risk detection, with examples for execute use.

## Overview

Executes a specific rule against an entity to test rule logic, validate conditions, and preview results before deploying to production. Useful for testing rules in shadow mode or debugging rule behavior.

## Endpoint

```
POST http://api.gu1.ai/rules/{ruleId}/execute
```

## Authentication

Requires a valid API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Path Parameters

<ParamField path="ruleId" type="string" required>
  UUID of the rule to execute
</ParamField>

## Request Body

<ParamField body="entityId" type="string" required>
  UUID of the entity to evaluate against the rule
</ParamField>

<ParamField body="testMode" type="boolean" default="false">
  If true, executes in test mode without creating alerts or modifying entities
</ParamField>

<ParamField body="includeDebug" type="boolean" default="false">
  If true, includes detailed debug information about condition evaluation
</ParamField>

## Response

<ResponseField name="matched" type="boolean">
  Whether the rule conditions matched
</ResponseField>

<ResponseField name="score" type="number">
  Risk score assigned by the rule (if matched)
</ResponseField>

<ResponseField name="executionTime" type="number">
  Execution time in milliseconds
</ResponseField>

<ResponseField name="conditions" type="object">
  Detailed evaluation results for each condition
</ResponseField>

<ResponseField name="actions" type="array">
  Actions that would be executed (or were executed if not in test mode)
</ResponseField>

<ResponseField name="debug" type="object">
  Debug information (if includeDebug=true)
</ResponseField>

## Example Requests

### Execute Rule in Test Mode

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "testMode": true,
      "includeDebug": true
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityId: '550e8400-e29b-41d4-a716-446655440000',
        testMode: true,
        includeDebug: true
      })
    }
  );

  const result = await response.json();
  console.log('Rule matched:', result.matched);
  console.log('Score:', result.score);
  console.log('Execution time:', result.executionTime + 'ms');
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityId': '550e8400-e29b-41d4-a716-446655440000',
          'testMode': True,
          'includeDebug': True
      }
  )

  result = response.json()
  print(f"Rule matched: {result['matched']}")
  print(f"Score: {result['score']}")
  print(f"Execution time: {result['executionTime']}ms")
  ```
</CodeGroup>

### Execute Rule in Production Mode

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "testMode": false
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityId: '550e8400-e29b-41d4-a716-446655440000',
        testMode: false
      })
    }
  );

  const result = await response.json();
  if (result.matched) {
    console.log('Rule matched! Actions executed:', result.actions.length);
  }
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityId': '550e8400-e29b-41d4-a716-446655440000',
          'testMode': False
      }
  )

  result = response.json()
  if result['matched']:
      print(f"Rule matched! Actions executed: {len(result['actions'])}")
  ```
</CodeGroup>

## Response Examples

### Successful Match with Debug Info

```json theme={null}
{
  "matched": true,
  "score": 85,
  "executionTime": 45,
  "conditions": {
    "operator": "AND",
    "result": true,
    "conditions": [
      {
        "id": "cond-1",
        "field": "enrichmentData.normalized.taxId",
        "operator": "eq",
        "expectedValue": "33.592.510/0001-54",
        "actualValue": "33.592.510/0001-54",
        "result": true
      }
    ]
  },
  "actions": [
    {
      "type": "createAlert",
      "status": "would_execute",
      "details": {
        "type": "COMPLIANCE",
        "title": "Blocklisted Company Detected",
        "severity": "CRITICAL"
      }
    },
    {
      "type": "updateEntityStatus",
      "status": "would_execute",
      "details": {
        "status": "blocked",
        "reason": "CNPJ in blocklist"
      }
    }
  ],
  "debug": {
    "entitySnapshot": {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "type": "company",
      "taxId": "33.592.510/0001-54",
      "name": "Test Company"
    },
    "conditionEvaluationOrder": ["cond-1"],
    "shortCircuited": false,
    "cacheHits": 0
  }
}
```

### No Match

```json theme={null}
{
  "matched": false,
  "score": 0,
  "executionTime": 23,
  "conditions": {
    "operator": "AND",
    "result": false,
    "conditions": [
      {
        "id": "cond-1",
        "field": "enrichmentData.normalized.taxId",
        "operator": "eq",
        "expectedValue": "33.592.510/0001-54",
        "actualValue": "12.345.678/0001-90",
        "result": false
      }
    ]
  },
  "actions": [],
  "debug": null
}
```

### Production Mode - Actions Executed

```json theme={null}
{
  "matched": true,
  "score": 85,
  "executionTime": 156,
  "conditions": {
    "operator": "AND",
    "result": true,
    "conditions": [...]
  },
  "actions": [
    {
      "type": "createAlert",
      "status": "executed",
      "alertId": "alert-uuid-123",
      "details": {
        "type": "COMPLIANCE",
        "title": "Blocklisted Company Detected",
        "severity": "CRITICAL"
      }
    },
    {
      "type": "updateEntityStatus",
      "status": "executed",
      "details": {
        "previousStatus": "active",
        "newStatus": "blocked",
        "reason": "CNPJ in blocklist"
      }
    }
  ]
}
```

## Error Responses

### 404 Not Found - Rule

```json theme={null}
{
  "error": "Rule not found",
  "ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
```

### 404 Not Found - Entity

```json theme={null}
{
  "error": "Entity not found",
  "entityId": "550e8400-e29b-41d4-a716-446655440000"
}
```

### 400 Bad Request - Type Mismatch

```json theme={null}
{
  "error": "Entity type mismatch",
  "details": {
    "ruleTargetTypes": ["company"],
    "entityType": "person",
    "message": "This rule only applies to company entities"
  }
}
```

### 400 Bad Request - Disabled Rule

```json theme={null}
{
  "error": "Rule is disabled",
  "ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
```

## Use Cases

### Testing New Rules

```javascript theme={null}
// Test a new rule against sample entities before enabling
async function testRuleAgainstSamples(ruleId, sampleEntityIds) {
  const results = [];

  for (const entityId of sampleEntityIds) {
    const response = await fetch(
      `http://api.gu1.ai/rules/${ruleId}/execute`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          entityId,
          testMode: true,
          includeDebug: true
        })
      }
    );

    const result = await response.json();
    results.push({
      entityId,
      matched: result.matched,
      executionTime: result.executionTime
    });
  }

  console.log('Test Results:', results);
  console.log('Match rate:',
    results.filter(r => r.matched).length / results.length * 100 + '%'
  );

  return results;
}
```

### Debugging Rule Behavior

```python theme={null}
def debug_rule_execution(rule_id, entity_id):
    """Get detailed debug information for rule execution"""
    response = requests.post(
        f'http://api.gu1.ai/rules/{rule_id}/execute',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'entityId': entity_id,
            'testMode': True,
            'includeDebug': True
        }
    )

    result = response.json()

    print(f"Rule Matched: {result['matched']}")
    print(f"Execution Time: {result['executionTime']}ms")
    print("\nCondition Evaluation:")

    for condition in result['conditions']['conditions']:
        print(f"  - {condition['field']}: ", end='')
        print(f"{condition['actualValue']} {condition['operator']} {condition['expectedValue']}")
        print(f"    Result: {'✅ Pass' if condition['result'] else '❌ Fail'}")

    if result.get('debug'):
        print("\nDebug Info:")
        print(f"  Short-circuited: {result['debug']['shortCircuited']}")
        print(f"  Cache hits: {result['debug']['cacheHits']}")

    return result
```

### Batch Testing

```javascript theme={null}
// Test multiple entities against a rule
async function batchTestRule(ruleId, entityIds) {
  const batchSize = 10;
  const results = {
    total: entityIds.length,
    matched: 0,
    failed: 0,
    avgExecutionTime: 0
  };

  for (let i = 0; i < entityIds.length; i += batchSize) {
    const batch = entityIds.slice(i, i + batchSize);
    const promises = batch.map(entityId =>
      fetch(`http://api.gu1.ai/rules/${ruleId}/execute`, {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          entityId,
          testMode: true
        })
      }).then(r => r.json())
    );

    const batchResults = await Promise.all(promises);

    batchResults.forEach(result => {
      if (result.matched) results.matched++;
      results.avgExecutionTime += result.executionTime;
    });
  }

  results.avgExecutionTime = Math.round(
    results.avgExecutionTime / entityIds.length
  );

  console.log('Batch Test Results:', results);
  return results;
}
```

## Best Practices

1. **Always Test First**: Use `testMode: true` before running rules in production
2. **Enable Debug for Development**: Use `includeDebug: true` to understand rule behavior
3. **Test Edge Cases**: Test with entities that should and shouldn't match
4. **Monitor Execution Time**: Optimize rules that take longer than 200ms
5. **Validate Actions**: Review action details before enabling production mode
6. **Use Shadow Mode**: Deploy rules with `status: "shadow"` to log matches without executing actions

## Performance Notes

* Average execution time: 50-150ms
* Sync rules block the request, async rules return immediately
* Complex nested conditions may increase execution time
* Array field evaluations with filters add \~10-30ms per array

## See Also

* [Create Rule](/en/api-reference/rules/create) - Create new rules
* [Condition Fields Reference](/en/api-reference/rules/conditions) - Available condition fields
* [List Rules](/en/api-reference/rules/list) - Query rules
* [Update Rule](/en/api-reference/rules/update) - Modify existing rules
