---
name: rebase-entity-history
description: Guide for tracking and reverting entity changes with Rebase's built-in history/audit-log system. Use this skill when the user needs entity versioning, change tracking, audit logs, reverting to previous versions, or understanding how history entities work.
---

# Rebase Entity History

Rebase includes a built-in entity history system that records entities of every create, update, and delete operation. History entries are stored in a dedicated PostgreSQL table and exposed via REST API endpoints. The admin panel shows the revisions in the record inspector, with one-click revert.

> **IMPORTANT FOR AGENTS:** Entity history requires **two** things to be enabled: (1) the global `history` flag in the backend config, AND (2) `history: true` on each individual table. If either is missing, no history is recorded for that table.
>
> Under the **runtime** (`rebase dev`, `rebase start`, the published image — the default) the global flag comes from `REBASE_HISTORY`, which **defaults to `true`**. So in a scaffolded project the global half is already on and the per-table `history: true` (in its `defineTable`) is the one you have to write. A hand-written `initializeRebaseBackend` call has to pass `history` itself.

## Enabling History

### Step 1 — Enable History Globally (Backend Config)

In a scaffolded project this is the `REBASE_HISTORY` environment variable,
which the runtime passes as the backend's `history` option and which defaults
to `true`. An ejected server adds `history: true` (or a configuration object)
to `initializeRebaseBackend()`:

```typescript
import { initializeRebaseBackend } from "@rebasepro/server";

await initializeRebaseBackend({
    app,
    server,
    // `db` from `createPostgresDatabaseConnection(env.DATABASE_URL)`: the adapter
    // needs the connection; a connection string alone opens no pool.
    database: createPostgresAdapter({ connection: db, connectionString: env.DATABASE_URL }),
    tables: [products, logs, users],

    // ── Enable entity history globally ──
    history: true,

    auth: { /* ... */ },
});
```

The `history` property accepts either:

| Value | Behavior |
|-------|----------|
| `true` | Enable history with default retention settings |
| `{ retention: number }` | Enable history with a custom TTL (in days) for automatic pruning |
| `false` / `undefined` | History disabled (default) |

```typescript
// Custom retention: prune entries older than 30 days
history: { retention: 30 },
```

### Step 2 — Enable History Per Table

On each table that should be tracked, set `history: true` in its `defineTable`:

```typescript
// backend/schema/products.ts
import { defineTable, col } from "@rebasepro/server/schema";

export const products = defineTable("products", {
    columns: {
        id: col.uuid().primaryKey().defaultRandom(),
        name: col.text().notNull(),
        price: col.numeric({ precision: 10, scale: 2 }),
        status: col.enum(["draft", "active"]).notNull().default("draft")
    },
    rls: "admin-only",

    // ── Enable history for this table ──
    history: true
});
```

> **WARNING FOR AGENTS:** Setting `history: true` on a table has **no effect** if the backend's `history` is off (`REBASE_HISTORY=false`, or an ejected server that leaves the option out). Both must be enabled.

## How History Recording Works

On Postgres, history is recorded **inside the write's transaction** and awaited: the row and its history entry commit together or neither does. A failed history insert therefore fails the write — deliberately, because a trail with silent gaps cannot tell "nothing changed" from "the entry was lost". Only the pruning pass afterwards is non-blocking.

### When History Entries Are Created

| Operation | Action Recorded | What's Stored |
|-----------|----------------|---------------|
| Create entity | `"create"` | Full entity values |
| Update entity | `"update"` | New values + previous values + list of changed fields |
| Delete entity | `"delete"` | Final entity values before deletion |

### Skipped Updates

Updates that produce **zero actual field changes** are silently skipped — no history entry is created. The system uses deep structural comparison (not reference equality) to detect whether values actually changed, including nested objects, arrays, and Date values.

### Changed Field Detection

For updates, the system compares old and new values field-by-field and records only the keys that changed. Internal metadata fields (prefixed with `__`) are excluded from change detection.

## History Entry Format

Each history entry has the following structure:

| Field | Type | Description |
|-------|------|-------------|
| `id` | `string` | UUID primary key of the history entry |
| `table_name` | `string` | The table slug / table path |
| `entity_id` | `string` | The ID of the entity this entry belongs to |
| `action` | `"create" \| "update" \| "delete"` | What operation was performed |
| `changed_fields` | `string[] \| null` | Array of field names that changed (only for updates) |
| `values` | `Record<string, unknown> \| null` | Full entity values at the time of the change (for a delete, the deleted entity) — the row as the REST API serves it: a `belongsTo` as its foreign key, never the related row's values. An entry an older version recorded with `{ "__type": "date" }` envelopes or `{ "__type": "relation" }` refs is served (and reverted) as plain values: the date, the foreign key, the related row's key |
| `previous_values` | `Record<string, unknown> \| null` | On an update, what the changed fields held before it (`null` for creates and deletes) — see `format` |
| `updated_by` | `string \| null` | UID of the user who made the change |
| `updated_at` | `string` (ISO 8601) | Timestamp of when the change was recorded |
| `format` | `1 \| 2` | `2` (since 0.25): `previous_values` holds the `changed_fields` only. `1` (older entries): it holds the whole previous entity |

### Example History Entry (JSON)

```json
{
    "id": "a1b2c3d4-5678-90ab-cdef-1234567890ab",
    "table_name": "products",
    "entity_id": "42",
    "action": "update",
    "changed_fields": ["price", "status"],
    "values": {
        "name": "Widget",
        "price": 29.99,
        "status": "active"
    },
    "previous_values": {
        "price": 19.99,
        "status": "draft"
    },
    "updated_by": "user-uuid-here",
    "updated_at": "2025-01-15T10:30:00.000Z",
    "format": 2
}
```

## REST API Endpoints

History endpoints are mounted under the data router at `{basePath}/data/:slug/:entityId/history`. They require the same authentication as regular data routes.

### List History Entries

```
GET /api/data/:slug/:entityId/history
```

| Query Parameter | Type | Default | Description |
|-----------------|------|---------|-------------|
| `limit` | `number` | `20` | Number of entries to return (max `100`; above it the request is refused with `400 INVALID_LIMIT`) |
| `offset` | `number` | `0` | Number of entries to skip |

**Response:**

```json
{
    "data": [
        {
            "id": "abc-123",
            "table_name": "products",
            "entity_id": "42",
            "action": "update",
            "changed_fields": ["price"],
            "values": { "name": "Widget", "price": 29.99 },
            "previous_values": { "price": 19.99 },
            "updated_by": "user-uuid",
            "updated_at": "2025-01-15T10:30:00.000Z",
            "format": 2
        }
    ],
    "meta": {
        "total": 47,
        "limit": 20,
        "offset": 0,
        "hasMore": true
    }
}
```

**Error Responses:**

| Status | Condition |
|--------|-----------|
| `404` | Table slug not found, or the entity does not exist / the caller may not read it (RLS — a 404, not a 403, so its existence is not confirmed) |
| `400` | History not enabled for this table, or `limit` above 100 (`INVALID_LIMIT`) |
| `403` | `SCOPE_MISSING` — an API key without `data:read` on the table |

Access is the row's: the route reads the entity through the caller's RLS-scoped driver first (a row in the trash included), and only then the history table.

### Revert to a Historical Version

```
POST /api/data/:slug/:entityId/history/:historyId/revert
```

No request body is needed. The server fetches the stored `values` from the history entry and saves them through the normal entity save path.

**Response:**

```json
{
    "data": { "id": 42, "name": "Widget", "price": 19.99, "status": "draft" },
    "meta": {
        "reverted_from": "abc-123"
    }
}
```

`data` is the saved row, flat, as the data API returns it. An entry recorded by an older version can hold keys the row has no column for (an `afterRead`-computed field, a relation stored as the admin's view of it); the revert leaves them out and names them in `meta.dropped_fields`.

**Error Responses:**

| Status | Condition |
|--------|-----------|
| `404` | Table, entity (or one the caller may not read) or history entry not found |
| `403` | `SCOPE_MISSING` — an API key without `data:write` on the table |
| `400` | History not enabled for the table |
| `400` | History entry belongs to a different entity (cross-entity revert blocked) |
| `400` | History entry has no stored values |

> **IMPORTANT FOR AGENTS:** Reverting goes through the **normal save path**, which means: (1) it triggers all `beforeSave` / `afterSave` hooks, (2) it creates a **new history entry** for the revert operation itself, providing a complete audit trail, and (3) it notifies real-time subscribers of the change.

### Example: Fetch and Revert via cURL

`$TOKEN` is an access token — the `accessToken` a sign-in returns, or an API key.

```bash
# List history for entity 42 in the "products" table
curl -H "Authorization: Bearer $TOKEN" \
     "http://localhost:3001/api/data/products/42/history?limit=10&offset=0"

# Revert entity 42 to the state captured in history entry "abc-123"
curl -X POST \
     -H "Authorization: Bearer $TOKEN" \
     "http://localhost:3001/api/data/products/42/history/abc-123/revert"
```

### Example: Fetch via JavaScript (fetch API)

```typescript
async function getEntityHistory(slug: string, entityId: string, token: string) {
    const response = await fetch(
        `http://localhost:3001/api/data/${slug}/${entityId}/history?limit=20&offset=0`,
        { headers: { Authorization: `Bearer ${token}` } }
    );
    const result = await response.json();
    // result.data — array of HistoryEntryData
    // result.meta — { total, limit, offset, hasMore }
    return result;
}

async function revertEntity(slug: string, entityId: string, historyId: string, token: string) {
    const response = await fetch(
        `http://localhost:3001/api/data/${slug}/${entityId}/history/${historyId}/revert`,
        {
            method: "POST",
            headers: { Authorization: `Bearer ${token}` },
        }
    );
    const result = await response.json();
    // result.data — the reverted row, flat
    // result.meta.reverted_from — the history entry ID used
    return result;
}
```

## Pagination

History entries are returned in **reverse chronological order** (newest first).

| Parameter | Default | Maximum | Minimum |
|-----------|---------|---------|---------|
| `limit` | `20` | `100` (above it: `400 INVALID_LIMIT`, not clamped) | — |
| `offset` | `0` | N/A | `0` (clamped with `Math.max`) |

Use the `meta.hasMore` boolean in the response to determine if more pages are available:

```typescript
let offset = 0;
const limit = 20;
const allEntries: unknown[] = [];

while (true) {
    const result = await fetch(`/api/data/products/42/history?limit=${limit}&offset=${offset}`);
    const json = await result.json();
    allEntries.push(...json.data);

    if (!json.meta.hasMore) break;
    offset += limit;
}
```

## Database Storage

### Table Schema

History data is stored in a dedicated table in the `rebase` schema:

```sql
-- Auto-created on startup when history is enabled
CREATE TABLE IF NOT EXISTS rebase.entity_history (
    id TEXT PRIMARY KEY DEFAULT gen_random_uuid()::text,
    table_name TEXT NOT NULL,
    entity_id TEXT NOT NULL,
    action TEXT NOT NULL,          -- 'create', 'update', or 'delete'
    changed_fields TEXT[],         -- array of changed field names (updates only)
    "values" JSONB,               -- full entity values
    previous_values JSONB,        -- updates only: the changed fields' previous values (format 2)
    updated_by TEXT,              -- user UID who made the change
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    format SMALLINT NOT NULL DEFAULT 1  -- 2: previous_values holds the changed fields only
);

-- Per-entity reads and pruning (its prefix serves (table_name, entity_id) lookups)
CREATE INDEX IF NOT EXISTS idx_history_time
    ON rebase.entity_history(table_name, entity_id, updated_at DESC);

-- The hourly retention sweep; built CONCURRENTLY in the background after boot
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_history_updated_at
    ON rebase.entity_history(updated_at);
```

> **IMPORTANT FOR AGENTS:** The `rebase.entity_history` table is **auto-created** on server startup when history is enabled. You do NOT need to create it manually or include it in migrations. The `rebase` schema is also created automatically if it doesn't exist. The exception is a server running with `REBASE_PROVISION=false`, which changes nothing in its database: it uses the table an earlier provisioning boot created, and where there is none, writes to a collection with `history: true` are refused.

### Storage Characteristics

- **Values are stored as JSONB** — `values` is the full entity, not a diff, so a revert simply writes it back. An update's `previous_values` holds only the fields it changed (`format: 2`); entries recorded before 0.25 hold the whole previous entity (`format: 1`).
- **All tables share one history table** — the `table_name` column distinguishes between them.
- **Entity IDs are stored as text** — regardless of the original column type.
- **Indexes**: `(table_name, entity_id, updated_at DESC)` for per-entity lookups, and `(updated_at)` for the retention sweep. A database from before 0.25 also had `(table_name, entity_id)`; boot drops it, as the first index covers it.

## Retention and Automatic Pruning

The history service automatically prunes old entries to prevent unbounded storage growth: **non-blocking** after every insert the server makes, for that entity, and **once an hour** for every entity (since 0.25). Writes through `openRebase` / `rebase console` record history but never prune: a script cannot know the server's retention, so the server prunes on its next write to that entity and in the hourly sweep.

### Retention Configuration

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `maxEntries` | `number` | `200` | Maximum entries kept per entity. Oldest pruned first |
| `ttlDays` | `number` | `90` | Entries older than this many days are deleted |

### How Pruning Works

After every history insert, one pruning statement runs in the background for that specific entity: it deletes entries older than `ttlDays` and everything beyond the newest `maxEntries`.

Once an hour, on one instance of the fleet (claimed in `rebase.cron_claims`, on the processes that run scheduled jobs), the backend also deletes every entry older than `ttlDays`, of every entity, in batches of 5,000 — so the history of an entity that is never written again, such as a deleted one, still ages out.

Pruning errors are logged but never block the main operation.

### Configuring Retention

Pass the `retention` option (in days) through the global history config:

```typescript no-verify
await initializeRebaseBackend({
    // ...
    history: { retention: 30 },  // TTL of 30 days
});
```

This sets the `ttlDays` value. The `maxEntries` default of `200` is currently not configurable through the backend config and uses the service default.

### Global Pruning

There is nothing to schedule: the hourly sweep above is the global, TTL-based cleanup. `HistoryService.pruneExpired()` is what it calls.

## Admin Panel Integration

When history is enabled for a table, the admin panel offers **History** in
the record's overflow (`⋮`) menu, beside **Inspect record**. Both open the record
inspector — a panel beside the form, not a tab in front of it — so the record
you are inspecting stays on screen while you read its revisions. The panel:

- Displays a paginated list of history entries with infinite scroll
- Shows the action type, changed fields, timestamp, and user who made the change
- Provides a **Revert** button on each entry with a confirmation dialog
- After revert, resets the form with the restored values (no page refresh needed)
- Warns users to save or discard unsaved changes before reverting

Columns the backend stamps itself — the audit timestamps and the primary key —
are left out of each entry's diff: they change on every write, and the entry
already states when it happened and which record it belongs to.

No additional configuration is needed — the menu entry appears for any
table with `history: true`.

## Client SDK Usage

There is currently **no dedicated client SDK method** for entity history. History is accessed via the REST API directly (as shown in the endpoints section above).

The admin panel uses an internal `useHistory` React hook that:
- Fetches history from `GET /api/data/:slug/:entityId/history`
- Supports pagination via offset-based loading
- Provides a `revert()` function that calls `POST /api/data/:slug/:entityId/history/:historyId/revert`

For custom client applications, use `fetch()` directly against the REST endpoints with your auth token.

## Complete Setup Example

```typescript
// backend/src/index.ts
import { Hono } from "hono";
import type { HonoEnv } from "@rebasepro/server";
import { getRequestListener } from "@hono/node-server";
import { createServer } from "http";
import { initializeRebaseBackend, loadEnv } from "@rebasepro/server";
import { createPostgresAdapter } from "@rebasepro/server-postgres";
import { defineTable, defineAuthTable, col } from "@rebasepro/server/schema";
import dotenv from "dotenv";

dotenv.config({ path: "../../.env" });
const env = loadEnv();

const app = new Hono<HonoEnv>();
const server = createServer(getRequestListener(app.fetch));

// Table with history enabled (normally in backend/schema/products.ts)
const products = defineTable("products", {
    columns: {
        id: col.uuid().primaryKey().defaultRandom(),
        name: col.text().notNull(),
        price: col.numeric({ precision: 10, scale: 2 }),
        description: col.text()
    },
    rls: "admin-only",
    history: true  // ← Per-table opt-in
});

// Table WITHOUT history — high-volume tables shouldn't track history
const logs = defineTable("logs", {
    columns: {
        id: col.uuid().primaryKey().defaultRandom(),
        message: col.text().notNull(),
        level: col.enum(["info", "warn", "error"]).notNull()
    },
    rls: "admin-only"
});

// The users table auth stores accounts in.
const users = defineAuthTable("users", {
    columns: { id: col.uuid().primaryKey().defaultRandom(), email: col.text().notNull().unique() },
    rls: "admin-only"
});

await initializeRebaseBackend({
    app,
    server,
    database: createPostgresAdapter({
        connection: db, // from createPostgresDatabaseConnection(env.DATABASE_URL)
        connectionString: env.DATABASE_URL,
    }),
    tables: [products, logs, users],

    // ── Enable history globally with 60-day retention ──
    history: { retention: 60 },

    auth: {
        jwtSecret: env.JWT_SECRET,
        serviceKey: env.REBASE_SERVICE_KEY,
    },
});

console.log(`Server running at http://localhost:${env.PORT}`);
```

## Performance Considerations

### Write Performance

- On Postgres, history recording is one extra `INSERT` **inside the write's transaction**, awaited — it adds to the write's latency and holds its locks for that long. A failing insert fails the write.
- For updates, the system fetches the **previous entity values** before saving (to compute `changed_fields` and store `previous_values`). This adds one extra `SELECT` query per update.
- Updates with zero actual changes are skipped entirely — no history entry is created.

### Storage Growth

- Each history entry stores the **full JSONB entity** in `values`; an update's `previous_values` adds only the changed fields (`format: 2`, since 0.25 — older entries hold the whole previous entity too). For entities with large text fields or complex nested structures, this can grow quickly.
- Default retention limits: **200 entries per entity** and **90 days TTL**. Adjust these based on your use case.
- All tables share the single `rebase.entity_history` table — monitor its size with:

```sql
SELECT pg_size_pretty(pg_total_relation_size('rebase.entity_history'));
```

### Recommendations

| Scenario | Recommendation |
|----------|---------------|
| High-write tables (logs, analytics, events) | Do NOT enable `history: true` — the volume will overwhelm storage |
| Content tables (articles, products, pages) | Enable history — great for audit trails and undo |
| User-facing data (orders, profiles) | Enable history — useful for compliance and support |
| Large text fields (markdown, HTML, JSON blobs) | Consider shorter retention (`history: { retention: 14 }`) to limit storage |

## References

- **Documentation:** [rebase.pro/docs](https://rebase.pro/docs)
- **GitHub:** [github.com/rebasepro/rebase](https://github.com/rebasepro/rebase)
