# Data Model: Unified Operations Runs

## Entities

### `OperationRun`
Canonical record for all long-running tenant operations.

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `id` | BigInt | Yes | Primary Key |
| `tenant_id` | BigInt | Yes | FK to Tenants |
| `user_id` | BigInt | No | FK to Users (Initiator). Null for system/scheduler. |
| `initiator_name` | String | Yes | Snapshot of user name or "System". |
| `type` | String | Yes | stable taxonomy e.g., `inventory.sync`. |
| `status` | String | Yes | Lifecycle state: `queued`, `running`, `completed`. |
| `outcome` | String | Yes | Result bucket: `pending`, `succeeded`, `partially_succeeded`, `failed`, `cancelled`. |
| `run_identity_hash` | String | Yes | Deterministic hash for idempotency. |
| `summary_counts` | JSONB | No | `{ "total": 10, "success": 8, "failed": 2, "skipped": 0 }` |
| `failure_summary` | JSONB | No | List of sanitized errors: `[{ "code": "graph.throttled", "message": "Throttled (retrying)", "count": 1 }]` |
| `context` | JSONB | No | Run-specific metadata. e.g., `{ "restore_run_id": 123, "selection": [...] }` |
| `started_at` | Timestamp | No | When execution began. |
| `completed_at` | Timestamp | No | When execution finished. |
| `created_at` | Timestamp | Yes | |
| `updated_at` | Timestamp | Yes | |

**Indexes**:
- `(tenant_id, run_identity_hash)` UNIQUE WHERE status IN ('queued', 'running')
- `(tenant_id, type, created_at)` for filtering/sorting
- `(tenant_id, created_at)` for default sort

### `RestoreRun` (Existing)
Remains the domain source of truth for Restore.
- Linked via `OperationRun.context['restore_run_id']`.
- Adapter row is created/visible only once `RestoreRunStatus=previewed` (or later).
  - When `RestoreRunStatus=previewed`, the adapter uses `OperationRun.status=queued` and `OperationRun.outcome=pending`.
- `OperationRun` mirrors the restore execution lifecycle for Monitoring visibility (restore domain history remains owned by `RestoreRun`).

## Enums

### `OperationRunStatus`
- `queued`
- `running`
- `completed`

### `OperationRunOutcome`
- `pending` (default when running/queued)
- `succeeded`
- `partially_succeeded`
- `failed`
- `cancelled` (reserved/future; MUST NOT be produced by 054)

**UI label mapping** (display-only):

- `pending` → “Pending”
- `succeeded` → “Succeeded”
- `partially_succeeded` → “Partially succeeded”
- `failed` → “Failed”
- `cancelled` → “Cancelled” (reserved)

## State Transitions

`OperationRun.status` transitions:

- `queued` → `running` → `completed`

`OperationRun.outcome` transitions:

- `pending` while `status` is `queued` or `running`
- one of `succeeded`, `partially_succeeded`, `failed`, `cancelled` when `status` is `completed`

## Relationships
- `OperationRun` belongs to `Tenant`.
- `OperationRun` belongs to `User` (optional).
