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) andprovider_subscription_item_id(:string) toAshBilling.Subscription(AddSubscriptionAttributes+ wildcard exclusion viaProtectBillingAttributes).WebhookSyncandAshBilling.reconcile_subscription/2now extract, persist, compare (@financial_sync_fields), and atomically CAS-guard both attributes for single-item subscriptions: legitimately absent/nullquantities remainnil(never assuming1), explicit0persists as0contracted 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): ExtendedAshBilling.check_configuration/1(preserving backwards-compatible{:ok, %{status: :valid, ...}}/{:error, reasons}contract) with layered structural, read-only PostgreSQL schema/migration/index checks (0.6.0last_reconciled_atand0.7.0quantity/provider_subscription_item_id),WebhookEventprivacy verification (rejecting accidentalAshJsonApi/AshGraphqlexposure), multitenancy/Repo checks, HTTP timeout guidance, optional read-only provider probes, and explicitconfiguration_validvsproduction_readydistinction. Added read-onlymix ash_billing.doctorsupportingPASS/WARN/FAILtext and--jsonoutput 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 aTelemetry.Metricsdashboard guide in Diagnostics, Recovery CLI & Observability.- Runnable SaaS Reference Application (
examples/saas_example): Convertedexamples/saas_exampleinto 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, transactionalFOR UPDATEseat enforcement,AshBilling.Checks.SubscribedandAshBilling.Checks.HasPricepolicies, HMAC-verified webhooks with PostgreSQL deduplication, workingmix ash_billing.doctor/mix ash_billing.reconcileintegrations, and an automated CI test suite.
[0.6.0] - 2026-11-19
Added & Changed
- Durable Reconciliation Checkpoints (
last_reconciled_at): Added nullable protected attributelast_reconciled_at(:utc_datetime_usec) toAshBilling.Subscription. See Upgrading to 0.6 for the required database migration. - PostgreSQL Shared-Clock Checkpointing:
AshBilling.reconcile_subscription/2queries PostgreSQLclock_timestamp()under canonicalCustomer -> SubscriptionFOR UPDATElocks, omits fabricated local timestamps ("created" => nil), and persistslast_reconciled_atmonotonically and atomically in the same transaction as reconciled state. - Post-Reconciliation Financial Verification: When
last_reconciled_atis present,AshBilling.WebhookSyncevaluates 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 underFOR UPDATEregardless ofevent.createdage, failing closed on provider or PostgreSQL errors with no ETS state. - 0.5.x Upgrade Cursor Healing & Operational Guidance:
AshBilling.reconcile_subscription/2now automatically clears ahead/futurelast_event_created_atvalues (> PostgreSQL clock_timestamp()) tonilatomically alongside persistinglast_reconciled_at(and supportsreset_event_cursor?: truefor shared app+DB forward clock skew), preventing synthetic0.5.xreconciliation timestamps from causingexisting_event_newer?/2to ignore legitimate Stripe webhooks. Documented explicitquantitypersistence scope and HTTP timeout /FOR UPDATElock 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/2now enters a transaction lock boundary and acquires canonicalCustomer -> SubscriptionFOR UPDATErow locks before callingAshBilling.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 preservingv0.5.2synthetic timestamp semantics ("created" => System.system_time(:second)) with no breaking API or schema changes. - Billing Invariants Documentation: Added the
Billing invariantssection todocumentation/topics/webhooks-and-resilience.mdmatching verified implementation behavior (:active,:trialing, and:past_dueaccess rules,ash_cust_idempotency key prefix, lock order, and0.5.xsynthetic timestamp boundaries). - Canary CI: Added PostgreSQL 16 service and readiness verification to
.github/workflows/canary.yml, removedcontinue-on-error: trueso compatibility regressions fail visibly, and classifiedINFRASTRUCTURE_FAILUREvsCOMPATIBILITY_FAILUREoutcomes.
[0.5.2] - 2026-11-06
Security & Reliability Hardening
- Subscription Quantity Updates (AB-01, AB-02): Added optional
update_quantity/3callback toAshBilling.Providerbehaviour and implemented it inAshBilling.Providers.Stripe. Quantity updates now POST onlyitems[0][id]anditems[0][quantity], omittingitems[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 whensubscription_item_idis supplied withoutprice_id. An optional:price_idcan 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 dynamicsubscription_idpath segments inAshBilling.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 raisingProtocol.UndefinedErroronJason.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 viaLogger.error/1while 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/2returning{:error, :invalid_customer}for non-map / non-struct inputs (nil,"", numbers, lists), replacingFunctionClauseError. - Documentation & Telemetry Consistency (AB-07): Documented
[:ash_billing, :swap_plan]and[:ash_billing, :update_quantity]telemetry spans inREADME.md. UpdatedSECURITY.mdsupported versions to explicitly list0.5.x.
[0.5.1] - 2026-11-03
Security
- Resolved Hex advisory on retired
ash_sql 0.8.4(Ecto query cache issue) by upgradingash_sqlto0.8.7(andnimble_optionsto1.2.0). Verified withmix 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'sprice_idmatches any element in the list. Enforces fail-closed semantics on empty lists, blank strings, or invalid non-binary elements.
Fixed
- Public error contracts in
AshBilling:AshBilling.create_portal_session/2: Returns{:error, :missing_return_url}when:return_urlis missing, blank, or non-binary, avoidingKeyError.AshBilling.get_subscription/2,cancel_subscription/2,resume_subscription/2: Return{:error, :invalid_subscription_id}when givennil,"", or unsupported structures, preventingFunctionClauseErrorand unneeded Stripe API requests.AshBilling.swap_plan/3: Returns{:error, :invalid_subscription_id}when the subscription ID is blank or invalid, and{:error, :invalid_price_id}whennew_price_idis blank or invalid.AshBilling.update_quantity/3: Returns{:error, :invalid_subscription_id}when the subscription ID is blank or invalid.
Developer Experience & Documentation
mix ash_billing.install: Enhanced post-install notice with a concrete PostgreSQL-backedWebhookEventresource example for clustered deployments.- Updated
README.mdand documentation examples to highlightHasPricemulti-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.HasPricenow fails closed whenprice:is missing or invalid.- Invalid price configurations are rejected during Ash policy compilation.
- Added authorization and policy-compilation regression tests.
Documentation
- Clarified that
WebhookEventis 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
HasPricewithout a validprice:must supply an explicit price or useAshBilling.Checks.Subscribedfor 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 NOWAITand 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_attombstone, 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_atto 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.
- Retain customer IDs with a persistent
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_idwhen 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
- Support
Ash.CiStringand Custom Structs in Stripe Payloads:- Automatically coerce
Ash.CiStringvalues (commonly used byAshAuthenticationfor:emailfields) to strings in the Stripe form encoder. - Safely serialize structs implementing
String.Charsor unwrap them to maps, preventingProtocol.UndefinedErrorwhen invokingAshBilling.create_customer/2orAshBilling.create_checkout_session/2.
- Automatically coerce
[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_idscoped 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.
- Enforced unique identity on
- 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 (
:canceledand:incomplete_expired, atom or string) now strictly returnfalsefrom both the:canceling?calculation andAshBilling.canceling?/1, even when historical cancellation fields remain populated.
- Enforced atomic database-level guards preventing obsolete or concurrent webhook reconciliations from mutating or resurrecting subscriptions in terminal states (
- 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.
- Redacted sensitive API keys (
- 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.
- Preserves exact raw webhook bytes across chunks for signature verification after
[v0.2.1] - 2026-10-27
Added
- Scheduled Cancellation Tracking (
:cancel_at&:canceling?):- Injected
cancel_at: :utc_datetime_usecattribute intoAshBilling.Subscriptionextension, allowing applications to preserve and display exact future cancellation dates (such as cancellations scheduled from the modern Stripe Customer Portal). - Injected
:canceling?calculation intoAshBilling.Subscriptionevaluating whethercancel_at_period_end == trueorcancel_atis scheduled for a future timestamp (cancel_at > now()). - Added public helper function
AshBilling.canceling?/1supporting both loaded structs and raw maps. - Extended
AshBilling.WebhookSyncto extractcancel_atfrom subscription payloads and authoritative live provider reconciliations. - Added
cancel_atconflict detection tosame_second_conflict?/3to ensure divergent cancellation timestamps arriving in the same second trigger authoritative live provider reconciliation.
- Injected
[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_tokengenerated 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
:failedstate are atomically reclaimed with attempt counter incrementing. - Fail-fast configuration validation:
:resourcestrategy 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
:statusand an atomic:updateaction, failing fast with{:error, :resource_lacks_update_action}. - Immutable
:processedevents: once marked:processed, records cannot be released or mutated back to:failed.
- Cryptographically secure
- Atomic Conditional Webhook Synchronization (
AshBilling.WebhookSync):update_subscription_safely/5: executes conditional updates viaAsh.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: 5header 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
v1signatures present inStripe-Signatureheader using constant-time comparison.
- Explicit HTTP 503 with
- 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 (
raiseif PostgreSQL is unavailable whenCI=true).
- Real integration tests (
- 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_endandtrial_settingsalongside legacy root timestamps. - Parameter normalization for
modein Checkout Sessions (accepting both:subscriptionand"subscription"). - Deterministic idempotency keys (
ash_cust_<id>) on customer creation.
- Recursive payload extraction for nested
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:
AshBilling.create_customer/2: Generates Stripe customer records with metadata.AshBilling.create_checkout_session/2: Creates Stripe Checkout sessions with pre-filled customer email, metadata, and success/cancel URLs.AshBilling.create_portal_session/2: Generates Stripe Customer Billing Portal sessions with defensive configuration checks.AshBilling.cancel_subscription/2andAshBilling.resume_subscription/2: Subscription cancellation and period-end resumption.AshBilling.swap_plan/3: Plan upgrades and downgrades with automatic proration and multi-item resolution.AshBilling.update_quantity/3: Per-seat quantity scaling with automatic item resolution.
- 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:
AshBilling.Checks.Subscribed: Policy check that verifies if the actor has an active subscription or ongoing trial.AshBilling.Checks.HasPrice: Policy check restricting access to specified price tiers.
- Developer Diagnostics & Tooling:
AshBilling.check_configuration/1andAshBilling.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
:telemetryspans 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@mainandash-project/spark@main.