$ fssg build --deterministic --validate |

Build a Compensation Ledger for AI Agent Workflows

AI Engineering

An AI agent cannot roll back an email, a payment, or a published release. Once an effect leaves the process boundary, recovery needs a new forward action—and a durable record of why that action is allowed.

I call that record a compensation ledger. It is smaller than a workflow engine and more honest than a generic undo() function. Each completed external effect writes enough information to decide, execute, retry, and audit its compensating action later.

This is an implementation guide for adding that boundary to an existing agent loop. It extends my recovery decision guide with a concrete artifact rather than another recovery taxonomy.

Start with one row per committed effect

A useful ledger does not store only the tool name. It binds the original effect to its receipt, compensation command, current precondition, and recovery status.

CREATE TABLE compensation_ledger (
  run_id              TEXT NOT NULL,
  sequence_no         INTEGER NOT NULL,
  effect_id           TEXT NOT NULL UNIQUE,
  action              TEXT NOT NULL,
  request_json        TEXT NOT NULL,
  receipt_json        TEXT NOT NULL,
  compensate_action   TEXT,
  compensate_json     TEXT,
  precondition_json   TEXT,
  status              TEXT NOT NULL,
  compensation_id     TEXT UNIQUE,
  compensation_receipt_json TEXT,
  last_error          TEXT,
  PRIMARY KEY (run_id, sequence_no)
);

receipt_json matters because intention is not proof. precondition_json matters because the world may change between the forward action and recovery. compensation_id matters because compensation can fail after the remote system commits but before the agent records success—the same ambiguous window as any other side effect.

The model may propose these fields. The execution layer must validate and persist them.

Register compensation before advancing

Suppose an agent provisions a preview environment in three steps:

  1. reserve a DNS name;
  2. create a deployment;
  3. publish a notification.

If deployment creation succeeds, the runtime should commit the forward receipt and compensation plan before it lets the agent move to step three:

def record_effect(db, *, run_id, seq, effect_id, action,
                  request, receipt, compensate_action,
                  compensate_request, precondition):
    db.execute(
        """INSERT INTO compensation_ledger
           (run_id, sequence_no, effect_id, action, request_json,
            receipt_json, compensate_action, compensate_json,
            precondition_json, status)
           VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'committed')""",
        (run_id, seq, effect_id, action, json.dumps(request),
         json.dumps(receipt), compensate_action,
         json.dumps(compensate_request), json.dumps(precondition)),
    )
    db.commit()

There is still a distributed-systems boundary between the remote call and this local commit. When the destination supports an idempotency key, send a stable effect ID before every retry. When it supports lookup, reconcile the effect before inserting the receipt. A compensation ledger does not replace idempotency or reconciliation; it begins after the runtime can prove what committed.

Treat compensation as its own effect

The dangerous shortcut is to mark the original row undone before calling the compensating API. That creates a lie if the process crashes during the call.

Use explicit transitions:

committed
  -> compensation_planned
  -> compensation_started
  -> compensated
                    \
                     -> compensation_unknown
                     -> manual_review

Derive a stable compensation identity from the original effect:

compensation_id = f"compensate:{effect_id}:v1"

Then execute conservatively:

def compensate(row, adapter):
    current = adapter.inspect(row.effect_id)

    if not precondition_holds(current, row.precondition_json):
        return mark_manual_review(row, "state changed")

    mark_started(row, row.compensation_id)
    try:
        receipt = adapter.execute(
            row.compensate_action,
            row.compensate_json,
            idempotency_key=row.compensation_id,
        )
    except TimeoutError:
        return mark_unknown(row)

    return mark_compensated(row, receipt)

A timeout after adapter.execute() is not permission to mint a new compensation ID. Reconcile the existing ID. If the destination cannot deduplicate or answer whether the compensation happened, stop in compensation_unknown instead of guessing.

Reverse order is a default, not a law

LIFO is a useful starting policy: later effects often depend on earlier ones, so unwind the newest committed effect first.

SELECT * FROM compensation_ledger
WHERE run_id = ? AND status IN ('committed', 'compensation_unknown')
ORDER BY sequence_no DESC;

But domain rules outrank stack order. A notification may be irreversible and require a correction rather than deletion. A DNS reservation may need to stay until a deployment is fully removed. A refund may require approval even when canceling a reservation does not.

I therefore store a recovery class beside each action in real designs:

Class Runtime behavior
automatic Compensate when the precondition still holds
approval_required Prepare the command, then pause
corrective_only Create a correction; never claim erasure
irreversible Preserve evidence and escalate

The classification belongs to tool policy, not to a fresh model decision after failure.

Keep the first version deliberately small

You do not need to migrate the whole application to a durable workflow platform to gain this boundary. A minimal integration has four hooks:

before effect   -> assign stable effect_id
on success      -> store receipt + compensation plan
on run failure  -> enumerate committed effects
on recovery     -> verify precondition + execute named compensation

Start with one high-consequence tool. Reject calls that cannot provide a stable identity and a success receipt. Add a dry-run endpoint that prints the planned compensations without executing them. Test three failure points: before the remote call, after remote commit but before local receipt, and during compensation.

This follows the same principle as the AI engineering runtime: the system around the model owns durable state transitions. The agent can decide that a preview environment is no longer needed. It should not decide that a remote effect vanished because a local function returned an exception.

Boundaries this ledger does not solve

A local SQLite ledger is not enough for multiple writers unless ownership and locking are explicit. A receipt can be stale. A destination may lack idempotency and lookup. Compensation may be legally or operationally impossible. Concurrent actors may invalidate the recorded precondition.

In those cases, the ledger still helps because it preserves the honest state: committed, unknown, blocked, or manually resolved. It does not manufacture exactly-once execution.

That is the standard I want from agent recovery. Not “the run tried to undo everything,” but a queryable chain:

original intent -> committed effect -> observed state
-> authorized compensation -> compensation receipt

Reality is not a transaction log the agent can erase. The least a reliable agent can do is keep a ledger precise enough to repair it without improvising.

Sources

FACET AI CLI Terminal
facet@ai:~$