# Dry Runs, Batches & Idempotency

> Bounded 50-item batch mutations, actor-scoped Idempotency-Key deduplication with SHA-256 request binding, /agent/v1/operations lookup, and ?dryRun=true validation.

Autonomous agents frequently retry timed-out HTTP requests, update dozens of entries in a single workflow, and validate complex payloads before committing them. OvertCMS provides three built-in primitives to make these workflows safe and deterministic: the **Bounded Batch API**, **Actor-Scoped Idempotency**, and **Dry-Run Validation**.

---

## Bounded Batch API (Up to 50 Items)

Execute multiple operations on a single post type in one HTTP call:

```text
POST /agent/v1/collections/{postType}/batch
```

(Or via MCP using [`cms_batch_entries`](/agents/mcp-server#8-cms_batch_entries).)

### Rules & Bounds

- **Hard item limit:** Must contain between **1 and 50** items (`MaxBatchItems = 50`). Empty arrays or batches with more than 50 items fail fast with `422 batch_size_exceeded`.
- **Upfront scope & quota checks:** Before executing item `0`, OvertCMS checks:
  - `entries:write` and `write` access on `{postType}`
  - `entries:publish` if any item uses `publish`, `schedule`, `unpublish`, `archive`, or `create` with a non-`draft` status
  - `entries:delete` if any item uses `trash`
  - Site kill switch (`agent_writes_paused`) and per-key daily write quota for the full batch size (`len(items)`)
- **Sequential execution with per-item isolation:** Items execute sequentially in array order through the exact same authoritative Core entry methods (validation, optimistic locking, references, media checks, audit logs, outbox events). A validation or conflict error on one item records an `error` on that item's receipt without aborting the rest of the batch.
- **Supported `op` values:** `create`, `update`, `publish`, `schedule`, `unpublish`, `archive`, `trash` (any other `op` records `invalid_batch_op` on that item).

### Request Example

```json
{
  "items": [
    {
      "op": "create",
      "slug": "q4-release-notes",
      "data": {
        "title": "Q4 Release Notes",
        "body": "<p>Highlights from Q4.</p>"
      },
      "commitMessage": "Create Q4 release notes draft"
    },
    {
      "op": "update",
      "id": "0195c8a2-0001-7000-8000-000000000001",
      "expectedVersion": 2,
      "data": { "featured": true },
      "clearFields": ["subtitle"]
    },
    {
      "op": "publish",
      "id": "0195c8a2-0001-7000-8000-000000000002",
      "expectedVersion": 5
    }
  ]
}
```

### Per-Item Receipt Structure (`200 OK`)

Every item produces a `BatchItemResult` at its matching `index`:

| Field | Type | Present When | Description |
| --- | --- | --- | --- |
| `index` | `integer` | Always | Zero-based index matching the input `items[]` array. |
| `op` | `string` | Always | Operation name from the request item. |
| `id` | `string` | When known | Created or mutated entry ID. |
| `status` | `string` | On success | Resulting entry lifecycle status (`draft`, `published`, etc.). |
| `version` | `integer` | On success | Resulting entry version number. |
| `changed` | `boolean` | On `update` success | `false` when the update was a no-op (no version bump), `true` otherwise. |
| `error` | `APIError` | On failure | Canonical error object (`code`, `message`, `retryable`, `applied: false`, `issues?`, `details?`). |

```json
{
  "results": [
    {
      "index": 0,
      "op": "create",
      "id": "0195c8ff-1111-7000-8000-000000000001",
      "status": "draft",
      "version": 1
    },
    {
      "index": 1,
      "op": "update",
      "id": "0195c8a2-0001-7000-8000-000000000001",
      "status": "draft",
      "version": 3,
      "changed": true
    },
    {
      "index": 2,
      "op": "publish",
      "id": "0195c8a2-0001-7000-8000-000000000002",
      "error": {
        "code": "version_conflict",
        "message": "entry \"0195c8a2-0001-7000-8000-000000000002\" was modified concurrently (current version is 6)",
        "retryable": false,
        "applied": false,
        "details": {
          "expectedVersion": 5,
          "currentVersion": 6
        }
      }
    }
  ]
}
```

---

## Idempotency (`Idempotency-Key`)

Attach a unique `Idempotency-Key` header (e.g., a UUIDv4 or deterministic job ID) to any mutating HTTP request (`POST`, `PATCH`, `PUT`, `DELETE`) on the Agent Plane—or pass `idempotencyKey` on mutating MCP tool calls—so network retries never create duplicate entries or double-apply transitions.

### Key Constraints & Actor Scoping

- **Length & characters:** Maximum **128 characters**; ASCII control characters (`< 0x20` or `0x7F`) are rejected with `400 invalid_idempotency_key`.
- **Actor-scoped storage:** Keys are atomically claimed under `(site_id, actor_scope, idempotency_key)` where `actor_scope` is `<actorKind>:<actorId>` (for example, `api_key:0195...` or `mcp:0195...`). One API key can never replay, collide with, or inspect another actor's operation receipt (`403 idempotency_key_forbidden`).
- **SHA-256 request hash binding:** Every claim binds `SHA-256(METHOD + "|" + REQUEST_URI + "|" + RAW_BODY)` (or `SHA-256("MCP|" + toolName + "|" + rawArgs)` on MCP). Reusing an existing `Idempotency-Key` with a different method, URL, or payload returns **`409 Conflict` (`idempotency_key_conflict`)**.

### Replay, Concurrency, and Non-Cached Failures

| Scenario | Status & Headers | Behavior |
| --- | --- | --- |
| **First execution** | Original status (`200`/`201`/`422`/etc.) | Claims key (`in_progress` lease TTL: **60 seconds**), executes handler, stores receipt for **24 hours**, returns response. |
| **Safe retry (identical hash, completed)** | Original status + **`Idempotency-Replayed: true`** | Returns the exact stored HTTP status and response body without re-executing the mutation. |
| **Concurrent retry (identical hash, still running)** | **`409 Conflict`** (`operation_in_progress`) + **`Retry-After: 1`** | Tells the caller the first attempt is still executing; retry after 1 second. |
| **Key reuse with different request** | **`409 Conflict`** (`idempotency_key_conflict`) | Protects against accidental key reuse across distinct mutations. |
| **Authz, rate-limit, or kill-switch rejection (`401`, `403`, `429`, `503`)** | Original status (no replay header) | **Not cached**—the idempotency claim is released immediately so the caller can retry with the same key once the transient condition clears. |
| **Unhandled internal failure (`500`)** | `500` | Recorded with `status: "failed"` (panic recovery guarantees a key is never stranded `in_progress`). |

<Note>
  Cached response bodies are capped at **1 MiB** (`MaxOperationResponseBodyBytes`). Streaming or large (`> 1 MiB`) `multipart/form-data` media uploads bypass HTTP idempotency body buffering automatically.
</Note>

### Inspecting Operation Receipts (`GET /agent/v1/operations/{idempotencyKey}`)

If a connection drops before your agent receives the HTTP response, you can either safely retry the exact same request with the same `Idempotency-Key` **or** query the receipt directly (requires `entries:read`, strictly scoped to the calling actor):

```bash
curl -s https://cms.example.dev/agent/v1/operations/job-2026-11-25-001 \
  -H "Authorization: Bearer ocms_live_0123456789abcdef_..."
```

```json
{
  "operation": {
    "id": "0195c900-aaaa-7000-8000-000000000001",
    "siteId": "0195c800-0000-7000-8000-000000000001",
    "idempotencyKey": "job-2026-11-25-001",
    "actorId": "0195c810-0000-7000-8000-000000000099",
    "method": "POST",
    "path": "/agent/v1/collections/posts/entries",
    "requestHash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "status": "completed",
    "responseStatus": 201,
    "responseBody": {
      "entry": {
        "id": "0195c900-bbbb-7000-8000-000000000002",
        "status": "draft",
        "version": 1
      }
    },
    "createdAt": "2026-11-25T16:10:00Z",
    "expiresAt": "2026-11-26T16:10:00Z"
  }
}
```

---

## Dry-Run Validation (`?dryRun=true`)

Test an entry creation payload end-to-end without writing to the database or consuming your daily write quota:

- **HTTP:** `POST /agent/v1/collections/{postType}/entries?dryRun=true` (or include `"dryRun": true` in the JSON body).
- **MCP:** Call `cms_create_entry` with `"dryRun": true`.

### What Dry Run Validates

Dry run executes the **full** server-side validation pipeline:
1. Locale, singleton existence, capability, status, and `scheduledAt`/`unpublishAt` checks
2. All 19 field types, constraints, `requiredOn`, write permissions (`readOnly` / `aiWritable`), HTML5 canonicalization, and `<cms-block>` validation
3. Reference existence, non-trashed status, and target post-type checks
4. Media asset existence, `ready` status, kind match, and media field constraints (inline external image URLs are checked without writing new media records)
5. Slug uniqueness and `unique: true` field uniqueness checks

### Side-Effect Guarantees

- **Zero database writes:** Never creates an entry, version, redirect, outbox event, or audit row.
- **Never touches `operations`:** Even if an `Idempotency-Key` header is present, dry runs bypass idempotency storage completely so the same key remains free for the real commit.
- **No write-quota deduction:** Does not increment daily write counters and remains usable even when `agentWritesPaused` is active.

### Response (`200 OK`)

```json
{
  "dryRun": true,
  "valid": true,
  "normalizedData": {
    "title": "Zero-Trust Headless CMS",
    "slug": "zero-trust-headless-cms",
    "body": "<p>Clean canonical HTML5.</p>"
  },
  "warnings": [],
  "publicUrl": "https://acme.dev/blog/zero-trust-headless-cms"
}
```

If any check fails, dry run returns the exact same `422 validation_error` / `409` error payload that a real create would return.
