From a3ed306cecfcb78c41c6515700b46e37dc2884fe Mon Sep 17 00:00:00 2001 From: WolveBrown <1244677795@qq.com> Date: Tue, 1 Dec 2026 16:58:36 +0800 Subject: [PATCH] perf(turns): prepare account directories once per recovery visit --- deeptutor/app/container.py | 2 +- deeptutor/multi_user/paths.py | 15 +++++++- tests/multi_user/test_turn_recovery_paths.py | 37 ++++++++++++++++++++ 3 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 tests/multi_user/test_turn_recovery_paths.py diff --git a/deeptutor/app/container.py b/deeptutor/app/container.py index e343aabec..c0c2e82b6 100644 --- a/deeptutor/app/container.py +++ b/deeptutor/app/container.py @@ -172,7 +172,7 @@ class ApplicationContainer: seen: set[str] = set() for user in self._local_users(): - with user_context(user): + with user_context(user, prepare_paths=True): try: activity = acquire_activity() except WorkspaceError: diff --git a/deeptutor/multi_user/paths.py b/deeptutor/multi_user/paths.py index de7936834..e49e3172b 100644 --- a/deeptutor/multi_user/paths.py +++ b/deeptutor/multi_user/paths.py @@ -17,6 +17,7 @@ in place by :func:`migrate_legacy_multi_user_tree`. from __future__ import annotations from contextlib import contextmanager +from contextvars import ContextVar import logging import os from pathlib import Path @@ -40,6 +41,9 @@ LEGACY_MULTI_USER_ROOT = PROJECT_ROOT / "multi-user" USER_SECRETS_DIRNAME = "user-secrets" _path_services: dict[str, PathService] = {} +_prepared_paths: ContextVar[tuple[UserScope, PathService] | None] = ContextVar( + "prepared_account_paths", default=None +) _legacy_migration_lock = threading.Lock() _legacy_migration_done = False @@ -156,6 +160,9 @@ def get_account_path_service() -> PathService: user = get_current_user_or_none() if user is None: return PathService.get_instance() + prepared = _prepared_paths.get() + if prepared is not None and prepared[0] is user.scope: + return prepared[1] if user.scope.kind == "user": ensure_scope_workspace(user.scope) return get_path_service_for_scope(user.scope) @@ -262,14 +269,20 @@ def current_owner_id() -> str: @contextmanager -def user_context(user: CurrentUser) -> Iterator[None]: +def user_context(user: CurrentUser, *, prepare_paths: bool = False) -> Iterator[None]: + """Bind an account, optionally preparing its directories once for a batch of operations.""" from deeptutor.services.workspace.context import account_workspace_context from .context import reset_current_user, set_current_user token = set_current_user(user) + paths_token = None try: with account_workspace_context(user.scope.root): + if prepare_paths: + paths_token = _prepared_paths.set((user.scope, get_account_path_service())) yield finally: + if paths_token is not None: + _prepared_paths.reset(paths_token) reset_current_user(token) diff --git a/tests/multi_user/test_turn_recovery_paths.py b/tests/multi_user/test_turn_recovery_paths.py new file mode 100644 index 000000000..338c478d2 --- /dev/null +++ b/tests/multi_user/test_turn_recovery_paths.py @@ -0,0 +1,37 @@ +from unittest.mock import patch + +import pytest + +from deeptutor.app.container import ApplicationContainer +from deeptutor.multi_user import paths + + +@pytest.mark.asyncio +async def test_recovery_prepares_each_account_once_per_pass(make_user, monkeypatch): + alice, bob = make_user("alice"), make_user("bob") + container = ApplicationContainer.build() + monkeypatch.setattr(container, "_local_users", lambda: [alice, bob]) + with patch.object( + paths, "ensure_scope_workspace", wraps=paths.ensure_scope_workspace + ) as ensure: + for _ in range(2): + ensure.reset_mock() + await container.recover_once() + assert [call.args[0] for call in ensure.call_args_list] == [alice.scope, bob.scope] + for user in (alice, bob): + assert paths.get_path_service_for_scope(user.scope).get_chat_history_db().is_file() + + +def test_prepared_paths_respect_nested_users_and_are_released_on_error(make_user): + alice, bob = make_user("alice"), make_user("bob") + with paths.user_context(alice): + with pytest.raises(RuntimeError, match="interrupted"): + with paths.user_context(alice, prepare_paths=True): + with paths.user_context(bob): + assert paths.get_account_path_service().workspace_root == bob.scope.root + assert paths.get_account_path_service().workspace_root == alice.scope.root + raise RuntimeError("interrupted") + # Outside the recovery visit, path lookup still repairs missing directories. + (alice.scope.root / "knowledge_bases").rmdir() + paths.get_account_path_service() + assert (alice.scope.root / "knowledge_bases").is_dir()