diff --git a/src/sentry/integrations/utils/issue_summary_for_alerts.py b/src/sentry/integrations/utils/issue_summary_for_alerts.py index 190c7d5a384762..fada419ab218bb 100644 --- a/src/sentry/integrations/utils/issue_summary_for_alerts.py +++ b/src/sentry/integrations/utils/issue_summary_for_alerts.py @@ -3,6 +3,7 @@ from typing import Any import sentry_sdk +from django.db import close_old_connections from sentry import features, options from sentry.issues.grouptype import GroupCategory @@ -15,6 +16,19 @@ logger = logging.getLogger(__name__) +def _get_issue_summary_with_cleanup( + group: Group, source: SeerAutomationSource +) -> tuple[dict[str, Any], int]: + """ + Wrapper for get_issue_summary that ensures database connections are properly closed. + This is needed when running in a thread to prevent connection leaks. + """ + try: + return get_issue_summary(group, source=source) + finally: + close_old_connections() + + def fetch_issue_summary(group: Group) -> dict[str, Any] | None: """ Try to fetch an issue summary with a timeout of 5 seconds. @@ -52,7 +66,7 @@ def fetch_issue_summary(group: Group) -> dict[str, Any] | None: with sentry_sdk.start_span(op="ai_summary.fetch_issue_summary_for_alert"): with concurrent.futures.ThreadPoolExecutor() as executor: future = executor.submit( - get_issue_summary, group, source=SeerAutomationSource.ALERT + _get_issue_summary_with_cleanup, group, SeerAutomationSource.ALERT ) summary_result, status_code = future.result(timeout=timeout)