Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions autogpt_platform/backend/backend/data/credit.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,6 +910,13 @@ async def _top_up_credits(
metadata=successful_transaction,
)

# Clear insufficient funds notification flags so user can receive
# Discord alerts again if they run out of funds in the future.
# Lazy import to avoid circular dependency with executor.manager
from backend.executor.manager import clear_insufficient_funds_notifications

clear_insufficient_funds_notifications(user_id)
Copy link

Copilot AI Dec 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The synchronous function clear_insufficient_funds_notifications is being called from async context without using asyncio.to_thread or similar mechanisms. This could block the event loop when performing Redis operations (scan_iter and delete). Consider making this function async and using get_redis_async() instead, or wrap the call in asyncio.to_thread() to avoid blocking the event loop during I/O operations.

Copilot uses AI. Check for mistakes.

async def top_up_intent(self, user_id: str, amount: int) -> str:
if amount < 500 or amount % 100 != 0:
raise ValueError(
Expand Down Expand Up @@ -1008,6 +1015,13 @@ async def fulfill_checkout(
metadata=SafeJson(checkout_session),
)

# Clear insufficient funds notification flags so user can receive
# Discord alerts again if they run out of funds in the future.
# Lazy import to avoid circular dependency with executor.manager
from backend.executor.manager import clear_insufficient_funds_notifications

clear_insufficient_funds_notifications(credit_transaction.userId)
Copy link

Copilot AI Dec 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The synchronous function clear_insufficient_funds_notifications is being called from async context without using asyncio.to_thread or similar mechanisms. This could block the event loop when performing Redis operations (scan_iter and delete). Consider making this function async and using get_redis_async() instead, or wrap the call in asyncio.to_thread() to avoid blocking the event loop during I/O operations.

Copilot uses AI. Check for mistakes.

async def get_credits(self, user_id: str) -> int:
balance, _ = await self._get_credits(user_id)
return balance
Expand Down
63 changes: 63 additions & 0 deletions autogpt_platform/backend/backend/executor/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,40 @@
"Ratio of active graph runs to max graph workers",
)

# Redis key prefix for tracking insufficient funds Discord notifications.
# We only send one notification per user per agent until they top up credits.
INSUFFICIENT_FUNDS_NOTIFIED_PREFIX = "insufficient_funds_discord_notified"
# TTL for the notification flag (30 days) - acts as a fallback cleanup
INSUFFICIENT_FUNDS_NOTIFIED_TTL_SECONDS = 30 * 24 * 60 * 60


def clear_insufficient_funds_notifications(user_id: str) -> int:
"""
Clear all insufficient funds notification flags for a user.

This should be called when a user tops up their credits, allowing
Discord notifications to be sent again if they run out of funds.

Args:
user_id: The user ID to clear notifications for.

Returns:
The number of keys that were deleted.
"""
try:
redis_client = redis.get_redis()
pattern = f"{INSUFFICIENT_FUNDS_NOTIFIED_PREFIX}:{user_id}:*"
keys = list(redis_client.scan_iter(match=pattern))
if keys:
return redis_client.delete(*keys)
return 0
except Exception as e:
logger.warning(
f"Failed to clear insufficient funds notification flags for user "
f"{user_id}: {e}"
)
return 0


# Thread-local storage for ExecutionProcessor instances
_tls = threading.local()
Expand Down Expand Up @@ -1261,12 +1295,40 @@ def _handle_insufficient_funds_notif(
graph_id: str,
e: InsufficientBalanceError,
):
# Check if we've already sent a notification for this user+agent combo.
# We only send one notification per user per agent until they top up credits.
redis_key = f"{INSUFFICIENT_FUNDS_NOTIFIED_PREFIX}:{user_id}:{graph_id}"
try:
redis_client = redis.get_redis()
# SET NX returns True only if the key was newly set (didn't exist)
is_new_notification = redis_client.set(
redis_key,
"1",
nx=True,
ex=INSUFFICIENT_FUNDS_NOTIFIED_TTL_SECONDS,
)
if not is_new_notification:
# Already notified for this user+agent, skip all notifications
logger.debug(
f"Skipping duplicate insufficient funds notification for "
f"user={user_id}, graph={graph_id}"
)
return
except Exception as redis_error:
# If Redis fails, log and continue to send the notification
# (better to occasionally duplicate than to never notify)
logger.warning(
f"Failed to check/set insufficient funds notification flag in Redis: "
f"{redis_error}"
)

shortfall = abs(e.amount) - e.balance
metadata = db_client.get_graph_metadata(graph_id)
base_url = (
settings.config.frontend_base_url or settings.config.platform_base_url
)

# Queue user email notification
queue_notification(
NotificationEventModel(
user_id=user_id,
Expand All @@ -1280,6 +1342,7 @@ def _handle_insufficient_funds_notif(
)
)

# Send Discord system alert
try:
user_email = db_client.get_user_email_by_id(user_id)

Expand Down
Loading
Loading