Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .agents/agents/ledger-reviewer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
name: ledger-reviewer
description: Read-only review of a ledger-service diff for money-safety: atomicity, idempotency, append-only entries, locking, and invariants. Use after changing ledger/models.py, ledger/services/, migrations, or any write endpoint.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You review; you never edit. Read the diff (`git diff`) and the touched files, then check:

1. **Balanced and atomic** — every transfer writes balanced entries inside one transaction; no partial write on any error path.
2. **Append-only** — no update or delete of entries; corrections are reversing entries.
3. **Idempotent** — a retried request with the same key returns the first result and writes nothing new.
4. **Concurrency** — balance checks and account updates hold row locks in a consistent order; no check-then-act race.
5. **Money type** — amounts are integers/Decimal via `ledger/money.py`; no float anywhere near money.
6. **Database backs it up** — invariants are enforced by constraints or triggers, and a migration is present for any schema change.

Report findings as `file:line — problem — why money could be lost or duplicated`, most severe first. Nothing found: say "No money-safety issues", and name what you checked.
16 changes: 16 additions & 0 deletions .agents/agents/verifier.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
name: verifier
description: Runs ledger-service's quality gates and reports only what fails. Use after any code change, before opening a PR, or when asked if the build is green.
tools: Bash, Read
model: haiku
---

You run the quality gates and report. You never edit source files.

The gates, in order (keep going after a failure):
1. `make lint`
2. `make typecheck`
3. `make test` — needs PostgreSQL; if it is not reachable, say so and skip it instead of failing.

Source of truth: `Makefile` and `.github/workflows/ci.yml`.
Report one line of gates (✓/✗ each), then each failure once with file and shortest message. No stack traces, no passing output. All green: "All gates pass" with test counts.
1 change: 1 addition & 0 deletions .claude/agents
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ LEDGER_SNAPSHOT_EVERY=500
# a Redis stream (install the `redis` extra).
LEDGER_OUTBOX_PUBLISHER=log
LEDGER_OUTBOX_STREAM=ledger.events
# For LEDGER_OUTBOX_PUBLISHER=webhook:
LEDGER_WEBHOOK_URL=
LEDGER_WEBHOOK_SECRET=
REDIS_URL=redis://localhost:6379/0

LOG_LEVEL=INFO
5 changes: 0 additions & 5 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ name: CI
on:
pull_request:
branches: [main]
push:
branches: [main]
schedule:
# Weekly, so a newly published advisory fails a build nobody pushed.
- cron: "17 4 * * 1"

concurrency:
group: ci-${{ github.ref }}
Expand Down
21 changes: 21 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# AGENTS.md — ledger-service

Canonical instructions for any AI agent or human working in this repo.
`CLAUDE.md` is a pointer only; new rules go **here**.

A double-entry ledger over HTTP (Django 6.1, Django Ninja, PostgreSQL 16, Redis as an optional event sink).
It moves money atomically, idempotently and append-only. Read `README.md`, `CONTRIBUTING.md` and `docs/adr/` first.

## Commands (`make help` lists all)

- `make check` — lint, mypy strict, tests: exactly what CI runs. Tests need PostgreSQL (triggers, row locks, `SKIP LOCKED`); there is no SQLite fallback.
- `make reconcile` — checks every ledger invariant against the database.
- `make requirements` — re-export the hash-pinned `requirements.txt` after any `uv.lock` change; CI and Docker install from it.

## Rules

- Money is never created or lost: every transfer is balanced entries inside one transaction. Amounts go through `ledger/money.py`, never floats.
- Entries are append-only. Corrections are new reversing entries, never updates or deletes.
- Every write endpoint is idempotent by key; a retry must return the first result.
- Schema changes ship as a migration; invariants that matter live in the database (triggers, constraints), not only in Python.
- CI workflows are reusable ones from `CtrlAltDevelop/ci-workflows`; change checks there, not here.
1 change: 1 addition & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
See [AGENTS.md](./AGENTS.md).
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1
FROM python:3.14-slim AS runtime
FROM python:3.15-slim AS runtime

# WEB_CONCURRENCY is gunicorn's worker count.
ENV PYTHONDONTWRITEBYTECODE=1 \
Expand Down
683 changes: 662 additions & 21 deletions LICENSE

Large diffs are not rendered by default.

12 changes: 9 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
![Python](https://img.shields.io/badge/python-3.12%2B-blue)
![Django](https://img.shields.io/badge/django-6.1-green)
![PostgreSQL](https://img.shields.io/badge/postgresql-16-336791)
[![License: MIT](https://img.shields.io/badge/license-MIT-yellow)](LICENSE)
![Redis](https://img.shields.io/badge/redis-7%20(optional)-DC382D)
![Docker](https://img.shields.io/badge/docker-compose-2496ED)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](LICENSE)
[![last commit](https://img.shields.io/github/last-commit/CtrlAltDevelop/ledger-service)](https://github.com/CtrlAltDevelop/ledger-service/commits/main)

A double-entry ledger over HTTP. It moves money between accounts
**atomically**, **idempotently** and **append-only**, so money is never
Expand Down Expand Up @@ -107,9 +110,11 @@ UUID is ideal). OpenAPI docs are served at `/docs`.
| `POST` | `/v1/withdrawals` | Money out to outside |
| `POST` | `/v1/transfers` | `from` → `to`, same currency and same side of the ledger |
| `POST` | `/v1/transactions` | Any balanced set of 2–50 signed entries, e.g. a trade with a fee leg |
| `GET` | `/v1/transactions` | Transactions, newest first, paged with `?cursor=&limit=`; filter by `account_id`, `kind`, `created_from`, `created_to` |
| `GET` | `/v1/transactions/{id}` | A transaction and its entries |
| `POST` | `/v1/transactions/{id}/reverse` | Post the exact negation, linked to the original |
| `POST` | `/v1/holds` | Reserve funds: `account_id`, `amount`, `currency`, optional `expires_at` |
| `GET` | `/v1/holds` | Holds, newest first, paged; filter by `account_id` and `status` (overdue holds count as `expired`) |
| `GET` | `/v1/holds/{id}` | Read a hold: `active`, `captured`, `released` or `expired` |
| `POST` | `/v1/holds/{id}/capture` | Move up to the held amount to `to`; any remainder is released |
| `POST` | `/v1/holds/{id}/release` | Let the funds go |
Expand Down Expand Up @@ -199,7 +204,8 @@ make check # ruff, mypy --strict, pytest

| Command | When |
|---|---|
| `manage.py outbox_worker [--once]` | Always running. Handles SIGTERM by finishing the batch in hand. |
| `manage.py outbox_worker [--once]` | Always running. `LEDGER_OUTBOX_PUBLISHER` is `log`, `redis` or `webhook` (POSTs each event to `LEDGER_WEBHOOK_URL`, HMAC-SHA256 in `X-Ledger-Signature`, keyed by `LEDGER_WEBHOOK_SECRET`). Handles SIGTERM by finishing the batch in hand. |
| `manage.py expire_holds` | Optional, from cron. Marks overdue holds `expired` and emits `hold.expired`; balances are already correct without it. |
| `manage.py reconcile [--json]` | On a schedule, e.g. nightly. Exits 1 on any discrepancy, so alert on the exit code. |
| `manage.py snapshot_balances [--min-entries N]` | Optional, off-peak. Busy accounts are snapshotted inline every `LEDGER_SNAPSHOT_EVERY` entries. |
| `manage.py create_api_client NAME` | Prints a new client's token once; only its SHA-256 is stored. |
Expand Down Expand Up @@ -273,4 +279,4 @@ Changes are listed in [CHANGELOG.md](CHANGELOG.md).

## License

[MIT](LICENSE) © 2026 Mohammad Zarif
[AGPL-3.0-only](LICENSE) © 2026 Mohammad Zarif
4 changes: 3 additions & 1 deletion config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ def _env_bool(name: str, *, default: bool = False) -> bool:
# one, so a balance read never sums more than this many rows.
LEDGER_SNAPSHOT_EVERY = int(os.environ.get("LEDGER_SNAPSHOT_EVERY", "500"))

# Where the outbox worker sends events: "log" or "redis" (a Redis stream).
# Where the outbox worker sends events: "log", "redis" (a Redis stream) or "webhook".
LEDGER_OUTBOX_PUBLISHER = os.environ.get("LEDGER_OUTBOX_PUBLISHER", "log")
LEDGER_OUTBOX_STREAM = os.environ.get("LEDGER_OUTBOX_STREAM", "ledger.events")
LEDGER_WEBHOOK_URL = os.environ.get("LEDGER_WEBHOOK_URL", "")
LEDGER_WEBHOOK_SECRET = os.environ.get("LEDGER_WEBHOOK_SECRET", "")
REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
55 changes: 50 additions & 5 deletions ledger/api/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,66 @@
import base64
import binascii
import json
from datetime import datetime
from typing import Any, TypeVar
from uuid import UUID

from django.db.models import Model, Q, QuerySet

from ledger import errors

M = TypeVar("M", bound=Model)


def encode(last_id: int) -> str:
raw = json.dumps({"before": last_id}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
return _pack(last_id)


def decode(cursor: str) -> int:
before = _unpack(cursor)
if not isinstance(before, int) or isinstance(before, bool) or before < 1:
raise errors.InvalidCursor("cursor is malformed")
return before


def _pack(value: Any) -> str:
raw = json.dumps({"before": value}, separators=(",", ":")).encode()
return base64.urlsafe_b64encode(raw).decode().rstrip("=")


def _unpack(cursor: str) -> Any:
try:
padded = cursor + "=" * (-len(cursor) % 4)
before = json.loads(base64.urlsafe_b64decode(padded))["before"]
return json.loads(base64.urlsafe_b64decode(padded))["before"]
except (binascii.Error, ValueError, KeyError, TypeError):
raise errors.InvalidCursor("cursor is malformed") from None
if not isinstance(before, int) or isinstance(before, bool) or before < 1:


def page_newest_first(
rows: "QuerySet[M]", cursor: str | None, limit: int
) -> tuple[list[M], str | None]:
"""One page of ``rows`` ordered by (created_at, id) descending, plus the next cursor.

For tables keyed by UUID, where the id alone says nothing about order.
``rows`` must have ``created_at`` and ``id`` fields.
"""
rows = rows.order_by("-created_at", "-id")
if cursor:
stamp, last_id = _decode_stamp(cursor)
rows = rows.filter(Q(created_at__lt=stamp) | Q(created_at=stamp, id__lt=last_id))
page = list(rows[: limit + 1])
has_more = len(page) > limit
page = page[:limit]
next_cursor = _pack([page[-1].created_at.isoformat(), str(page[-1].id)]) if has_more else None # type: ignore[attr-defined]
return page, next_cursor


def _decode_stamp(cursor: str) -> tuple[datetime, UUID]:
value = _unpack(cursor)
try:
stamp, last_id = datetime.fromisoformat(value[0]), UUID(value[1])
except (ValueError, TypeError, IndexError, KeyError, AttributeError):
raise errors.InvalidCursor("cursor is malformed") from None
if stamp.tzinfo is None:
raise errors.InvalidCursor("cursor is malformed")
return before
return stamp, last_id
4 changes: 2 additions & 2 deletions ledger/api/presenters.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def entries(items: Iterable[Entry], scales: dict[str, int]) -> list[dict[str, An
]


def transaction(txn: Transaction) -> dict[str, Any]:
def transaction(txn: Transaction, scales: dict[str, int] | None = None) -> dict[str, Any]:
reversed_by = Transaction.objects.filter(reverses=txn).values_list("id", flat=True).first()
return {
"id": txn.id,
Expand All @@ -74,7 +74,7 @@ def transaction(txn: Transaction) -> dict[str, Any]:
"reverses": txn.reverses_id,
"reversed_by": reversed_by,
"created_at": txn.created_at,
"entries": entries(txn.entries.order_by("id"), currency_scales()),
"entries": entries(txn.entries.order_by("id"), scales or currency_scales()),
}


Expand Down
24 changes: 21 additions & 3 deletions ledger/api/routes/holds.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
from uuid import UUID

from django.http import HttpRequest
from ninja import Router, Status
from ninja import Field, Query, Router, Schema, Status

from ledger.api import presenters
from ledger.api import pagination, presenters
from ledger.api.auth import client_of
from ledger.api.idempotency import OPENAPI_EXTRA, idempotent
from ledger.api.schemas import CaptureIn, HoldIn, HoldOut
from ledger.api.schemas import CaptureIn, HoldIn, HoldOut, HoldPage
from ledger.models import HoldStatus
from ledger.services import holds

router = Router(tags=["holds"])
Expand All @@ -28,6 +29,23 @@ def create_hold(request: HttpRequest, payload: HoldIn) -> Status[dict[str, Any]]
return Status(201, presenters.hold(hold))


class HoldQuery(Schema):
account_id: UUID | None = None
status: HoldStatus | None = Field(
None, description="Effective status: overdue holds are expired."
)
cursor: str | None = None
limit: int = Field(50, ge=1, le=200)


@router.get("/holds", response=HoldPage)
def list_holds(request: HttpRequest, query: Query[HoldQuery]) -> dict[str, Any]:
"""Holds newest first, paged by an opaque cursor."""
rows = holds.list_holds(client_of(request), account_id=query.account_id, status=query.status)
page, next_cursor = pagination.page_newest_first(rows, query.cursor, query.limit)
return {"items": [presenters.hold(h) for h in page], "next_cursor": next_cursor}


@router.get("/holds/{hold_id}", response=HoldOut)
def get_hold(request: HttpRequest, hold_id: UUID) -> dict[str, Any]:
return presenters.hold(holds.get_hold(client_of(request), hold_id))
Expand Down
42 changes: 38 additions & 4 deletions ledger/api/routes/transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,24 @@
from uuid import UUID

from django.http import HttpRequest
from ninja import Router, Status
from ninja import Field, Query, Router, Schema, Status
from pydantic import AwareDatetime

from ledger import errors
from ledger.api import presenters
from ledger.api import pagination, presenters
from ledger.api.auth import client_of
from ledger.api.idempotency import OPENAPI_EXTRA, idempotent
from ledger.api.schemas import (
DepositIn,
JournalIn,
ReverseIn,
TransactionOut,
TransactionPage,
TransferIn,
WithdrawalIn,
)
from ledger.models import Transaction
from ledger.services import payments, reversals
from ledger.models import Entry, Transaction, TransactionKind
from ledger.services import accounts, payments, reversals
from ledger.services.posting import Leg

router = Router(tags=["transactions"])
Expand Down Expand Up @@ -82,6 +84,38 @@ def journal(request: HttpRequest, payload: JournalIn) -> Created:
return Status(201, presenters.transaction(txn))


class TransactionQuery(Schema):
account_id: UUID | None = Field(
None, description="Only transactions with a leg on this account."
)
kind: TransactionKind | None = None
created_from: AwareDatetime | None = Field(None, description="Inclusive.")
created_to: AwareDatetime | None = Field(None, description="Exclusive.")
cursor: str | None = None
limit: int = Field(50, ge=1, le=100)


@router.get("/transactions", response=TransactionPage)
def list_transactions(request: HttpRequest, query: Query[TransactionQuery]) -> dict[str, Any]:
"""Transactions newest first, paged by an opaque cursor."""
client = client_of(request)
rows = Transaction.objects.filter(client=client)
if query.account_id is not None:
account = accounts.get_account(client, query.account_id)
legs = Entry.objects.filter(account=account).values("transaction_id")
rows = rows.filter(id__in=legs)
if query.kind is not None:
rows = rows.filter(kind=query.kind)
if query.created_from is not None:
rows = rows.filter(created_at__gte=query.created_from)
if query.created_to is not None:
rows = rows.filter(created_at__lt=query.created_to)
page, next_cursor = pagination.page_newest_first(rows, query.cursor, query.limit)
# ponytail: two queries per item (entries, reversed_by); batch them if lists get hot.
scales = presenters.currency_scales()
return {"items": [presenters.transaction(t, scales) for t in page], "next_cursor": next_cursor}


@router.get("/transactions/{transaction_id}", response=TransactionOut)
def get_transaction(request: HttpRequest, transaction_id: UUID) -> dict[str, Any]:
try:
Expand Down
10 changes: 10 additions & 0 deletions ledger/api/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,11 @@ class TransactionOut(Schema):
entries: list[EntryOut]


class TransactionPage(Schema):
items: list[TransactionOut]
next_cursor: str | None = Field(description="Pass as ?cursor= for the next page.")


class EntryPage(Schema):
items: list[EntryOut]
next_cursor: str | None = Field(description="Pass as ?cursor= for the next page.")
Expand All @@ -147,6 +152,11 @@ class CaptureIn(Schema):
description: Description


class HoldPage(Schema):
items: list["HoldOut"]
next_cursor: str | None = Field(description="Pass as ?cursor= for the next page.")


class HoldOut(Schema):
id: UUID
account_id: UUID
Expand Down
19 changes: 19 additions & 0 deletions ledger/management/commands/expire_holds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Any

from django.core.management.base import BaseCommand, CommandParser

from ledger.services import holds


class Command(BaseCommand):
help = "Mark overdue holds expired and announce them. Safe to run from cron."

def add_arguments(self, parser: CommandParser) -> None:
parser.add_argument("--batch-size", type=int, default=100)

def handle(self, *args: Any, **options: Any) -> None:
batch_size: int = options["batch_size"]
total = 0
while (done := holds.expire_due(batch_size=batch_size)) > 0:
total += done
self.stdout.write(f"expired {total} hold(s)")
Loading