perf(turns): prepare account directories once per recovery visit

This commit is contained in:
WolveBrown
2026-12-01 16:58:36 +08:00
parent 8fe2567c65
commit a3ed306cec
3 changed files with 52 additions and 2 deletions

View File

@@ -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:

View File

@@ -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)

View File

@@ -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()