Skip to content

PostgreSQL Stripe host ledger

The optional PostgreSQL ledger supplies durable intent binding and resource reservation bookkeeping for adopter-owned Stripe repositories. It does not own payments, subscriptions or invoices. The host retains those canonical rows and their business transactions.

From a checkout, install the locked database dependencies and inspect the migration before applying it:

uv sync --extra dev --extra postgres --locked
uv run python - <<'PY'
from threvo_actions.integrations.stripe import render_stripe_postgres_migration
print(render_stripe_postgres_migration())
PY

Apply migrations explicitly from a deployment step:

from threvo_actions.integrations.stripe import migrate_stripe_postgres

await migrate_stripe_postgres(owner_pool, schema="threvo_stripe")

PostgresStripeLedger constructors perform no I/O and never migrate. The migration has an immutable checksum record and is included in the wheel.

Transaction seam

The ledger's reserve_in, record_no_submission_in and record_outcome_in methods require an already active caller-owned transaction. A concrete host repository must lock and validate its canonical resource first, call the ledger inside that same transaction, and return ACQUIRED only after the outer commit has succeeded.

async with pool.acquire() as connection, connection.transaction():
    payment = await load_payment_for_update(connection, tenant, payment_reference)
    assert_payment_matches_snapshot(payment, snapshot)
    result = await ledger.reserve_in(
        connection,
        tenant_reference=tenant,
        action_group=StripeHostActionGroup.REFUNDS,
        effect_reference=snapshot.effect_reference,
        resource_reference=f"customer:{customer_reference}",
        snapshot_data=model_json_object(snapshot),
        not_after=deadline,
    )
# Only here has an ACQUIRED result committed.
return RefundReservationStatus(result.value)

The ledger takes a transaction-scoped advisory lock for tenant + resource before checking unresolved intents. This serializes different Stripe action groups that use the same resource reference. It does not block an application's ordinary writer by itself. Every mutation path for that canonical resource must take the same row lock or enforce an equivalent database guard. When sharing the advisory lock directly, derive its text input with stripe_resource_lock_reference(tenant_reference, resource_reference) and pass that value to hashtextextended; this avoids delimiter ambiguity and PostgreSQL text-encoding errors. The reference schema includes a shared customer-resource row and triggers that reject payment, subscription, or invoice updates and deletes while that customer has an unresolved Stripe reservation.

An exception after commit is an uncertain acknowledgement. Preserve the row and reconcile; never convert the exception into UNAVAILABLE or retry the provider mutation.

Expected persistence dispositions are values, while an exception means the ledger could not establish a trustworthy disposition:

  • remember returns CREATED, MATCHED, or CONFLICT;
  • load and load_in return an entry or None for known absence;
  • reserve_in returns the shared StripeHostReserveStatus vocabulary; StripeLedgerReservationStatus remains an alias for compatibility; and
  • terminal writes return RECORDED, MATCHED, or CONFLICT.

Do not catch StripePostgresHostError and infer one of these values from its message. Reference repositories translate a known typed conflict into their own operation failure and let uncertain persistence errors propagate. Exact repeated terminal writes are idempotent. Rows are retained after closure so a spent intent cannot reopen.

Reference implementation

examples/stripe_host contains:

  • concrete refund, subscription-cancellation, and credit-note repositories;
  • canonical ReferencePayment, ReferenceSubscription, and ReferenceInvoice rows mapped to one guarded customer resource;
  • composition boundaries for all three maintained host protocols; and
  • proposal-bound reference envelope encryption for evaluation.

The repository uses byte-oriented JSON reads so behavior does not depend on an asyncpg JSON codec. It accepts configurable validated schema names for isolated tests. The default SQL file assumes stripe_host_app and threvo_stripe.

The protection example keeps its wrapping key in process memory and stores wrapped data keys in PostgreSQL. It demonstrates proposal binding and erasure; production key custody should use a separately authorized managed key service.

Run the local checks with:

uv run pytest -q tests/unit/test_stripe_postgres.py \
  tests/integration/stripe/test_postgres_host.py

Set THREVO_ACTIONS_TEST_POSTGRES_DSN to exercise PostgreSQL. Without it the database case is reported as skipped, not passed. Run the separate Stripe host exercise against the adopter's schema and normal writer before using the repository pattern for live effects.

The approval request store and its checksummed migration are installed under threvo_actions.integrations.approval_channels. It remains separate from the Stripe ledger and must be applied explicitly. Recovery-case tables remain application-owned. Preserve decision and observation records according to the host retention policy.