Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(backend): sync tier on checkout + expire abandoned sessions + lazy Stripe reconciliation (#13060)

Zamil Majdy51014b6d4a23
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 7caeaae5f3..56ecadcb99 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -78,6 +78,7 @@ from backend.data.credit import (
set_subscription_tier,
sync_subscription_from_stripe,
sync_subscription_schedule_from_stripe,
+ sync_tier_from_checkout_session,
)
from backend.data.graph import GraphSettings
from backend.data.model import CredentialsMetaInput, UserOnboarding
@@ -1322,6 +1323,7 @@ async def stripe_webhook(request: Request):
)
return Response(status_code=200)
await UserCredit().fulfill_checkout(session_id=session_id)
+ await sync_tier_from_checkout_session(data_object)
if event_type in (
"customer.subscription.created",
diff --git a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
new file mode 100644
index 0000000000..86b6b2bdf3
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
@@ -0,0 +1,316 @@
+"""Unit tests for Stripe webhook handler and subscription checkout helpers."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import fastapi
+import fastapi.testclient
+import pytest_mock
+import stripe
+
+from backend.data.credit import (
+ _expire_open_subscription_sessions,
+ reconcile_stripe_tier_for_user,
+ sync_tier_from_checkout_session,
+)
+
+from .v1 import v1_router
+
+app = fastapi.FastAPI()
+app.include_router(v1_router)
+client = fastapi.testclient.TestClient(app)
+
+
+def _make_checkout_event(mode: str, sub_id: str | None = None) -> dict:
+ return {
+ "type": "checkout.session.completed",
+ "data": {
+ "object": {
+ "id": "cs_test_123",
+ "mode": mode,
+ "subscription": sub_id,
+ }
+ },
+ }
+
+
+# ---------------------------------------------------------------------------
+# Webhook endpoint tests — verify the handler calls the right helpers
+# ---------------------------------------------------------------------------
+
+
+def test_stripe_webhook_checkout_calls_sync_tier_helper(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ mocker.patch(
+ "stripe.Webhook.construct_event",
+ return_value=_make_checkout_event("subscription", "sub_123"),
+ )
+ mocker.patch(
+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ new="whsec_test",
+ )
+ mocker.patch(
+ "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ )
+ mock_sync = mocker.patch(
+ "backend.api.features.v1.sync_tier_from_checkout_session",
+ new_callable=AsyncMock,
+ )
+
+ response = client.post(
+ "/credits/stripe_webhook",
+ content=b"{}",
+ headers={"stripe-signature": "t=1,v1=sig"},
+ )
+
+ assert response.status_code == 200
+ mock_sync.assert_called_once()
+
+
+def test_stripe_webhook_checkout_propagates_sync_failure(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ """Tier sync failure must surface as 5xx so Stripe retries the webhook."""
+ mocker.patch(
+ "stripe.Webhook.construct_event",
+ return_value=_make_checkout_event("subscription", "sub_err"),
+ )
+ mocker.patch(
+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ new="whsec_test",
+ )
+ mocker.patch(
+ "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ )
+ mocker.patch(
+ "backend.api.features.v1.sync_tier_from_checkout_session",
+ new_callable=AsyncMock,
+ side_effect=stripe.StripeError("network error"),
+ )
+
+ # raise_server_exceptions=False so the test client returns 500 instead of
+ # re-raising, mirroring real ASGI behavior where Stripe sees the 5xx and retries.
+ nonraising_client = fastapi.testclient.TestClient(
+ app, raise_server_exceptions=False
+ )
+ response = nonraising_client.post(
+ "/credits/stripe_webhook",
+ content=b"{}",
+ headers={"stripe-signature": "t=1,v1=sig"},
+ )
+
+ assert response.status_code >= 500
+
+
+# ---------------------------------------------------------------------------
+# sync_tier_from_checkout_session unit tests
+# ---------------------------------------------------------------------------
+
+
+async def test_sync_tier_subscription_mode_retrieves_and_syncs(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ fake_sub = MagicMock()
+ mocker.patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ return_value=fake_sub,
+ )
+ mock_sync = mocker.patch(
+ "backend.data.credit.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+
+ await sync_tier_from_checkout_session(
+ {"mode": "subscription", "subscription": "sub_123"}
+ )
+
+ mock_sync.assert_called_once_with(dict(fake_sub))
+
+
+async def test_sync_tier_payment_mode_is_noop(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ mock_retrieve = mocker.patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ )
+
+ await sync_tier_from_checkout_session({"mode": "payment"})
+
+ mock_retrieve.assert_not_called()
+
+
+async def test_sync_tier_missing_sub_id_is_noop(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ mock_retrieve = mocker.patch(
+ "backend.data.credit.stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ )
+
+ await sync_tier_from_checkout_session(
+ {"mode": "subscription", "subscription": None}
+ )
+
+ mock_retrieve.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# _expire_open_subscription_sessions tests
+# ---------------------------------------------------------------------------
+
+
+async def test_expire_open_subscription_sessions_empty_list(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ mock_sessions = MagicMock()
+ mock_sessions.data = []
+ mock_sessions.has_more = False
+ mocker.patch(
+ "stripe.checkout.Session.list_async",
+ new_callable=AsyncMock,
+ return_value=mock_sessions,
+ )
+ mock_expire = mocker.patch(
+ "stripe.checkout.Session.expire_async", new_callable=AsyncMock
+ )
+
+ await _expire_open_subscription_sessions("cus_test")
+
+ stripe.checkout.Session.list_async.assert_called_once_with(
+ customer="cus_test", status="open", limit=100
+ )
+ mock_expire.assert_not_called()
+
+
+async def test_expire_open_subscription_sessions_expires_only_subscription_sessions(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ sub_session = MagicMock(id="cs_sub_open", mode="subscription")
+ payment_session = MagicMock(id="cs_pay_open", mode="payment")
+
+ mock_sessions = MagicMock()
+ mock_sessions.data = [sub_session, payment_session]
+ mock_sessions.has_more = False
+ mocker.patch(
+ "stripe.checkout.Session.list_async",
+ new_callable=AsyncMock,
+ return_value=mock_sessions,
+ )
+ mock_expire = mocker.patch(
+ "stripe.checkout.Session.expire_async", new_callable=AsyncMock
+ )
+
+ await _expire_open_subscription_sessions("cus_test")
+
+ mock_expire.assert_called_once_with("cs_sub_open")
+
+
+async def test_expire_open_subscription_sessions_paginates(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ page1 = MagicMock()
+ page1.data = [MagicMock(id="cs_page1", mode="subscription")]
+ page1.has_more = True
+ page2 = MagicMock()
+ page2.data = [MagicMock(id="cs_page2", mode="subscription")]
+ page2.has_more = False
+
+ mock_list = mocker.patch(
+ "stripe.checkout.Session.list_async",
+ new_callable=AsyncMock,
+ side_effect=[page1, page2],
+ )
+ mock_expire = mocker.patch(
+ "stripe.checkout.Session.expire_async", new_callable=AsyncMock
+ )
+
+ await _expire_open_subscription_sessions("cus_test")
+
+ assert mock_list.call_count == 2
+ mock_list.assert_any_call(customer="cus_test", status="open", limit=100)
+ mock_list.assert_any_call(
+ customer="cus_test", status="open", limit=100, starting_after="cs_page1"
+ )
+ assert mock_expire.call_count == 2
+
+
+# ---------------------------------------------------------------------------
+# reconcile_stripe_tier_for_user tests
+# ---------------------------------------------------------------------------
+
+
+async def test_reconcile_stripe_tier_no_customer_returns_false(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ user = MagicMock(stripe_customer_id=None)
+ mocker.patch(
+ "backend.data.credit.get_user_by_id", new_callable=AsyncMock, return_value=user
+ )
+ mock_get_sub = mocker.patch(
+ "backend.data.credit._get_active_subscription", new_callable=AsyncMock
+ )
+
+ assert await reconcile_stripe_tier_for_user("user_abc") is False
+ mock_get_sub.assert_not_called()
+
+
+async def test_reconcile_stripe_tier_no_active_sub_returns_false(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ user = MagicMock(stripe_customer_id="cus_abc")
+ mocker.patch(
+ "backend.data.credit.get_user_by_id", new_callable=AsyncMock, return_value=user
+ )
+ mocker.patch(
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ return_value=None,
+ )
+ mock_sync = mocker.patch(
+ "backend.data.credit.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+
+ assert await reconcile_stripe_tier_for_user("user_abc") is False
+ mock_sync.assert_not_called()
+
+
+async def test_reconcile_stripe_tier_stripe_error_returns_false(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ user = MagicMock(stripe_customer_id="cus_abc")
+ mocker.patch(
+ "backend.data.credit.get_user_by_id", new_callable=AsyncMock, return_value=user
+ )
+ mocker.patch(
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ side_effect=stripe.StripeError("network error"),
+ )
+ mock_sync = mocker.patch(
+ "backend.data.credit.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+
+ assert await reconcile_stripe_tier_for_user("user_abc") is False
+ mock_sync.assert_not_called()
+
+
+async def test_reconcile_stripe_tier_active_sub_syncs_and_returns_true(
+ mocker: pytest_mock.MockFixture,
+) -> None:
+ user = MagicMock(stripe_customer_id="cus_abc")
+ fake_sub = MagicMock()
+ mocker.patch(
+ "backend.data.credit.get_user_by_id", new_callable=AsyncMock, return_value=user
+ )
+ mocker.patch(
+ "backend.data.credit._get_active_subscription",
+ new_callable=AsyncMock,
+ return_value=fake_sub,
+ )
+ mock_sync = mocker.patch(
+ "backend.data.credit.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+
+ assert await reconcile_stripe_tier_for_user("user_abc") is True
+ mock_sync.assert_called_once_with(dict(fake_sub))
diff --git a/autogpt_platform/backend/backend/copilot/rate_limit.py b/autogpt_platform/backend/backend/copilot/rate_limit.py
index 0d79e42be4..a4966aa952 100644
--- a/autogpt_platform/backend/backend/copilot/rate_limit.py
+++ b/autogpt_platform/backend/backend/copilot/rate_limit.py
@@ -925,6 +925,42 @@ async def _fetch_user_tier(user_id: str) -> SubscriptionTier:
raise _UserNotFoundError(user_id)
+_STRIPE_RECONCILE_PREFIX = "stripe_reconcile:"
+_STRIPE_RECONCILE_TTL = 300 # seconds — matches the tier cache TTL
+
+
+async def _maybe_reconcile_stripe_tier(user_id: str) -> bool:
+ """Gate a lazy Stripe subscription check to at most once per 5 min per user.
+
+ Sets a Redis NX key before calling Stripe so concurrent requests don't
+ all fan out simultaneously. The key is deleted on transient errors so
+ the next request can retry. Returns True when a subscription was found
+ and synced (tier was updated in DB + cache cleared).
+ """
+ gate_key = f"{_STRIPE_RECONCILE_PREFIX}{user_id}"
+ try:
+ redis = await get_redis_async()
+ if not await redis.set(gate_key, "1", nx=True, ex=_STRIPE_RECONCILE_TTL):
+ return False # already checked recently
+ except Exception as exc:
+ logger.warning(
+ "stripe_reconcile: redis gate unavailable for %s: %s", user_id[:8], exc
+ )
+ return False
+
+ try:
+ from backend.data.credit import reconcile_stripe_tier_for_user # avoid circular
+
+ return await reconcile_stripe_tier_for_user(user_id)
+ except Exception as exc:
+ logger.warning("stripe_reconcile: check failed for %s: %s", user_id[:8], exc)
+ try:
+ await redis.delete(gate_key)
+ except Exception:
+ pass
+ return False
+
+
async def get_user_tier(user_id: str) -> SubscriptionTier:
"""Look up the user's rate-limit tier from the database.
@@ -934,9 +970,17 @@ async def get_user_tier(user_id: str) -> SubscriptionTier:
Falls back to ``DEFAULT_TIER`` **without caching** when the DB is
unreachable or returns an unrecognised value, so the next call retries
the query instead of serving a stale fallback for up to 5 minutes.
+
+ When the resolved tier is NO_TIER and the user has a Stripe customer
+ record, a lazy reconciliation check is attempted (gated to once per 5
+ minutes via a Redis key) to recover from missed webhooks.
"""
+ tier_from_db = True
try:
- return await _fetch_user_tier(user_id)
+ tier = await _fetch_user_tier(user_id)
+ except _UserNotFoundError:
+ # Row missing or tier is NULL — DB-confirmed NO_TIER, eligible for reconciliation.
+ tier = SubscriptionTier.NO_TIER
except Exception as exc:
logger.warning(
"Failed to resolve rate-limit tier for user %s, defaulting to %s: %s",
@@ -944,7 +988,23 @@ async def get_user_tier(user_id: str) -> SubscriptionTier:
DEFAULT_TIER.value,
exc,
)
- return DEFAULT_TIER
+ tier = DEFAULT_TIER
+ tier_from_db = False
+
+ if tier != SubscriptionTier.NO_TIER:
+ return tier
+
+ if tier_from_db and await _maybe_reconcile_stripe_tier(user_id):
+ try:
+ return await _fetch_user_tier(user_id)
+ except Exception as exc:
+ logger.warning(
+ "get_user_tier: tier re-read failed after reconciliation for %s: %s",
+ user_id[:8],
+ exc,
+ )
+
+ return tier
# Expose cache management on the public function so callers (including tests)
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 2c92eea65c..cf1e7d654e 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -2259,6 +2259,84 @@ async def get_subscription_price_id(
return price_id if isinstance(price_id, str) and price_id else None
+async def _expire_open_subscription_sessions(customer_id: str) -> None:
+ """Expire open subscription checkout sessions for the customer.
+
+ An abandoned subscription session leaves an incomplete subscription + open invoice
+ in Stripe. Expiring it triggers Stripe to cancel that subscription and void the
+ invoice, so the user is not shown phantom charges on their billing page.
+ """
+ try:
+ starting_after: str | None = None
+ while True:
+ list_kwargs: dict = {
+ "customer": customer_id,
+ "status": "open",
+ "limit": 100,
+ }
+ if starting_after:
+ list_kwargs["starting_after"] = starting_after
+ sessions = await stripe.checkout.Session.list_async(**list_kwargs)
+ for s in sessions.data:
+ if s.mode == "subscription":
+ try:
+ await stripe.checkout.Session.expire_async(s.id)
+ except stripe.StripeError:
+ logger.warning(
+ "create_subscription_checkout: could not expire session %s",
+ s.id,
+ )
+ if not sessions.has_more or not sessions.data:
+ break
+ starting_after = sessions.data[-1].id
+ except Exception:
+ logger.warning(
+ "create_subscription_checkout: could not list open sessions for %s",
+ customer_id,
+ )
+
+
+async def reconcile_stripe_tier_for_user(user_id: str) -> bool:
+ """Check Stripe for an active subscription and sync tier if found.
+
+ Called as a lazy fallback when a user is on NO_TIER to recover from
+ missed webhooks. Returns True if an active subscription was found and
+ synced. Does NOT create a Stripe customer — only checks existing ones.
+ """
+ user = await get_user_by_id(user_id)
+ if not user.stripe_customer_id:
+ return False
+ try:
+ sub = await _get_active_subscription(user.stripe_customer_id)
+ except Exception:
+ logger.warning(
+ "reconcile_stripe_tier_for_user: Stripe lookup failed for user %s",
+ user_id[:8],
+ )
+ return False
+ if sub is None:
+ return False
+ await sync_subscription_from_stripe(dict(sub))
+ return True
+
+
+async def sync_tier_from_checkout_session(data_object: dict) -> None:
+ """Sync subscription tier from a checkout.session.completed event payload.
+
+ Retrieves the Stripe subscription and calls sync_subscription_from_stripe so
+ the tier is set immediately without waiting for customer.subscription.created.
+ No-op when mode != "subscription" or subscription ID is absent.
+ Raises stripe.StripeError if the subscription cannot be retrieved.
+ """
+ if data_object.get("mode") != "subscription":
+ return
+ sub_id = data_object.get("subscription")
+ if not sub_id:
+ return
+ sub = await stripe.Subscription.retrieve_async(sub_id)
+ await sync_subscription_from_stripe(dict(sub))
+
+
async def create_subscription_checkout(
user_id: str,
tier: SubscriptionTier,
@@ -2271,6 +2349,7 @@ async def create_subscription_checkout(
if not price_id:
raise ValueError(f"Subscription not available for tier {tier.value}")
customer_id = await get_stripe_customer_id(user_id)
+ await _expire_open_subscription_sessions(customer_id)
session = await run_in_threadpool(
stripe.checkout.Session.create,
customer=customer_id,