# PostgreSQL 17: Side-effect ledger: run each tool effect once per key

> A Postgres table plus a Python decorator that records each committed side effect under a stable key, so a resumed or retried tool call returns the stored result instead of running the charge again.

Status: tested 2026-10-18 · Python + PostgreSQL (tested on PostgreSQL 17) · License: MIT · Tier: Free
Download: https://tryagentsignal.com/downloads/side-effect-ledger.zip

## What it shows
- **schema.sql**: One side_effects row per (effect, idempotency_key), with status pending, committed or failed and the stored result.
- **Reserve, then commit**: insert ... on conflict do nothing returning status. A committed row returns its stored result without calling the effect. A pending row inside its lease (default 5 min) raises EffectInFlight; after the lease, or after a failure, the next call runs the effect again.
- **@side_effect_ledger**: Wraps a tool function. The key must come from stable run data (thread_id, order_id, tool_call_id); a missing key raises.

## Mocked vs real
The tests run against a real local Postgres. See LAST_TESTED.md in the download for exactly what was run.

## Gotchas
- Derive the key from stable run data, never uuid4(): the node re-runs on resume and would get a new key.
- Runs once per key; if a worker crashes mid-call, the effect can run again after the lease expires. It is not exactly-once.
- Pass the same key to the provider when it supports one (for example Stripe's Idempotency-Key header).

## FAQ
### Is this exactly-once?
No. It runs once per key; if a worker crashes mid-call, the effect can run again after the lease expires, so also pass the same key to the provider (e.g. Stripe Idempotency-Key).

### Why not use uuid4() as the key?
The node or tool re-runs on resume and retry, so a fresh uuid4() is a new key every time and the ledger never matches.

### Do I need to sign up?
No. The page and code are free to read and copy. MIT-licensed.

## Code

### schema.sql

```
-- side-effect ledger (tested on PostgreSQL 17). MIT. https://tryagentsignal.com/templates/side-effect-ledger/
-- Safe to re-run. One row per (effect, idempotency_key). Reserve, then commit:
--   pending   = reserved, the effect may be running. now() < lease_until -> EffectInFlight;
--               lease expired -> treated as a crashed call, reclaimed, the effect runs again with the same key
--   committed = the effect ran; result holds its return value (returned, the effect is not called again)
--   failed    = the effect raised (error holds it); the next call with the same key and args runs it again
-- args_hash = sha256 of the canonical JSON of the call's args; same key + different args -> IdempotencyKeyMismatch
create table if not exists side_effects (
  run_id          text not null,
  effect          text not null,
  idempotency_key text not null,
  args_hash       text not null,
  status          text not null check (status in ('pending','committed','failed')),
  result          jsonb,
  error           text,
  created_at      timestamptz not null default now(),
  lease_until     timestamptz,
  committed_at    timestamptz,
  primary key (effect, idempotency_key)
);
create index if not exists side_effects_pending_lease_idx on side_effects (lease_until) where status = 'pending';

```

### ledger.py

```python
"""Side-effect ledger: run a side effect once per key, with a lease for crashed calls (psycopg 3, sync + async).
MIT. Needs the side_effects table from schema.sql. https://tryagentsignal.com/templates/side-effect-ledger/

    @side_effect_ledger(conn=lambda: psycopg.connect(DSN), key=lambda amount, order_id, **_: f"{order_id}:charge")
    def charge(amount, order_id, idempotency_key):      # idempotency_key is filled in for you
        return stripe.PaymentIntent.create(amount=amount, currency="usd", idempotency_key=idempotency_key).id

The key MUST come from stable run data (order_id, thread_id, tool_call_id): a resumed or retried run has
to compute the same key. str(uuid4()) is wrong: every retry gets a new key, so nothing is deduped.
Runs once per key; if a worker crashes mid-call, the effect can run again after the lease expires, so also
pass the same key to the provider (e.g. Stripe Idempotency-Key).
  committed            -> stored result returned, the effect is not called
  pending, in lease    -> EffectInFlight (another worker is mid-call, or one crashed: retry later)
  pending, lease over  -> treated as a crashed call: reclaimed atomically, the effect runs again, same key
  failed (it raised)   -> the effect runs again, same key
  same key, other args -> IdempotencyKeyMismatch, the effect is not called
A crash, kill or cancellation leaves the row pending. Results are stored as JSON (non-JSON via str()).
"""
import asyncio, functools, hashlib, inspect, json, logging, os
import psycopg
from psycopg.types.json import Jsonb

log = logging.getLogger("side_effect_ledger")
class EffectInFlight(RuntimeError): """Same effect + key is pending inside its lease. Retry later."""
class MissingIdempotencyKey(ValueError): """No key, or an empty one. Keys must come from stable run data."""
class IdempotencyKeyMismatch(ValueError): """The key was already used with different arguments."""

RESERVE = ("insert into side_effects (run_id, effect, idempotency_key, args_hash, status, lease_until) "
           "values (%s, %s, %s, %s, 'pending', now() + make_interval(secs => %s)) on conflict do nothing returning status")
READ = ("select status, result, args_hash, lease_until > now() from side_effects "
        "where effect = %s and idempotency_key = %s")
RECLAIM = ("update side_effects set status = 'pending', run_id = %s, error = null, "
           "lease_until = now() + make_interval(secs => %s) where effect = %s and idempotency_key = %s "
           "and (status = 'failed' or (status = 'pending' and lease_until < now())) returning status")
COMMIT = ("update side_effects set status = 'committed', result = %s, committed_at = now(), lease_until = null "
          "where effect = %s and idempotency_key = %s")
FAIL = ("update side_effects set status = 'failed', error = %s, lease_until = null "
        "where effect = %s and idempotency_key = %s")

def _plain(o):  # args that aren't JSON: dates/decimals/uuids by value, other objects by type only (reprs hold addresses)
    return str(o) if type(o).__module__ in ("datetime", "decimal", "uuid") else f"<{type(o).__qualname__}>"

def _decide(effect, key, args_hash, row):
    """None -> reserve again; ('hit', result); ('reclaim', status) -> try to take the row over."""
    if row is None: return None
    status, result, stored_hash, in_lease = row
    if stored_hash != args_hash:
        raise IdempotencyKeyMismatch(f"{effect}: key {key!r} was already used with different arguments")
    if status == "committed": return ("hit", result)
    if status == "pending" and in_lease: raise EffectInFlight(f"{effect}: key {key!r} is pending (lease not expired)")
    return ("reclaim", status)

def side_effect_ledger(*, conn, key, lease_seconds=300, effect=None, run_id=None):
    """conn: callable returning a psycopg connection (sync or async), a pool's .connection, or an autocommit connection."""
    if not callable(key): raise MissingIdempotencyKey("side_effect_ledger needs key=callable(*args, **kwargs) -> str")
    if conn is None: raise TypeError("side_effect_ledger needs conn=")
    def deco(fn):
        name, sig = effect or f"{fn.__module__}.{fn.__qualname__}", inspect.signature(fn)
        inject = "idempotency_key" in sig.parameters
        def prep(a, kw):
            k = key(*a, **kw)
            if k is None or str(k).strip() == "":
                raise MissingIdempotencyKey(f"{name}: key() returned {k!r}; derive it from stable run data")
            b = sig.bind_partial(*a, **kw); b.apply_defaults(); b.arguments.pop("idempotency_key", None)
            h = hashlib.sha256(json.dumps(b.arguments, sort_keys=True, default=_plain, separators=(",", ":")).encode()).hexdigest()
            lease = float(os.environ.get("AGENTSIGNAL_LEDGER_LEASE_S", lease_seconds))
            return str(k), str(run_id(*a, **kw) if run_id else k), h, lease
        def call(a, kw, k): return fn(*a, **kw, **({"idempotency_key": k} if inject else {}))
        def jsonb(v): return Jsonb(v, dumps=functools.partial(json.dumps, default=str))
        def warn(k, why): log.warning("re-running %s key %r (%s); same key passed again", name, k, why)

        @functools.wraps(fn)
        async def awrapper(*a, **kw):
            k, rid, h, lease = prep(a, kw)
            async with _aconnect(conn) as c:
                async def q(sql, p):
                    if isinstance(c, psycopg.AsyncConnection): return await (await c.execute(sql, p)).fetchone()
                    return await asyncio.to_thread(lambda: c.execute(sql, p).fetchone())
                for _ in range(5):
                    if await q(RESERVE, (rid, name, k, h, lease)): break
                    d = _decide(name, k, h, await q(READ, (name, k)))
                    if d and d[0] == "hit": return d[1]
                    if d and await q(RECLAIM, (rid, lease, name, k)): warn(k, d[1]); break
                else: raise EffectInFlight(f"{name}: key {k!r} is contended")
                try: res = await call(a, kw, k)
                except Exception as e:  # crash/cancel (BaseException) leaves it pending -> lease
                    await q(FAIL + " returning 1", (repr(e), name, k)); raise
                await q(COMMIT + " returning 1", (jsonb(res), name, k)); return res

        @functools.wraps(fn)
        def wrapper(*a, **kw):
            k, rid, h, lease = prep(a, kw)
            with _connect(conn) as c:
                for _ in range(5):
                    if c.execute(RESERVE, (rid, name, k, h, lease)).fetchone(): break
                    d = _decide(name, k, h, c.execute(READ, (name, k)).fetchone())
                    if d and d[0] == "hit": return d[1]
                    if d and c.execute(RECLAIM, (rid, lease, name, k)).fetchone(): warn(k, d[1]); break
                else: raise EffectInFlight(f"{name}: key {k!r} is contended")
                try: res = call(a, kw, k)
                except Exception as e:  # crash/cancel (BaseException) leaves it pending -> lease
                    c.execute(FAIL, (repr(e), name, k)); raise
                c.execute(COMMIT, (jsonb(res), name, k)); return res
        return awrapper if inspect.iscoroutinefunction(fn) else wrapper
    return deco

def _ready(c):
    if not c.autocommit:
        if c.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
            raise ValueError("side_effect_ledger needs a connection outside a transaction (use autocommit=True)")
        c.autocommit = True  # the reservation must be committed before the effect runs
    return c

class _connect:
    """Shared connection object: used as-is. Callable: called per use; a connection is closed after, a context
    manager (pool.connection) is entered and exited."""
    def __init__(self, conn): self.conn, self.cm, self.own = conn, None, False
    def __enter__(self):
        if isinstance(self.conn, psycopg.Connection): return _ready(self.conn)
        r = self.conn()
        if isinstance(r, psycopg.Connection): self.cm, self.own = r, True; return _ready(r)
        self.cm = r; return _ready(r.__enter__())
    def __exit__(self, *e):
        if self.own: self.cm.close()
        elif self.cm is not None: self.cm.__exit__(*e)

class _aconnect:
    def __init__(self, conn): self.conn, self.cm, self.own, self.c = conn, None, False, None
    async def __aenter__(self):
        if isinstance(self.conn, (psycopg.Connection, psycopg.AsyncConnection)): self.c = self.conn
        else:
            r = self.conn()
            if inspect.isawaitable(r): r = await r
            if isinstance(r, (psycopg.Connection, psycopg.AsyncConnection)): self.c, self.own = r, True
            else: self.cm = r; self.c = await r.__aenter__() if hasattr(r, "__aenter__") else r.__enter__()
        if isinstance(self.c, psycopg.AsyncConnection) and not self.c.autocommit:
            if self.c.info.transaction_status != psycopg.pq.TransactionStatus.IDLE:
                raise ValueError("side_effect_ledger needs a connection outside a transaction (use autocommit=True)")
            await self.c.set_autocommit(True)
        elif isinstance(self.c, psycopg.Connection): _ready(self.c)
        return self.c
    async def __aexit__(self, *e):
        if self.own: r = self.c.close(); await r if inspect.isawaitable(r) else None
        elif self.cm is not None: await self.cm.__aexit__(*e) if hasattr(self.cm, "__aexit__") else self.cm.__exit__(*e)

```

### examples/langgraph_node.py

```python
# LangGraph: approve in one node with interrupt(), charge in the next node through the ledger.
import os, psycopg, stripe
from langgraph.types import interrupt
from ledger import side_effect_ledger

@side_effect_ledger(conn=lambda: psycopg.connect(os.environ["DATABASE_URL"]), effect="charge",
                    key=lambda amount, order_id, **_: f"{order_id}:charge")
def charge(amount, order_id, idempotency_key):
    return stripe.PaymentIntent.create(amount=amount, currency="usd", confirm=True,
                                       idempotency_key=idempotency_key).id

def approve(state): return {"approved": bool(interrupt({"q": f"Charge {state['amount']}?"}))}
def execute(state):  # runs after interrupt(); safe on resume, retry or a replayed approval
    if not state.get("approved"): return {}
    return {"charge_id": charge(state["amount"], order_id=state["order_id"])}

```

### examples/openai_agents_tool.py

```python
# OpenAI Agents SDK: the approved tool's body goes through the ledger (async path).
import os, psycopg, stripe
from agents import function_tool, RunContextWrapper
from ledger import side_effect_ledger

@side_effect_ledger(conn=lambda: psycopg.AsyncConnection.connect(os.environ["DATABASE_URL"]),
                    effect="charge", key=lambda amount, order_id, **_: f"{order_id}:charge")
async def ledger_charge(amount, order_id, idempotency_key):
    return (await stripe.PaymentIntent.create_async(amount=amount, currency="usd", confirm=True,
                                                    idempotency_key=idempotency_key)).id

@function_tool(needs_approval=True)
async def charge(ctx: RunContextWrapper[dict], amount: int) -> str:
    """Charge the customer for this order."""
    return await ledger_charge(amount, order_id=ctx.context["order_id"])

```

### ledger.ts

```
// Side-effect ledger for TypeScript (pg). Same table and semantics as ledger.py. MIT.
// Needs the side_effects table from schema.sql. https://tryagentsignal.com/templates/side-effect-ledger/
//
//   const id = await withLedger("charge", `${orderId}:charge`, (key) =>
//     stripe.paymentIntents.create({ amount, currency: "usd" }, { idempotencyKey: key }).then((p) => p.id),
//     { pool, args: { amount, orderId } });
//
// The key MUST come from stable run data (orderId, threadId, toolCallId). crypto.randomUUID() is wrong:
// every retry gets a new key, so nothing is deduped. Runs once per key; if a worker crashes mid-call, the
// effect can run again after the lease expires, so also pass the same key to the provider (e.g. Stripe
// Idempotency-Key).
//   committed -> stored result, fn not called       pending, in lease -> EffectInFlight (retry later)
//   pending, lease over -> treated as a crashed call: reclaimed atomically, fn runs again with the same key
//   failed (fn threw) -> fn runs again, same key    same key, other args -> IdempotencyKeyMismatch
import { createHash } from "node:crypto";
import type { Pool } from "pg";

export class EffectInFlight extends Error { name = "EffectInFlight"; }
export class MissingIdempotencyKey extends Error { name = "MissingIdempotencyKey"; }
export class IdempotencyKeyMismatch extends Error { name = "IdempotencyKeyMismatch"; }
export type LedgerOptions = {
  pool: Pool;                 // required: no implicit globals
  args?: unknown;             // the effect's arguments; hashed into args_hash (canonical JSON, sorted keys)
  leaseSeconds?: number;      // default 300; env AGENTSIGNAL_LEDGER_LEASE_S overrides
  runId?: string;             // stored for debugging; defaults to the key
  log?: (msg: string) => void;
};

const RESERVE = `insert into side_effects (run_id, effect, idempotency_key, args_hash, status, lease_until)
  values ($1, $2, $3, $4, 'pending', now() + make_interval(secs => $5)) on conflict do nothing returning status`;
const READ = `select status, result, args_hash, lease_until > now() as in_lease from side_effects
  where effect = $1 and idempotency_key = $2`;
const RECLAIM = `update side_effects set status = 'pending', run_id = $1, error = null,
  lease_until = now() + make_interval(secs => $2) where effect = $3 and idempotency_key = $4
  and (status = 'failed' or (status = 'pending' and lease_until < now())) returning status`;
const COMMIT = `update side_effects set status = 'committed', result = $3, committed_at = now(), lease_until = null
  where effect = $1 and idempotency_key = $2`;
const FAIL = `update side_effects set status = 'failed', error = $3, lease_until = null
  where effect = $1 and idempotency_key = $2`;

const canon = (v: unknown): string => Array.isArray(v) ? `[${v.map(canon).join(",")}]`
  : v && typeof v === "object" ? `{${Object.keys(v).sort().filter((k) => (v as any)[k] !== undefined)
      .map((k) => `${JSON.stringify(k)}:${canon((v as any)[k])}`).join(",")}}`
  : JSON.stringify(v ?? null);

export async function withLedger<T>(effect: string, key: string | null | undefined,
                                    fn: (idempotencyKey: string) => Promise<T>, opts: LedgerOptions): Promise<T> {
  if (!opts?.pool) throw new TypeError("withLedger needs opts.pool");
  if (!effect || key == null || String(key).trim() === "")
    throw new MissingIdempotencyKey(`${effect}: key is ${JSON.stringify(key)}; derive it from stable run data`);
  const db = opts.pool, k = String(key), runId = opts.runId ?? k;
  const lease = Number(process.env.AGENTSIGNAL_LEDGER_LEASE_S ?? opts.leaseSeconds ?? 300);
  const hash = createHash("sha256").update(canon(opts.args ?? {})).digest("hex");
  let owned = false;
  for (let i = 0; i < 5 && !owned; i++) {
    if ((await db.query(RESERVE, [runId, effect, k, hash, lease])).rowCount) { owned = true; break; }
    const row = (await db.query(READ, [effect, k])).rows[0];
    if (!row) continue;                                          // deleted meanwhile: reserve again
    if (row.args_hash !== hash) throw new IdempotencyKeyMismatch(`${effect}: key '${k}' was already used with different arguments`);
    if (row.status === "committed") return row.result as T;      // stored result, fn not called
    if (row.status === "pending" && row.in_lease) throw new EffectInFlight(`${effect}: key '${k}' is pending (lease not expired)`);
    if ((await db.query(RECLAIM, [runId, lease, effect, k])).rowCount) {
      owned = true; (opts.log ?? console.warn)(`re-running ${effect} key '${k}' (${row.status}); same key passed again`);
    }
  }
  if (!owned) throw new EffectInFlight(`${effect}: key '${k}' is contended`);
  let res: T;
  try { res = await fn(k); }
  catch (e) { await db.query(FAIL, [effect, k, String(e)]); throw e; }
  await db.query(COMMIT, [effect, k, JSON.stringify(res === undefined ? null : res)]);
  return res;
}

```

### requirements.txt

```
psycopg[binary]==3.3.6

```

### LAST_TESTED.md

```
# Last tested
- When: 2026-10-18T17:17Z to 17:23Z (UTC) = 2026-10-18 11:17–11:23 MT (full suite run 3 times in a row)
- Database: tested on PostgreSQL 17 (17.11), a throwaway local cluster (`scripts/pg_tmp.sh start`, temp dir, deleted after). No hosted or production database.
- Python: 3.13.5, psycopg 3.3.6, psycopg-pool 3.3.0, pytest 9.1.1. `pytest -q tests/`: **38 passed, 1 xfailed or xpassed** on each of 3 runs (the naive LangGraph kill_resume control is `xfail(strict=False)` until the checker fix, so it can flap between xfailed and xpassed from run to run; it is not asserted).
- Crash test: agentsignal-check 0.3.2 (ee1b8e3), langgraph 1.2.16 (+ checkpoint 4.3.0, checkpoint-sqlite 3.1.2), openai-agents 0.24.0, offline scripted model, no API keys.
- TypeScript: Node 20.19.2, pg 8.23.1, vitest 5.0.5, typescript 7.0.2. `npm test`: **9 passed**; `tsc`: clean.

## What the tests prove
- Same key twice: the effect runs once; the second call returns the stored result (also from a new process).
- Different keys both run; the same key under two effect names are independent.
- Same key with different arguments: `IdempotencyKeyMismatch`, effect not called (Python and TS).
- Missing key (`None`, `""`, no `key=`) or no `conn=`: raises before anything runs.
- `uuid4()` keys don't dedupe (documents why they're wrong).
- The README `## Python` block runs as written; its key lambda works with positional, keyword and mixed calls.
- The README fixtures table lists both `--effect` targets for the fixed LangGraph fixture (provider call + decorated function).
- The mock provider (`tests/fixtures/provider.py`) writes atomically (temp file in the same directory, flush + fsync,
  `os.replace`): an interrupt mid-write leaves the file intact with no temp file; a hard kill never truncates the file but may leave a stray `*.tmp`.
- Crash after the effect, before the commit (process hard-killed, `os._exit`): the row stays `pending`;
  inside the lease every call raises `EffectInFlight` and the effect is not called; once the lease expires
  (forced, and in real time with `lease_seconds=1`/`2`) the row is reclaimed atomically and the effect runs
  again with the **same** key, which the mock provider dedupes, so one charge in total.
- A cancelled or interrupted call (`KeyboardInterrupt`, `asyncio.CancelledError`) leaves the row `pending`.
- Effect raises: row `failed` with `error`, exception re-raised; the next call with the same key re-runs it.
- Concurrency: 8 threads and `asyncio.gather` of 8 on one key give exactly one effect call, the rest
  `EffectInFlight`, then all get the stored result; 6 workers racing to reclaim one expired lease give one
  re-run. TS: 8 concurrent `withLedger` calls give one call.
- `AGENTSIGNAL_LEDGER_LEASE_S` overrides `lease_seconds`; `schema.sql` applied twice without error.
- Connections: callable (sync/async), `ConnectionPool.connection`, a shared autocommit connection; a
  connection inside an open transaction is refused.

## Crash test (agentsignal check) on the fixtures
| fixture | effect watched | lease | result |
|---|---|---|---|
| `tests.fixtures.lg_fixed:build` | `tests.fixtures.provider:charge` | expired (`AGENTSIGNAL_LEDGER_LEASE_S=0`) | 5/5 PASS |
| `tests.fixtures.lg_fixed:build` | `tests.fixtures.billing:charge` only | 300 s | 5/5 PASS (trivial: the crash lands after the commit, so this never tests a mid-call crash) |
| `tests.fixtures.lg_fixed:build` | `tests.fixtures.provider:charge` + `tests.fixtures.billing:charge` | expired | 5/5 PASS |
| `tests.fixtures.lg_fixed:build` | `tests.fixtures.provider:charge` | 300 s | kill_resume WARN or PASS (0.3.2 usually WARN: the ledger refused inside the lease), never a duplicate, exactly 1 provider charge per crash point; others PASS |
| `tests.fixtures.oai_fixed:build` | `tests.fixtures.provider:charge` | 0 and 300 s | 4/4 PASS |
| `tests.fixtures.lg_naive:build`, `tests.fixtures.oai_naive:build` (controls) | `tests.fixtures.provider:charge` | n/a | kill_resume + replay FAIL, as expected |

agentsignal-check 0.3.2 usually reports the in-lease refusal as WARN; watching an async decorated function under OpenAI Agents gives a false duplicate on 0.3.2 (checker bug, fixed in 0.4.0), so the OAI rows watch the provider call; 0.4.0 or later reports it as PASS with an "in flight" note (spec decision G7).

```
