diff --git a/deeptutor/api/router_index.json b/deeptutor/api/router_index.json index 39c1815a5..b269b8dba 100644 --- a/deeptutor/api/router_index.json +++ b/deeptutor/api/router_index.json @@ -1,5 +1,5 @@ { - "fingerprint": "d6e7ac72e956df8656ebf42bf11dd2d559c8a5c6f36945028e68a15dccc9eab4", + "fingerprint": "0a09c99f6065a58d6de8a124e2ee054f83eff78a8337efac504037907cdd4e5a", "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 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