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.
refactor(backend): remove BetaUserCredit monthly credit refill (hotfix) (#12969)
Toran Bruce Richards9e4172607806
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.pyindex b9241cd9cc..41b086a700 100644--- a/autogpt_platform/backend/backend/data/credit.py+++ b/autogpt_platform/backend/backend/data/credit.py@@ -36,7 +36,7 @@ from backend.data.user import get_user_by_id, get_user_email_by_idfrom backend.notifications.notifications import queue_notification_asyncfrom backend.util.cache import cachedfrom backend.util.exceptions import InsufficientBalanceError-from backend.util.feature_flag import Flag, get_feature_flag_value, is_feature_enabled+from backend.util.feature_flag import Flag, get_feature_flag_valuefrom backend.util.json import SafeJson, dumpsfrom backend.util.models import Paginationfrom backend.util.retry import func_retry@@ -1154,37 +1154,6 @@ class UserCredit(UserCreditBase):]-class BetaUserCredit(UserCredit):- """- This is a temporary class to handle the test user utilizing monthly credit refill.- TODO: Remove this class & its feature toggle.- """-- def __init__(self, num_user_credits_refill: int):- self.num_user_credits_refill = num_user_credits_refill-- async def get_credits(self, user_id: str) -> int:- cur_time = self.time_now().date()- balance, snapshot_time = await self._get_credits(user_id)- if (snapshot_time.year, snapshot_time.month) == (cur_time.year, cur_time.month):- return balance-- target = self.num_user_credits_refill-- try:- balance, _ = await self._add_transaction(- user_id=user_id,- amount=max(target - balance, 0),- transaction_type=CreditTransactionType.GRANT,- transaction_key=f"MONTHLY-CREDIT-TOP-UP-{cur_time}",- metadata=SafeJson({"reason": "Monthly credit refill"}),- )- return balance- except UniqueViolationError:- # Already refilled this month- return (await self._get_credits(user_id))[0]--class DisabledUserCredit(UserCreditBase):async def get_credits(self, *args, **kwargs) -> int:return 100@@ -1221,30 +1190,16 @@ class DisabledUserCredit(UserCreditBase):async def get_user_credit_model(user_id: str) -> UserCreditBase:- """- Get the credit model for a user, considering LaunchDarkly flags.-- Args:- user_id (str): The user ID to check flags for.+ """Return the credit model for a user.- Returns:- UserCreditBase: The appropriate credit model for the user+ The ``user_id`` parameter is currently unused but retained for ABI+ stability — many callers already pass it, and the function may need to+ branch on user identity again in the future."""+ _ = user_idif not settings.config.enable_credit:return DisabledUserCredit()-- # Check LaunchDarkly flag for payment pilot users- # Default to False (beta monthly credit behavior) to maintain current behavior- is_payment_enabled = await is_feature_enabled(- Flag.ENABLE_PLATFORM_PAYMENT, user_id, default=False- )-- if is_payment_enabled:- # Payment enabled users get UserCredit (no monthly refills, enable payments)- return UserCredit()- else:- # Default behavior: users get beta monthly credits- return BetaUserCredit(settings.config.num_user_credits_refill)+ return UserCredit()def get_block_costs() -> dict[str, list["BlockCost"]]:diff --git a/autogpt_platform/backend/backend/data/credit_concurrency_test.py b/autogpt_platform/backend/backend/data/credit_concurrency_test.pyindex 90f9487e21..6a7be947a1 100644--- a/autogpt_platform/backend/backend/data/credit_concurrency_test.py+++ b/autogpt_platform/backend/backend/data/credit_concurrency_test.py@@ -20,7 +20,6 @@ from backend.util.exceptions import InsufficientBalanceErrorfrom backend.util.json import SafeJsonfrom backend.util.test import SpinTestServer-# Test with both UserCredit and BetaUserCredit if neededcredit_system = UserCredit()diff --git a/autogpt_platform/backend/backend/data/credit_integration_test.py b/autogpt_platform/backend/backend/data/credit_integration_test.pyindex 45fdd27992..88a7440418 100644--- a/autogpt_platform/backend/backend/data/credit_integration_test.py+++ b/autogpt_platform/backend/backend/data/credit_integration_test.py@@ -11,9 +11,11 @@ from prisma.models import CreditTransaction, User, UserBalancefrom backend.data.credit import (AutoTopUpConfig,- BetaUserCredit,+ DisabledUserCredit,UsageTransactionMetadata,+ UserCredit,get_auto_top_up,+ get_user_credit_model,set_auto_top_up,)from backend.util.json import SafeJson@@ -61,7 +63,7 @@ async def test_credit_transaction_enum_casting_integration(cleanup_test_user):platform."CreditTransactionType" but got "CreditTransactionType"."""user_id = cleanup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# Test each transaction type to ensure enum casting workstest_cases = [@@ -111,11 +113,9 @@ async def test_auto_top_up_integration(cleanup_test_user, monkeypatch):from backend.data.credit import settingsmonkeypatch.setattr(settings.config, "enable_credit", True)- monkeypatch.setattr(settings.config, "enable_beta_monthly_credit", True)- monkeypatch.setattr(settings.config, "num_user_credits_refill", 1000)user_id = cleanup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# First add some initial credits so we can test the configuration and subsequent behaviorbalance, _ = await credit_system._add_transaction(@@ -177,7 +177,7 @@ async def test_enable_transaction_enum_casting_integration(cleanup_test_user):involves SQL queries with CreditTransactionType enum casting."""user_id = cleanup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# Create an inactive transactionbalance, tx_key = await credit_system._add_transaction(@@ -238,11 +238,9 @@ async def test_auto_top_up_configuration_storage(cleanup_test_user, monkeypatch)from backend.data.credit import settingsmonkeypatch.setattr(settings.config, "enable_credit", True)- monkeypatch.setattr(settings.config, "enable_beta_monthly_credit", True)- monkeypatch.setattr(settings.config, "num_user_credits_refill", 1000)user_id = cleanup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# Set initial balancebalance, _ = await credit_system._add_transaction(@@ -275,3 +273,24 @@ async def test_auto_top_up_configuration_storage(cleanup_test_user, monkeypatch)# Should only have the initial GRANT transactionassert len(transactions) == 1assert transactions[0].type == CreditTransactionType.GRANT++[email protected](loop_scope="session")+async def test_get_user_credit_model_returns_usercredit_unconditionally(+ cleanup_test_user, monkeypatch+):+ """Regression guard: the factory must never branch back to a beta-cohort class.++ Uses ``__class__ is UserCredit`` (not ``isinstance``) so that any future+ ``class BetaFoo(UserCredit)`` resurrection trips this test instead of+ silently passing.+ """+ from backend.data.credit import settings++ monkeypatch.setattr(settings.config, "enable_credit", True)+ model = await get_user_credit_model(cleanup_test_user)+ assert model.__class__ is UserCredit++ monkeypatch.setattr(settings.config, "enable_credit", False)+ model_disabled = await get_user_credit_model(cleanup_test_user)+ assert model_disabled.__class__ is DisabledUserCreditdiff --git a/autogpt_platform/backend/backend/data/credit_metadata_test.py b/autogpt_platform/backend/backend/data/credit_metadata_test.pyindex f55abd71c1..81643def4b 100644--- a/autogpt_platform/backend/backend/data/credit_metadata_test.py+++ b/autogpt_platform/backend/backend/data/credit_metadata_test.py@@ -13,7 +13,7 @@ import pytestfrom prisma.enums import CreditTransactionTypefrom prisma.models import CreditTransaction, UserBalance-from backend.data.credit import BetaUserCredit+from backend.data.credit import UserCreditfrom backend.data.user import DEFAULT_USER_IDfrom backend.util.json import SafeJson@@ -38,7 +38,7 @@ async def setup_test_user():async def test_metadata_json_serialization(setup_test_user):"""Test that metadata is properly serialized for JSONB column in raw SQL."""user_id = setup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# Test with complex metadata that would fail if not properly serializedcomplex_metadata = SafeJson(@@ -90,7 +90,7 @@ async def test_metadata_json_serialization(setup_test_user):async def test_enable_transaction_metadata_serialization(setup_test_user):"""Test that _enable_transaction also handles metadata JSON serialization correctly."""user_id = setup_test_user- credit_system = BetaUserCredit(1000)+ credit_system = UserCredit()# First create an inactive transactionbalance, tx_key = await credit_system._add_transaction(diff --git a/autogpt_platform/backend/backend/data/credit_test.py b/autogpt_platform/backend/backend/data/credit_test.pyindex 0f5cd152a0..5f38be4cc0 100644--- a/autogpt_platform/backend/backend/data/credit_test.py+++ b/autogpt_platform/backend/backend/data/credit_test.py@@ -1,31 +1,26 @@-from datetime import datetime, timedelta, timezone-import pytestfrom prisma.enums import CreditTransactionTypefrom prisma.models import CreditTransaction, UserBalancefrom backend.blocks import get_blockfrom backend.blocks.llm import AITextGeneratorBlock-from backend.data.credit import BetaUserCredit, UsageTransactionMetadata+from backend.data.credit import UsageTransactionMetadata, UserCreditfrom backend.data.execution import ExecutionContext, NodeExecutionEntryfrom backend.data.user import DEFAULT_USER_IDfrom backend.executor.utils import block_usage_costfrom backend.integrations.credentials_store import openai_credentialsfrom backend.util.test import SpinTestServer-REFILL_VALUE = 1000-user_credit = BetaUserCredit(REFILL_VALUE)+user_credit = UserCredit()async def disable_test_user_transactions():await CreditTransaction.prisma().delete_many(where={"userId": DEFAULT_USER_ID})- # Also reset the balance to 0 and set updatedAt to old date to trigger monthly refill- old_date = datetime.now(timezone.utc) - timedelta(days=35) # More than a month agoawait UserBalance.prisma().upsert(where={"userId": DEFAULT_USER_ID},data={"create": {"userId": DEFAULT_USER_ID, "balance": 0},- "update": {"balance": 0, "updatedAt": old_date},+ "update": {"balance": 0},},)@@ -119,112 +114,3 @@ async def test_block_credit_top_up(server: SpinTestServer):new_credit = await user_credit.get_credits(DEFAULT_USER_ID)assert new_credit == current_credit + 100--[email protected](loop_scope="session")-async def test_block_credit_reset(server: SpinTestServer):- """Test that BetaUserCredit provides monthly refills correctly."""- await disable_test_user_transactions()-- # Save original time_now function for restoration- original_time_now = user_credit.time_now-- try:- # Test month 1 behavior- month1 = datetime.now(timezone.utc).replace(month=1, day=1)- user_credit.time_now = lambda: month1-- # IMPORTANT: Set updatedAt to December of previous year to ensure it's- # in a different month than month1 (January). This fixes a timing bug- # where if the test runs in early February, 35 days ago would be January,- # matching the mocked month1 and preventing the refill from triggering.- dec_previous_year = month1.replace(year=month1.year - 1, month=12, day=15)- await UserBalance.prisma().update(- where={"userId": DEFAULT_USER_ID},- data={"updatedAt": dec_previous_year},- )-- # First call in month 1 should trigger refill- balance = await user_credit.get_credits(DEFAULT_USER_ID)- assert balance == REFILL_VALUE # Should get 1000 credits-- # Manually create a transaction with month 1 timestamp to establish history- await CreditTransaction.prisma().create(- data={- "userId": DEFAULT_USER_ID,- "amount": 100,- "type": CreditTransactionType.TOP_UP,- "runningBalance": 1100,- "isActive": True,- "createdAt": month1, # Set specific timestamp- }- )-- # Update user balance to match- await UserBalance.prisma().upsert(- where={"userId": DEFAULT_USER_ID},- data={- "create": {"userId": DEFAULT_USER_ID, "balance": 1100},- "update": {"balance": 1100},- },- )-- # Now test month 2 behavior- month2 = datetime.now(timezone.utc).replace(month=2, day=1)- user_credit.time_now = lambda: month2-- # In month 2, since balance (1100) > refill (1000), no refill should happen- month2_balance = await user_credit.get_credits(DEFAULT_USER_ID)- assert month2_balance == 1100 # Balance persists, no reset-- # Now test the refill behavior when balance is low- # Set balance below refill threshold and backdate updatedAt to month2 so- # the month3 refill check sees a different (month2 → month3) transition.- # Without the explicit updatedAt, Prisma sets it to real-world NOW which- # may share the same calendar month as the mocked month3, suppressing refill.- await UserBalance.prisma().update(- where={"userId": DEFAULT_USER_ID},- data={"balance": 400, "updatedAt": month2},- )-- # Create a month 2 transaction to update the last transaction time- await CreditTransaction.prisma().create(- data={- "userId": DEFAULT_USER_ID,- "amount": -700, # Spent 700 to get to 400- "type": CreditTransactionType.USAGE,- "runningBalance": 400,- "isActive": True,- "createdAt": month2,- }- )-- # Move to month 3- month3 = datetime.now(timezone.utc).replace(month=3, day=1)- user_credit.time_now = lambda: month3-- # Should get refilled since balance (400) < refill value (1000)- month3_balance = await user_credit.get_credits(DEFAULT_USER_ID)- assert month3_balance == REFILL_VALUE # Should be refilled to 1000-- # Verify the refill transaction was created- refill_tx = await CreditTransaction.prisma().find_first(- where={- "userId": DEFAULT_USER_ID,- "type": CreditTransactionType.GRANT,- "transactionKey": {"contains": "MONTHLY-CREDIT-TOP-UP"},- },- order={"createdAt": "desc"},- )- assert refill_tx is not None, "Monthly refill transaction should be created"- assert refill_tx.amount == 600, "Refill should be 600 (1000 - 400)"- finally:- # Restore original time_now function- user_credit.time_now = original_time_now--[email protected](loop_scope="session")-async def test_credit_refill(server: SpinTestServer):- await disable_test_user_transactions()- balance = await user_credit.get_credits(DEFAULT_USER_ID)- assert balance == REFILL_VALUEdiff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.pyindex 4dc774432e..a3007e036b 100644--- a/autogpt_platform/backend/backend/util/settings.py+++ b/autogpt_platform/backend/backend/util/settings.py@@ -128,14 +128,6 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):default=False,description="If user credit system is enabled or not",)- enable_beta_monthly_credit: bool = Field(- default=True,- description="If beta monthly credits accounting is enabled or not",- )- num_user_credits_refill: int = Field(- default=1500,- description="Number of credits to refill for each user",- )refund_credit_tolerance_threshold: int = Field(default=500,description="Maximum number of credits above the balance to be auto-approved.",