From d39b470d91997887f2daa2b3b3bda7ba22d480a2 Mon Sep 17 00:00:00 2001 From: denghui996 <63841220+denghui996@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:07:05 +0800 Subject: [PATCH 1/2] fix: resolve a KB's storage scope past unreadable workspace registrations workspace_id_for_kb_base_dir() walks every registered workspace to find the one that owns a KB directory, and it runs on every upload, folder sync and reindex. A registration whose folder no longer exists (archived leftovers, a directory the user moved) raises WorkspaceError on entry, which aborted the whole lookup and dropped the storage scope from the background task. Because WorkspaceError is a ValueError, the upload/sync routes then answered 404 'Knowledge base not found' for a KB that exists, the background task was never registered (the call sits in add_task's argument list), and the KB kept the progress entry written just before it, so the UI showed an endless 'scanning' state with no error on disk. - skip registrations that cannot be entered instead of aborting the scan - resolve the scope before copying files or marking the KB queued, so a failure cannot leave a task-less progress entry behind - surface WorkspaceError as 409 with its real message instead of a 404 Fixes #2524 --- deeptutor/api/routers/knowledge.py | 22 +++++++-- deeptutor/services/workspace/knowledge.py | 19 ++++++-- .../workspace/test_kb_scope_lookup.py | 48 +++++++++++++++++++ 3 files changed, 82 insertions(+), 7 deletions(-) create mode 100644 tests/services/workspace/test_kb_scope_lookup.py diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py index 53af734ba..98267dd38 100644 --- a/deeptutor/api/routers/knowledge.py +++ b/deeptutor/api/routers/knowledge.py @@ -100,6 +100,7 @@ from deeptutor.services.rag.pipelines.ima.config import ( from deeptutor.services.rag.visual_assets import VisualAssetStore from deeptutor.services.web_source.scheduler import get_web_source_sync_scheduler from deeptutor.services.workspace.knowledge import workspace_id_for_kb_base_dir +from deeptutor.services.workspace.models import WorkspaceError from deeptutor.utils.document_extractor import ( MAX_EXTRACTED_CHARS_PER_DOC, DocumentExtractionError, @@ -3431,6 +3432,11 @@ async def upload_files( """ try: manager, kb_name, kb_base_dir = _writable_kb(kb_name) + # Resolve the storage scope before copying anything or marking the KB + # queued: this lookup walks the workspace catalog and may fail, and a + # failure here must not leave a "queued" progress entry whose + # background task was never registered. + storage_workspace_id = workspace_id_for_kb_base_dir(kb_base_dir) requested_provider = None if rag_provider is not None and str(rag_provider).strip(): requested_provider = _validate_registered_provider(rag_provider) @@ -3506,7 +3512,7 @@ async def upload_files( task_id=task_id, rag_provider=kb_provider, owner=get_current_user(), - storage_workspace_id=workspace_id_for_kb_base_dir(kb_base_dir), + storage_workspace_id=storage_workspace_id, ) return { @@ -3516,6 +3522,9 @@ async def upload_files( } except (HTTPException, AccessError): raise + except WorkspaceError as exc: + # A workspace problem is not a missing knowledge base; keep the reason. + raise HTTPException(status_code=409, detail=str(exc)) from exc except ValueError: raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found") except Exception as e: @@ -4131,6 +4140,8 @@ async def reindex_knowledge_base( """ try: manager, kb_name, kb_base_dir = _writable_kb(kb_name) + # See upload_files(): resolve the destination scope before queueing. + storage_workspace_id = workspace_id_for_kb_base_dir(kb_base_dir) kb_entry = _load_kb_entry_or_404(manager, kb_name) _assert_not_connected_kb(kb_name, kb_entry) force_reindex = str(kb_entry.get("status") or "").lower() == "error" @@ -4273,7 +4284,7 @@ async def reindex_knowledge_base( signature_hash=signature_hash, indexing_snapshot=indexing_snapshot, owner=get_current_user(), - storage_workspace_id=workspace_id_for_kb_base_dir(kb_base_dir), + storage_workspace_id=storage_workspace_id, **( {"embedding_selection": embedding_selection, "embedding_config": embedding_config} if embedding_selection @@ -4807,6 +4818,9 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background """ try: manager, kb_name, kb_base_dir = _writable_kb(kb_name) + # See upload_files(): resolve the destination scope before queueing so a + # failing lookup cannot leave a task-less "starting" progress entry. + storage_workspace_id = workspace_id_for_kb_base_dir(kb_base_dir) kb_entry = _load_kb_entry_or_404(manager, kb_name) _assert_kb_writable_or_409(kb_name, kb_entry) kb_provider = _validate_registered_provider( @@ -4871,7 +4885,7 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background folder_id=folder_id, # Pass folder_id to update state on success folder_root=folder_path, # Preserve each file's path relative to this root owner=get_current_user(), - storage_workspace_id=workspace_id_for_kb_base_dir(kb_base_dir), + storage_workspace_id=storage_workspace_id, ) return SyncFolderResponse( @@ -4885,6 +4899,8 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background ) except (HTTPException, AccessError): raise + except WorkspaceError as exc: + raise HTTPException(status_code=409, detail=str(exc)) from exc except ValueError: raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found") except Exception as e: diff --git a/deeptutor/services/workspace/knowledge.py b/deeptutor/services/workspace/knowledge.py index b623c8fe5..b786f0ba7 100644 --- a/deeptutor/services/workspace/knowledge.py +++ b/deeptutor/services/workspace/knowledge.py @@ -22,11 +22,19 @@ def qualified_kb_id(name: str, workspace_id: str = "") -> str: def workspace_id_for_kb_base_dir(base_dir: str | Path) -> str | None: - """Find the owned storage scope for a KB directory used by a background job.""" + """Find the owned storage scope for a KB directory used by a background job. + + A registration can outlive its folder (archived leftovers, a directory the + user moved or deleted). Entering such a scope raises ``WorkspaceError``; + skip it and keep scanning, because this lookup runs on every upload/sync + and one dead registration must not break the write path of the workspaces + that are healthy. + """ from deeptutor.multi_user.paths import get_account_path_service from deeptutor.services.path_service import get_path_service from deeptutor.services.workspace import get_content_workspace_service from deeptutor.services.workspace.context import workspace_context + from deeptutor.services.workspace.models import WorkspaceError root = Path(base_dir).resolve() if root == get_account_path_service().get_knowledge_bases_root().resolve(): @@ -34,9 +42,12 @@ def workspace_id_for_kb_base_dir(base_dir: str | Path) -> str | None: for row in get_content_workspace_service()._catalog(): if row.get("kind") != "workspace": continue - with workspace_context(row["workspace_id"]): - if root == get_path_service().get_knowledge_bases_root().resolve(): - return str(row["workspace_id"]) + try: + with workspace_context(row["workspace_id"]): + if root == get_path_service().get_knowledge_bases_root().resolve(): + return str(row["workspace_id"]) + except WorkspaceError: + continue return None diff --git a/tests/services/workspace/test_kb_scope_lookup.py b/tests/services/workspace/test_kb_scope_lookup.py new file mode 100644 index 000000000..114339e22 --- /dev/null +++ b/tests/services/workspace/test_kb_scope_lookup.py @@ -0,0 +1,48 @@ +"""A dead workspace registration must not break KB scope lookup. + +`workspace_id_for_kb_base_dir()` runs on every upload/sync/reindex to stamp the +destination scope onto the background task. It walks every registered +workspace, and a registration whose folder no longer exists raises on entry — +which used to abort the whole lookup (surfacing as a bogus +``404 Knowledge base '' not found`` on an otherwise healthy workspace). +""" + +from __future__ import annotations + +from pathlib import Path + +from deeptutor.multi_user.paths import get_account_path_service +from deeptutor.services.path_service import get_path_service +from deeptutor.services.workspace.context import workspace_context +from deeptutor.services.workspace.knowledge import workspace_id_for_kb_base_dir +from tests.services.workspace.test_data_scope import account as account + + +def test_lookup_skips_a_registration_whose_folder_is_gone(account): + stale = account.create_workspace("Leftover") + Path(stale["path"]).rename(Path(stale["path"]).with_name("leftover-moved")) + account.update_workspace(stale["workspace_id"], archived=True) + + target = account.create_workspace("Calculus")["workspace_id"] + with workspace_context(target): + kb_root = get_path_service().get_knowledge_bases_root() + + assert workspace_id_for_kb_base_dir(kb_root) == target + + +def test_account_knowledge_base_root_needs_no_workspace_scan(account): + account.create_workspace("Leftover") + + with workspace_context(""): + account_kb_root = get_account_path_service().get_knowledge_bases_root() + + assert workspace_id_for_kb_base_dir(account_kb_root) == "" + + +def test_lookup_returns_none_for_an_unowned_directory(account, tmp_path): + account.create_workspace("Calculus") + + stray = tmp_path / "not-a-workspace-kb" + stray.mkdir() + + assert workspace_id_for_kb_base_dir(stray) is None From 0902053a12b14835006c6ebd2a62b0bb65ca1b26 Mon Sep 17 00:00:00 2001 From: denghui996 <63841220+denghui996@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:07:08 +0800 Subject: [PATCH 2/2] fix: do not hold the workspace activity lease across a progress stream The authenticated-request dependency takes a shared lease on workspace-activity.sqlite3 for the whole ASGI call, and the middleware releases it when that call returns. A streaming response only returns when the stream ends, so an indexing-progress SSE held the lease for as long as its tab stayed open -- and when the indexed task never starts (see the preceding commit) that is indefinitely. Every exclusive workspace operation (KB move, registration update, data migration) then answered 'Workspace data is busy' until the backend was restarted, because acquire_activity() uses timeout=0 and a leaked shared lock never expires. Task-board events and the calendar stream were already excluded for this reason; the knowledge-base task progress stream reads only in-memory task state and is equally safe to exclude. A failing task therefore no longer locks the workspace it cannot even reach. Regenerate the router index for the changed router sources. Fixes #2525 --- deeptutor/api/router_index.json | 2 +- deeptutor/api/routers/auth.py | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/deeptutor/api/router_index.json b/deeptutor/api/router_index.json index 5f3dd90c9..62085ac77 100644 --- a/deeptutor/api/router_index.json +++ b/deeptutor/api/router_index.json @@ -1,5 +1,5 @@ { - "fingerprint": "b3ff4a2963d642a226ba3b8fd034f616c878ec27cdb071e720e82674dabd3b75", + "fingerprint": "483005de3a065c12992b5c8f28bdd0f23d20628a1347506adabb7898b219a18f", "routers": { "deeptutor.api.routers.auth:router": [ { diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py index ca4851b25..8f9c902e7 100644 --- a/deeptutor/api/routers/auth.py +++ b/deeptutor/api/routers/auth.py @@ -560,10 +560,23 @@ def _install_request_workspace(request) -> None: raise WorkspaceError("Restore this workspace before changing its data.") # Management/migration requests acquire their own exclusive lease. task_board_request = path == "/api/task-board" or path.startswith("/api/task-board/") - if getattr(request, "method", None) is not None and ( - not management - or (task_board_request and path != "/api/task-board/events") - or (path.startswith("/api/calendar/") and path != "/api/calendar/stream") + # A progress stream can outlive the work it reports: a queued indexing + # task that never starts keeps the SSE open indefinitely. Holding the + # request's shared lease for the stream's whole lifetime then answers + # "Workspace data is busy" to every exclusive workspace operation + # (move, registration update, migration) until the tab is closed, so + # this read-only observer opts out. + progress_stream = path.startswith("/api/knowledge-bases/tasks/") and path.endswith( + "/stream" + ) + if ( + getattr(request, "method", None) is not None + and not progress_stream + and ( + not management + or (task_board_request and path != "/api/task-board/events") + or (path.startswith("/api/calendar/") and path != "/api/calendar/stream") + ) ): from deeptutor.services.workspace.activity import acquire_activity