RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix: resolve asyncio correctness issues (fire-and-forget tasks, event loop nesting) (#14761)
wdeveloper164b36801b53ee
diff --git a/api/apps/restful_apis/agent_api.py b/api/apps/restful_apis/agent_api.pyindex d7641d43de..0803a2b11b 100644--- a/api/apps/restful_apis/agent_api.py+++ b/api/apps/restful_apis/agent_api.py@@ -25,6 +25,7 @@ import jsonimport loggingimport timefrom functools import partial, wraps+from typing import Setfrom api.utils.web_utils import CONTENT_TYPE_MAP, apply_safe_file_response_headersimport jwt@@ -63,6 +64,9 @@ from common.constants import RetCodefrom common.misc_utils import get_uuid, thread_pool_execfrom peewee import MySQLDatabase, PostgresqlDatabase+# Keeps strong references to fire-and-forget tasks so they are not GC'd before completion.+_background_tasks: Set[asyncio.Task] = set()+def _require_canvas_access_sync(func):@wraps(func)@@ -2079,7 +2083,10 @@ async def webhook(agent_id: str):except Exception:logging.exception("Failed to append webhook trace")- asyncio.create_task(background_run())+ task = asyncio.create_task(background_run())+ if isinstance(task, asyncio.Task):+ _background_tasks.add(task)+ task.add_done_callback(_background_tasks.discard)return respelse:async def sse():diff --git a/api/apps/restful_apis/tenant_api.py b/api/apps/restful_apis/tenant_api.pyindex 4d45337cb0..56f40444a5 100644--- a/api/apps/restful_apis/tenant_api.py+++ b/api/apps/restful_apis/tenant_api.py@@ -15,6 +15,7 @@#import asyncioimport logging+from typing import Setfrom api.apps import current_user, login_requiredfrom api.db import UserTenantRole@@ -33,6 +34,9 @@ from common.constants import RetCode, StatusEnumfrom common.misc_utils import get_uuidfrom common.time_utils import delta_seconds+# Keeps strong references to fire-and-forget tasks so they are not GC'd before completion.+_background_tasks: Set[asyncio.Task] = set()+@manager.route("/tenants/<tenant_id>/users", methods=["GET"]) # noqa: F821@login_required@@ -97,7 +101,16 @@ async def create(tenant_id):if user:user_name = user.nickname- asyncio.create_task(+ def _on_invite_email_done(done_task: asyncio.Task) -> None:+ _background_tasks.discard(done_task)+ try:+ done_task.result()+ except asyncio.CancelledError:+ logging.warning("Invite email task cancelled: tenant_id=%s to=%s", tenant_id, invite_user_email)+ except Exception:+ logging.exception("Invite email task failed: tenant_id=%s to=%s", tenant_id, invite_user_email)++ task = asyncio.create_task(send_invite_email(to_email=invite_user_email,invite_url=settings.MAIL_FRONTEND_URL,@@ -105,6 +118,9 @@ async def create(tenant_id):inviter=user_name or current_user.email,))+ if isinstance(task, asyncio.Task):+ _background_tasks.add(task)+ task.add_done_callback(_on_invite_email_done)except Exception as exc:logging.exception(f"Failed to send invite email to {invite_user_email}: {exc}")return get_json_result(diff --git a/rag/llm/chat_model.py b/rag/llm/chat_model.pyindex 7c1652ddb0..82a9e48f9b 100644--- a/rag/llm/chat_model.py+++ b/rag/llm/chat_model.py@@ -766,9 +766,9 @@ class LocalLLM(Base):from rag.svr.jina_server import Generationanswer = ""+ loop = asyncio.new_event_loop()try:res = self.client.stream_doc(on=endpoint, inputs=prompt, return_type=Generation)- loop = asyncio.get_event_loop()try:while True:answer = loop.run_until_complete(res.__anext__()).text@@ -777,6 +777,8 @@ class LocalLLM(Base):passexcept Exception as e:yield answer + "\n**ERROR**: " + str(e)+ finally:+ loop.close()yield num_tokens_from_string(answer)def chat(self, system, history, gen_conf=None, **kwargs):