All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.


[0.7.0] - 2026-11-20

Added & Changed

  • Subscription Quantity & Item Synchronization: Added protected nullable attributes quantity (:integer, min: 0) and provider_subscription_item_id (:string) to AshBilling.Subscription (AddSubscriptionAttributes + wildcard exclusion via ProtectBillingAttributes). WebhookSync and AshBilling.reconcile_subscription/2 now extract, persist, compare (@financial_sync_fields), and atomically CAS-guard both attributes for single-item subscriptions: legitimately absent/null quantities remain nil (never assuming 1), explicit 0 persists as 0 contracted seats, negative or malformed non-integer quantities fail closed with {:error, :invalid_quantity} without erasing valid persisted quantities, and multi-item non-terminal payloads remain rejected (:unsupported_subscription_items). See Upgrading to 0.7.
  • Diagnostics Engine & Doctor CLI (AshBilling.Diagnostics, mix ash_billing.doctor): Extended AshBilling.check_configuration/1 (preserving backwards-compatible {:ok, %{status: :valid, ...}} / {:error, reasons} contract) with layered structural, read-only PostgreSQL schema/migration/index checks (0.6.0 last_reconciled_at and 0.7.0 quantity/provider_subscription_item_id), WebhookEvent privacy verification (rejecting accidental AshJsonApi/AshGraphql exposure), multitenancy/Repo checks, HTTP timeout guidance, optional read-only provider probes, and explicit configuration_valid vs production_ready distinction. Added read-only mix ash_billing.doctor supporting PASS/WARN/FAIL text and --json output without exposing secrets.
  • Reconciliation CLI (AshBilling.Reconciler, mix ash_billing.reconcile): Added read-only-by-default (--dry-run) drift inspection and confirmed (--execute --confirm) single/bulk subscription reconciliation with fail-closed selection filter validation, stable keyset batch streaming, bounded concurrency, global cross-worker rate limiting, and strict Ash actor/policy, multitenant, and database-level Stripe Connect isolation.
  • Observability & Low-Cardinality Telemetry: Instrumented [:ash_billing, :reconcile, ...], [:ash_billing, :reverify, ...], [:ash_billing, :deduplication, :acquire | :complete | :release], [:ash_billing, :postgres, :contention], and [:ash_billing, :reconciler, :batch] with low-cardinality metadata and drift detection, plus a Telemetry.Metrics dashboard guide in Diagnostics, Recovery CLI & Observability.

  • Runnable SaaS Reference Application (examples/saas_example): Converted examples/saas_example into a runnable Phoenix + Ash + AshPostgres application with PostgreSQL 16 Docker Compose, migrations (0.6.0 + 0.7.0), idempotent demo seeds, PBKDF2 authentication + fresh actor reload, server-controlled plan catalog, Stripe Checkout/Portal/plan swap/quantity update/cancel/resume/reconciliation, transactional FOR UPDATE seat enforcement, AshBilling.Checks.Subscribed and AshBilling.Checks.HasPrice policies, HMAC-verified webhooks with PostgreSQL deduplication, working mix ash_billing.doctor / mix ash_billing.reconcile integrations, and an automated CI test suite.

[0.6.0] - 2026-11-19

Added & Changed

  • Durable Reconciliation Checkpoints (last_reconciled_at): Added nullable protected attribute last_reconciled_at (:utc_datetime_usec) to AshBilling.Subscription. See Upgrading to 0.6 for the required database migration.
  • PostgreSQL Shared-Clock Checkpointing: AshBilling.reconcile_subscription/2 queries PostgreSQL clock_timestamp() under canonical Customer -> Subscription FOR UPDATE locks, omits fabricated local timestamps ("created" => nil), and persists last_reconciled_at monotonically and atomically in the same transaction as reconciled state.
  • Post-Reconciliation Financial Verification: When last_reconciled_at is present, AshBilling.WebhookSync evaluates critical synchronized financial attributes (status, price_id, current_period_end, trial_ends_at, cancel_at_period_end, cancel_at) before applying non-terminal or delayed terminal webhooks. Safe fast paths (duplicates, event.created < last_event_created_at, or identical snapshots with no financial diff) skip provider calls, while any financial difference triggers live provider re-verification under FOR UPDATE regardless of event.created age, failing closed on provider or PostgreSQL errors with no ETS state.
  • 0.5.x Upgrade Cursor Healing & Operational Guidance: AshBilling.reconcile_subscription/2 now automatically clears ahead/future last_event_created_at values (> PostgreSQL clock_timestamp()) to nil atomically alongside persisting last_reconciled_at (and supports reset_event_cursor?: true for shared app+DB forward clock skew), preventing synthetic 0.5.x reconciliation timestamps from causing existing_event_newer?/2 to ignore legitimate Stripe webhooks. Documented explicit quantity persistence scope and HTTP timeout / FOR UPDATE lock hold / PostgreSQL pool sizing recommendations in Upgrading to 0.6.

[0.5.3] - 2026-11-15

Fixed & Hardened

  • Reconciliation Concurrency & Lock Error Propagation: AshBilling.reconcile_subscription/2 now enters a transaction lock boundary and acquires canonical Customer -> Subscription FOR UPDATE row locks before calling AshBilling.get_subscription/2. Lookup and lock-acquisition failures propagate cleanly without invoking the provider, preventing concurrent webhook updates from racing against in-flight stale snapshots while preserving v0.5.2 synthetic timestamp semantics ("created" => System.system_time(:second)) with no breaking API or schema changes.
  • Billing Invariants Documentation: Added the Billing invariants section to documentation/topics/webhooks-and-resilience.md matching verified implementation behavior (:active, :trialing, and :past_due access rules, ash_cust_ idempotency key prefix, lock order, and 0.5.x synthetic timestamp boundaries).
  • Canary CI: Added PostgreSQL 16 service and readiness verification to .github/workflows/canary.yml, removed continue-on-error: true so compatibility regressions fail visibly, and classified INFRASTRUCTURE_FAILURE vs COMPATIBILITY_FAILURE outcomes.

[0.5.2] - 2026-11-06

Security & Reliability Hardening

  • Subscription Quantity Updates (AB-01, AB-02): Added optional update_quantity/3 callback to AshBilling.Provider behaviour and implemented it in AshBilling.Providers.Stripe. Quantity updates now POST only items[0][id] and items[0][quantity], omitting items[0][price]. This prevents unintended plan switches, avoids race conditions where a concurrent plan change would be clobbered by a quantity update, and avoids unnecessary GET requests when subscription_item_id is supplied without price_id. An optional :price_id can be passed as an optimistic assertion against the active plan, returning {:error, {:price_mismatch, actual}} if stale. Emits [:ash_billing, :update_quantity] telemetry span.
  • URL Path Sanitization & Traversal Prevention (AB-03): Added percent-encoding via URI.encode(..., &URI.char_unreserved?/1) for all dynamic subscription_id path segments in AshBilling.Providers.Stripe (get_subscription, cancel_subscription, resume_subscription, swap_plan, update_quantity). Validates subscription IDs early and returns {:error, :invalid_subscription_id} on blank, whitespace-only, or non-binary input without making remote requests.
  • Webhook Error Normalization (AB-04): Normalized verification error handling in AshBilling.Plug. Signed non-JSON payloads now return a clean 400 response with {"error": "invalid_payload"} instead of raising Protocol.UndefinedError on Jason.DecodeError.
  • Pre-Authentication Information Disclosure Prevention (AB-05): Redacted internal repository module names from the 503 response body when the pre-authentication transaction boundary fails in AshBilling.Plug. Details are logged via Logger.error/1 while external callers receive a sanitized {"error": "transaction_boundary", "message": "Service temporarily unavailable"}.
  • Public API Contract Robustness (AB-06): Added fallback clause to AshBilling.create_customer/2 returning {:error, :invalid_customer} for non-map / non-struct inputs (nil, "", numbers, lists), replacing FunctionClauseError.
  • Documentation & Telemetry Consistency (AB-07): Documented [:ash_billing, :swap_plan] and [:ash_billing, :update_quantity] telemetry spans in README.md. Updated SECURITY.md supported versions to explicitly list 0.5.x.

[0.5.1] - 2026-11-03

Security

  • Resolved Hex advisory on retired ash_sql 0.8.4 (Ecto query cache issue) by upgrading ash_sql to 0.8.7 (and nimble_options to 1.2.0). Verified with mix hex.audit (0 advisories).

Added

  • AshBilling.Checks.HasPrice: added support for specifying multiple allowed price IDs as a list (e.g. price: ["price_monthly", "price_annual"]). Authorizes when the active subscription's price_id matches any element in the list. Enforces fail-closed semantics on empty lists, blank strings, or invalid non-binary elements.

Fixed

Developer Experience & Documentation

  • mix ash_billing.install: Enhanced post-install notice with a concrete PostgreSQL-backed WebhookEvent resource example for clustered deployments.
  • Updated README.md and documentation examples to highlight HasPrice multi-price matching and new error tuple returns.

[0.5.0] - 2026-11-02

Fixed

  • Preserve the selected Stripe item's quantity on price changes; reject invalid quantities, missing item quantities, ambiguous selections and truncated collections.
  • Require a Customer ID before recurring Checkout, and exactly one subscription line item. Reject multi-item nonterminal webhook/reconciliation snapshots rather than storing their first price; allow terminal events to revoke access.
  • Reject impossible requested customer persistence before provider calls; preserve the remote customer ID in errors when a later local association fails.
  • Bind record Checkout ownership references to the record and reject a loaded customer's mismatched tenant before customer/Checkout provider calls.
  • Roll back returned synchronization and handler errors on shared-Repo PostgreSQL; record failure/release leases after rollback and retain commit-before-response.
  • Reject unexpected handler returns instead of marking the event processed.

Compatibility

  • Explicit item ID avoids GET only when a valid quantity is also supplied.
  • Recurring Checkout no longer lets Stripe create an implicit Customer: persist a Customer first and reload the resource. Payment Checkout remains independent.
  • Handlers must return :ok, {:ok, value}, or {:error, reason}.
  • Raw lease callbacks returning errors now propagate those errors and roll back PostgreSQL; raw callers remain responsible for lease release after rollback.
  • No new schema migration is required. See the 0.5 upgrade guide.

Documentation and validation

  • Update Customer setup, handler contracts, actor freshness and unsupported-snapshot guidance.
  • Add an isolated Stripe Test Mode consumer with bounded webhook/SQL/policy convergence checks and credential-free negative controls. The consumer is excluded from the Hex package.

[0.4.1] - 2026-10-31

Fixed

  • AshBilling.Checks.HasPrice now fails closed when price: is missing or invalid.
  • Invalid price configurations are rejected during Ash policy compilation.
  • Added authorization and policy-compilation regression tests.

Documentation

  • Clarified that WebhookEvent is an internal deduplication resource and must not be exposed through public APIs.
  • Documented PostgreSQL requirements for distributed webhook deduplication.
  • Updated installation and upgrade guidance for the published 0.4.x series.

Upgrade Notes

  • Applications using HasPrice without a valid price: must supply an explicit price or use AshBilling.Checks.Subscribed for any active subscription.
  • No database schema migration is introduced by this maintenance patch.

[0.4.0] - 2026-10-30

Upgrade requirements

This pre-1.0 minor release intentionally changes billing input acceptance, Stripe Connect scope, transaction boundaries and customer idempotency keys. It is not a transparent 0.3.x patch. Apply consumer schema migrations and drain old workers before switching versions. See Upgrading to 0.4.

Fixed

  • Final billing hardening (U1–U4):

    • Exclude customer identity/tombstones and subscription state/ownership from wildcard action inputs; preserve explicit trusted accepts and internal action validation/authorization.
    • Propagate canonical tenants through all deduplication operations and scope memory/database fences by tenant, including composite event primary keys.
    • Validate Stripe account and live/test scope before recording events; require a bound mode for Connect, reject unsupported context envelopes, and preserve configured account/idempotency headers over request header overrides.
    • Resolve subscription API/reconciliation providers from the resource, preserving explicit overrides and Stripe defaults for raw IDs.
    • Namespace automatic customer idempotency keys by resource, tenant and local ID. Existing explicit keys remain unchanged; review pending retries when deploying this key format change.
    • Update the development/test Bandit lock from 1.14.0 to 1.14.1; the final Hex audit reports no advisories.
    • Compatibility: review explicit billing write actions, Connect options and tenant-aware event schema before deployment. See the public upgrade and resilience guides.
  • Webhook commit acknowledgment and contention: Send successful HTTP responses only after the execution transaction commits; failed commits and lease persistence errors remain retryable even with the legacy error acknowledgment opt-out. Reject missing/empty event IDs when deduplication is enabled. Reject caller-owned HTTP transactions and different primary Repo pools before processing. Use PostgreSQL transaction-scoped try advisory locks plus FOR UPDATE NOWAIT and persistent token CAS so duplicates do not wait on an active handler while occupying pool connections. Different Repo modules may explicitly share one primary pool; separate primary pools now fail closed with HTTP 503.

  • Billing Security and Recovery (F1–F6):

    • Retain customer IDs with a persistent billing_deleted_at tombstone, revoke their subscriptions, and reject late nonterminal events.
    • Serialize PostgreSQL customer/subscription synchronization with row locks, reconcile all same-second entitlement changes, and guard direct writes against stale snapshots.
    • Atomically associate public API customer IDs without overwriting a competing identity; load required handlers and reject invalid handler configuration.
    • Replace orphanable reclaim locks with monitored local serialization where needed, and fence Plug execution through database row locks or single-node OTP locks.
    • Migration required: generate and apply a migration adding billing_deleted_at to customer resources before deploying. Deleted customer IDs are now retained rather than cleared. Handler work runs inside the event-resource transaction; external effects remain at-least-once and require idempotency.
  • Customer Persistence Authorization: Forward the supplied actor and tenant when persisting provider customer IDs through Ash.

  • Checkout Subscription Options: Preserve subscription_data, including trial settings and subscription metadata, when checkout metadata is empty.

  • Subscription Item Quantities: Respect the requested subscription_item_id when resolving its price for quantity updates, and return an error if the item is missing instead of updating another item.

[v0.3.1] - 2026-10-28

Fixed

[v0.3.0] - 2026-10-27

Major integrity, security, and developer experience release delivering database-level uniqueness, atomic terminal guards, customer identity validation, Igniter installer fixes, and credential redaction.

Added

  • Tenant-Scoped Database Uniqueness (AshBilling.Subscription):
    • Enforced unique identity on provider_subscription_id scoped by resource and tenant (tenant_id), backed by a PostgreSQL unique index.
    • Concurrent create conflicts automatically retry through normal ownership and lifecycle checks while preserving unrelated persistence errors.
  • Migration & Operational Guidance:
    • Added documentation and SQL diagnostics for detecting duplicate provider subscription rows across single-tenant and multi-tenant schemas prior to running migrations.

Fixed

  • Atomic Terminal State Guards:
    • Enforced atomic database-level guards preventing obsolete or concurrent webhook reconciliations from mutating or resurrecting subscriptions in terminal states (:canceled, :incomplete_expired), even across same-second timestamps and custom update actions.
    • Terminal subscriptions (:canceled and :incomplete_expired, atom or string) now strictly return false from both the :canceling? calculation and AshBilling.canceling?/1, even when historical cancellation fields remain populated.
  • Customer Identity Association:
    • Atomically validates incoming customer identities. Contradictory customer mappings fail safely with retryable errors rather than overwriting subscriptions or granting unauthorized access.
    • Email alone no longer establishes billing identity; missing customers cannot be replaced by subscription or Checkout session IDs.
  • Credential Redaction:
    • Redacted sensitive API keys (sk_live_..., whsec_...) from configuration diagnostics and raised verification exceptions.
  • Igniter Installer (mix igniter.install ash_billing):
    • Registers generated resources and domains, configures credentials at runtime, passes configured webhook secrets, and preserves raw bodies through the endpoint parser.
    • Subscriptions generated with AshPostgres automatically inherit the customer's explicitly configured Repo.
  • Plug Body Reader (AshBilling.Plug.read_body/2):
    • Preserves exact raw webhook bytes across chunks for signature verification after Plug.Parsers.

[v0.2.1] - 2026-10-27

Added

  • Scheduled Cancellation Tracking (:cancel_at & :canceling?):
    • Injected cancel_at: :utc_datetime_usec attribute into AshBilling.Subscription extension, allowing applications to preserve and display exact future cancellation dates (such as cancellations scheduled from the modern Stripe Customer Portal).
    • Injected :canceling? calculation into AshBilling.Subscription evaluating whether cancel_at_period_end == true or cancel_at is scheduled for a future timestamp (cancel_at > now()).
    • Added public helper function AshBilling.canceling?/1 supporting both loaded structs and raw maps.
    • Extended AshBilling.WebhookSync to extract cancel_at from subscription payloads and authoritative live provider reconciliations.
    • Added cancel_at conflict detection to same_second_conflict?/3 to ensure divergent cancellation timestamps arriving in the same second trigger authoritative live provider reconciliation.

[v0.2.0] - 2026-10-27

Production-grade hardening release delivering distributed multi-node deduplication, atomic conditional webhook synchronization, live provider conflict reconciliation, and distributed PostgreSQL contention testing.

Added

  • Multi-Node Distributed Deduplication Engine (AshBilling.Deduplication):
    • Cryptographically secure lease_token generated on every lease acquisition.
    • Zombie worker rejection: workers completing (complete/2) or releasing (release/2) after lease expiration or reclamation are strictly rejected with {:error, :lease_token_mismatch}, preventing state corruption from delayed workers.
    • Automatic stale lease reclamation: abandoned leases exceeding configurable TTL (default 60s) or left in :failed state are atomically reclaimed with attempt counter incrementing.
    • Fail-fast configuration validation: :resource strategy strictly fails with {:error, :deduplication_resource_not_configured} rather than silently falling back to local memory, ensuring multi-node deployments fail safely.
    • Resource contract enforcement: validating upfront that persistent deduplication resources have both :status and an atomic :update action, failing fast with {:error, :resource_lacks_update_action}.
    • Immutable :processed events: once marked :processed, records cannot be released or mutated back to :failed.
  • Atomic Conditional Webhook Synchronization (AshBilling.WebhookSync):
    • update_subscription_safely/5: executes conditional updates via Ash.bulk_update (strategy: [:atomic]) filtering on (is_nil(last_event_created_at) or last_event_created_at <= ^event_dt). Out-of-order older webhooks are discarded without overwriting newer state.
    • Same-second conflict resolution (same_second_conflict?/3): detects divergent subscription attributes arriving within the same second and queries the payment provider for authoritative live state.
    • Safe live reconciliation (reconcile_subscription_with_provider/7): updates derived from authoritative live provider queries are written through atomic conditional bulk updates, preventing race conditions if newer events arrive during live API calls.
    • Terminal state protection: subscription records in terminal states (:canceled, :incomplete_expired) cannot be resurrected by delayed or reordered incoming webhooks.
  • Enterprise Webhook Ingestion Protocol (AshBilling.Plug):
    • Explicit HTTP 503 with Retry-After: 5 header when an incoming webhook is currently being processed by another worker (already_processing), instructing Stripe to back off and retry.
    • HTTP 500 fail-closed semantics for unconfigured deduplication resources, persistence failures, database sync errors, or missing webhook secrets.
    • Zero-downtime secret rotation: verifies all v1 signatures present in Stripe-Signature header using constant-time comparison.
  • PostgreSQL Distributed Contention Test Suite:
    • Real integration tests (AshBilling.PostgresDeduplicationTest) verifying multi-process lease contention, atomic completion, stale lease reclamation, and zombie worker protection against PostgreSQL 16.
    • Automated PostgreSQL 16 service container in GitHub Actions CI with strict CI enforcement (raise if PostgreSQL is unavailable when CI=true).
  • Spark DSL Compile-Time Verifiers:
    • VerifyCustomerRelationship: validates at compile time that configured customer relationships exist on the target resource.
    • VerifyCustomerIdAttribute: validates that custom customer ID attributes are string-compatible.
  • Modernized Stripe API Compatibility:
    • Recursive payload extraction for nested items.data[].current_period_end and trial_settings alongside legacy root timestamps.
    • Parameter normalization for mode in Checkout Sessions (accepting both :subscription and "subscription").
    • Deterministic idempotency keys (ash_cust_<id>) on customer creation.

Changed

  • Updated minimum test coverage gate to >= 90.00% in CI.
  • Updated documentation and tutorials to {:ash_billing, "~> 0.2.0"}.

[v0.1.0] - 2026-10-26

Initial release of ash_billing: Declarative billing, subscription, and payment extensions for the Ash Framework.

Added

  • Spark DSL Extensions:
    • AshBilling.Resource: Configures customer resources (customer_id_attribute, provider).
    • AshBilling.Subscription: Injects subscription attributes (provider_subscription_id, status, price_id, current_period_end, trial_ends_at, cancel_at_period_end) and calculations (active?, on_trial?).
    • AshBilling.WebhookEvent: Database-backed resource extension for cluster-wide webhook deduplication.
  • Stripe Provider:
  • Secure Webhook Plug:
    • AshBilling.Plug: Endpoint with constant-time HMAC-SHA256 signature verification and replay attack protection.
    • HTTP 500 retry protocol: Responds with status 500 on database synchronization failure to trigger Stripe automatic exponential retries.
    • Multi-node deduplication strategies: in-memory ETS (:memory) and database-backed Ash resource (:resource).
  • Resilient Webhook Synchronization (AshBilling.WebhookSync):
    • Polymorphic extraction for customer IDs and pricing objects (supporting both string IDs and expanded Stripe maps).
    • Exception-safe UNIX timestamp conversions (DateTime.from_unix/2).
    • Idempotent concurrency race resolution: automatic update fallback when duplicate creation arrives concurrently.
  • Native Ash Policies:
  • Developer Diagnostics & Tooling:
    • AshBilling.check_configuration/1 and AshBilling.verify_configuration!/1: Pre-flight diagnostics for API keys, secrets, and registered resources.
    • Automated installer task: mix igniter.install ash_billing (Mix.Tasks.Igniter.Install.AshBilling).
    • Standard :telemetry spans across checkout, billing portal, webhook ingestion, and database synchronization.
    • Built-in Spark cheat sheets and ExDoc documentation.
    • Multi-version CI matrix across Elixir 1.17, 1.18 and Erlang/OTP 26, 27.
    • Weekly Canary CI workflow testing against ash-project/ash@main and ash-project/spark@main.