From 0b16c4da2cf74d43e9c521f4e2d75339d15cade1 Mon Sep 17 00:00:00 2001 From: abhi1992002 Date: Tue, 17 Feb 2026 10:36:37 +0530 Subject: [PATCH] refactor(api): optimize folder ancestry check in database - Updated the `is_descendant_of` function to fetch all user folders in a single query, reducing database round-trips and improving performance. - Replaced the previous method of querying each folder's parent ID with an in-memory parent map, enhancing efficiency in checking folder ancestry. - These changes streamline the folder validation process and improve overall responsiveness of the API. --- .../backend/api/features/library/db.py | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py index 4c0de561c5..ff1ae82c08 100644 --- a/autogpt_platform/backend/backend/api/features/library/db.py +++ b/autogpt_platform/backend/backend/api/features/library/db.py @@ -1124,6 +1124,9 @@ async def is_descendant_of( """ Check if folder_id is a descendant of potential_ancestor_id. + Fetches all user folders in a single query and walks the parent chain + in memory to avoid N database round-trips. + Args: folder_id: The ID of the folder to check. potential_ancestor_id: The ID of the potential ancestor. @@ -1132,22 +1135,16 @@ async def is_descendant_of( Returns: True if folder_id is a descendant of potential_ancestor_id. """ - current_id: str | None = folder_id + all_folders = await prisma.models.LibraryFolder.prisma().find_many( + where={"userId": user_id, "isDeleted": False}, + ) + parent_map = {f.id: f.parentId for f in all_folders} + current_id: str | None = folder_id while current_id: if current_id == potential_ancestor_id: return True - - folder = await prisma.models.LibraryFolder.prisma().find_first( - where={ - "id": current_id, - "userId": user_id, - "isDeleted": False, - } - ) - if not folder or not folder.parentId: - break - current_id = folder.parentId + current_id = parent_map.get(current_id) return False