DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: Persistent File Library with API router (issue #1437) (#1446)
Srini Jagadeesh3006ec3671a1
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.pyindex 9b1760769..35a3bacdf 100644--- a/deeptutor/api/main.py+++ b/deeptutor/api/main.py@@ -529,6 +529,7 @@ from deeptutor.api.routers import (from deeptutor.api.routers import (tools as tools_router,)+from deeptutor.api.routers.file_library import router as file_library_router # noqa: E402from deeptutor.api.routers.multi_user import router as multi_user_router # noqa: E402# Auth router is public — login/logout/register/status require no token@@ -559,7 +560,6 @@ app.include_router(tags=["multi-user"],dependencies=_auth,)-app.include_router(question.router, prefix="/api/question", tags=["question"], dependencies=_auth)app.include_router(knowledge.router, prefix="/api", tags=["knowledge-bases"], dependencies=_auth)app.include_router(imports.router, prefix="/api/imports", tags=["imports"], dependencies=_auth)@@ -572,6 +572,12 @@ app.include_router(tags=["mastery-path"],dependencies=_auth,)+app.include_router(+ file_library_router,+ prefix="/files/library",+ tags=["library"],+ dependencies=_auth,+)# WebSocket handlers authenticate inside the connection before ``accept``.# Keep them off HTTP router dependencies: ``require_learning_surface`` takes a# Request, which FastAPI cannot construct for a WebSocket scope.diff --git a/deeptutor/api/routers/file_library.py b/deeptutor/api/routers/file_library.pynew file mode 100644index 000000000..bcd935f45--- /dev/null+++ b/deeptutor/api/routers/file_library.py@@ -0,0 +1,169 @@+"""HTTP endpoints for the Persistent File Library (issue #1437).++URL shape::++ GET /files/library/ — list files (newest first)+ POST /files/library/ — upload a file (multipart)+ GET /files/library/search — search by filename (query param: q)+ GET /files/library/{file_id} — get one entry+ GET /files/library/{file_id}/download — download the file+ DELETE /files/library/{file_id} — soft-delete a file+ POST /files/library/{file_id}/restore — restore a soft-deleted file++The library is scoped to the authenticated user (via ``require_auth``) so+each user sees only their own files.+"""++from __future__ import annotations++import logging+import mimetypes++from fastapi import (+ APIRouter,+ Depends,+ File,+ Form,+ HTTPException,+ Query,+)+from fastapi.responses import FileResponse++from deeptutor.api.routers.auth import require_auth+from deeptutor.services.auth import TokenPayload+from deeptutor.services.storage import file_library as _fl++logger = logging.getLogger(__name__)++router = APIRouter()+++def _get_store():+ """Resolve the store at call time so tests can monkey-patch ``_fl``."""+ return _fl.get_file_library_store()+++def _mime_type(filename: str) -> str:+ mt, _ = mimetypes.guess_type(filename)+ return mt or "application/octet-stream"+++# ── endpoints ──────────────────────────────────────────────────────────────++[email protected]("/", operation_id="library_list")+async def list_library_files(+ limit: int = Query(default=50, ge=1, le=200),+ offset: int = Query(default=0, ge=0),+ _auth: TokenPayload = Depends(require_auth),+) -> list[dict]:+ """List active library entries, newest first."""+ return await _get_store().list_files(limit=limit, offset=offset)++[email protected]("/", operation_id="library_add")+async def add_library_file(+ filename: str = File(..., description="Original filename"),+ mime_type: str = Form(""),+ file: bytes = File(..., description="Raw file bytes"),+ _auth: TokenPayload = Depends(require_auth),+) -> dict:+ """Add a file to the library.++ The request must be ``multipart/form-data`` with a ``file`` field containing+ the raw bytes. If a file with the same SHA-256 content hash already exists+ in the library, returns the existing entry (deduplication).+ """+ entry = await _get_store().add_file(+ data=file,+ filename=filename,+ mime_type=mime_type,+ )+ return entry++[email protected]("/search", operation_id="library_search")+async def search_library_files(+ q: str = Query(..., min_length=1, max_length=200),+ _auth: TokenPayload = Depends(require_auth),+) -> list[dict]:+ """Search library entries by filename (case-insensitive substring)."""+ return await _get_store().search_files(query=q)++[email protected]("/{file_id}", operation_id="library_get")+async def get_library_file(+ file_id: str,+ _auth: TokenPayload = Depends(require_auth),+) -> dict:+ """Get a single library entry by id (includes soft-deleted)."""+ entry = await _get_store().get_file(file_id)+ if entry is None:+ raise HTTPException(status_code=404, detail="File not found")+ return entry++[email protected]("/{file_id}/download", operation_id="library_download")+async def download_library_file(+ file_id: str,+ _auth: TokenPayload = Depends(require_auth),+) -> FileResponse:+ """Download a library file by id."""+ store = _get_store()+ entry = await store.get_file(file_id)+ if entry is None or entry.get("is_deleted"):+ raise HTTPException(status_code=404, detail="File not found")++ path = store.resolve_path(file_id)+ if path is None or not path.is_file():+ raise HTTPException(status_code=404, detail="File not found on disk")++ media_type = _mime_type(entry["filename"])+ return FileResponse(+ path,+ media_type=media_type,+ filename=entry["filename"],+ headers={+ "Cache-Control": "private, max-age=31536000, immutable",+ "X-Content-Type-Options": "nosniff",+ },+ )++[email protected]("/{file_id}/download", operation_id="library_download_head")+async def download_library_file_head(+ file_id: str,+ _auth: TokenPayload = Depends(require_auth),+) -> None:+ """Check whether a library file exists (HEAD only)."""+ store = _get_store()+ entry = await store.get_file(file_id)+ if entry is None or entry.get("is_deleted"):+ raise HTTPException(status_code=404, detail="File not found")+ path = store.resolve_path(file_id)+ if path is None or not path.is_file():+ raise HTTPException(status_code=404, detail="File not found on disk")++[email protected]("/{file_id}", operation_id="library_delete")+async def delete_library_file(+ file_id: str,+ _auth: TokenPayload = Depends(require_auth),+) -> dict:+ """Soft-delete a library file (sets is_deleted=1)."""+ deleted = await _get_store().delete_file(file_id)+ if not deleted:+ raise HTTPException(status_code=404, detail="File not found")+ return {"id": file_id, "deleted": True}++[email protected]("/{file_id}/restore", operation_id="library_restore")+async def restore_library_file(+ file_id: str,+ _auth: TokenPayload = Depends(require_auth),+) -> dict:+ """Restore a soft-deleted library file."""+ restored = await _get_store().restore_file(file_id)+ if not restored:+ raise HTTPException(status_code=404, detail="File not found")+ return {"id": file_id, "restored": True}diff --git a/deeptutor/services/storage/__init__.py b/deeptutor/services/storage/__init__.pyindex 17baaa7e0..dc8ce6de6 100644--- a/deeptutor/services/storage/__init__.py+++ b/deeptutor/services/storage/__init__.py@@ -1,18 +1,17 @@-"""Pluggable storage backends for chat-session artifacts.--Currently exposes only :mod:`attachment_store`, which persists user-uploaded-chat attachments to disk so the frontend can preview them after the original-base64 payload is dropped from the message record.-"""-from deeptutor.services.storage.attachment_store import (AttachmentStore,LocalDiskAttachmentStore,get_attachment_store,)+from deeptutor.services.storage.file_library import (+ FileLibraryStore,+ get_file_library_store,+)__all__ = ["AttachmentStore",+ "FileLibraryStore","LocalDiskAttachmentStore","get_attachment_store",+ "get_file_library_store",]diff --git a/deeptutor/services/storage/file_library.py b/deeptutor/services/storage/file_library.pynew file mode 100644index 000000000..0bae7a159--- /dev/null+++ b/deeptutor/services/storage/file_library.py@@ -0,0 +1,482 @@+"""Persistent File Library — reusable file storage across conversations (issue #1437).++Architecture+------------+Files are stored on disk under a library root (default:+``data/user/workspace/library/files``). The SQLite database tracks metadata:+id (UUID), sha256, filename, mime_type, size_bytes, library_path (relative+to root), created_at, updated_at, is_deleted, deleted_at.++Deduplication: content is identified by SHA-256. When ``add_file`` is called,+we compute the hash of the incoming bytes and check if an active (non-deleted)+entry with that hash already exists. If so, we return the existing entry+without storing a duplicate file on disk.++Soft delete: ``delete_file`` sets ``is_deleted=1`` and records+``deleted_at``. The file on disk is NOT removed — it can be restored.+``hard_delete_file`` first requires soft-delete, then permanently removes+both the database row and the file from disk.++Listing and search both return only non-deleted entries.+"""++from __future__ import annotations++import asyncio+from contextlib import contextmanager+import hashlib+import logging+import os+from pathlib import Path+import threading+import time+from typing import Any, Iterator+import uuid++from deeptutor.services.path_service import get_path_service++logger = logging.getLogger(__name__)++# Default subpath under the user root for library files+_LIBRARY_FILES_SUBDIR = ("workspace", "library", "files")+_LIBRARY_DB_SUBDIR = ("workspace", "library")+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++# ---------------------------------------------------------------------------+# Schema migrations+# ---------------------------------------------------------------------------++_SCHEMA_VERSION = 1++_MIGRATIONS: list[tuple[int, str]] = [+ # (version, sql)+]+++def _current_schema_version(conn) -> int:+ try:+ row = conn.execute("PRAGMA user_version").fetchone()+ return row[0] if row else 0+ except Exception:+ return 0+++def _run_migrations(conn) -> None:+ version = _current_schema_version(conn)+ for target_version, sql in _MIGRATIONS:+ if target_version <= version:+ continue+ conn.executescript(sql)+ conn.execute(f"PRAGMA user_version = {_SCHEMA_VERSION}")+++# ---------------------------------------------------------------------------+# FileLibraryStore+# ---------------------------------------------------------------------------+++class FileLibraryStore:+ """Persistent file library store.++ Stores file metadata in a SQLite database and files on disk under a+ configurable root directory.++ Parameters+ ----------+ db_path : Path+ Path to the SQLite database file.+ root : Path, optional+ Root directory for stored files. Defaults to+ ``data/user/workspace/library/files`` under the path service root.+ """++ def __init__(self, db_path: Path, root: Path | None = None) -> None:+ if root is None:+ root = get_path_service().get_user_root().joinpath(*_LIBRARY_FILES_SUBDIR).resolve()+ self._root = root+ self._db_path = db_path+ # Serializes the check-then-write-then-insert sequence in+ # _add_file_sync so concurrent uploads of identical content cannot+ # both miss the dedup lookup and create duplicate rows/files.+ self._add_lock = threading.Lock()+ self._init_db()++ # ------------------------------------------------------------------+ # Database helpers+ # ------------------------------------------------------------------++ @contextmanager+ def _connect(self) -> Iterator[None]:+ import sqlite3++ conn = sqlite3.connect(str(self._db_path), timeout=30.0)+ conn.row_factory = sqlite3.Row+ try:+ with conn:+ yield conn+ finally:+ conn.close()++ def _init_db(self) -> None:+ import sqlite3++ with self._connect() as conn:+ conn.execute(+ """+ CREATE TABLE IF NOT EXISTS library_files (+ id TEXT PRIMARY KEY,+ sha256 TEXT NOT NULL,+ filename TEXT NOT NULL,+ mime_type TEXT NOT NULL DEFAULT '',+ size_bytes INTEGER NOT NULL DEFAULT 0,+ library_path TEXT NOT NULL,+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL,+ is_deleted INTEGER NOT NULL DEFAULT 0,+ deleted_at REAL+ )+ """+ )+ # A plain index isn't enough to prevent duplicate active rows for+ # the same content — enforce it at the DB layer too (belt and+ # suspenders alongside the _add_lock in _add_file_sync, which is+ # the primary guard within a single process).+ conn.execute("DROP INDEX IF EXISTS idx_library_sha256")+ try:+ conn.execute(+ "CREATE UNIQUE INDEX IF NOT EXISTS idx_library_sha256_active "+ "ON library_files(sha256) WHERE is_deleted = 0"+ )+ except sqlite3.IntegrityError:+ logger.warning(+ "Could not create unique active-sha256 index on %s: "+ "duplicate active rows already exist",+ self._db_path,+ )+ conn.execute(+ "CREATE INDEX IF NOT EXISTS idx_library_is_deleted ON library_files(is_deleted)"+ )+ conn.commit()++ # ------------------------------------------------------------------+ # File I/O helpers+ # ------------------------------------------------------------------++ def _file_path(self, library_path: str) -> Path:+ """Return the absolute Path for a relative library_path."""+ return (self._root / library_path).resolve()++ def _ensure_root(self) -> None:+ self._root.mkdir(parents=True, exist_ok=True)++ def _write_file(self, library_path: str, data: bytes) -> None:+ target = self._file_path(library_path)+ self._ensure_root()+ target.parent.mkdir(parents=True, exist_ok=True)+ tmp = target.with_suffix(target.suffix + ".tmp")+ try:+ with tmp.open("wb") as fh:+ fh.write(data)+ os.replace(tmp, target)+ finally:+ if tmp.exists():+ try:+ tmp.unlink()+ except OSError:+ pass++ def _delete_file(self, library_path: str) -> None:+ target = self._file_path(library_path)+ if target.exists():+ try:+ target.unlink()+ except OSError as exc:+ logger.warning("failed to delete library file %s: %s", target, exc)+ # Try to remove now-empty parent dirs up to (but not including) root+ try:+ for parent in target.parents:+ if parent == self._root or not parent.is_relative_to(self._root):+ break+ if parent.is_dir() and not any(parent.iterdir()):+ parent.rmdir()+ except Exception:+ pass++ # ------------------------------------------------------------------+ # Public API — add / get / delete+ # ------------------------------------------------------------------++ async def add_file(+ self,+ *,+ data: bytes,+ filename: str,+ mime_type: str = "",+ ) -> dict[str, Any]:+ """Add a file to the library, deduplicating by content hash.++ If an active entry with the same SHA-256 already exists, returns that+ entry without storing a duplicate. Otherwise stores the file on disk+ and creates a new database entry.+ """+ return await asyncio.to_thread(self._add_file_sync, data, filename, mime_type)++ def _add_file_sync(+ self,+ data: bytes,+ filename: str,+ mime_type: str,+ ) -> dict[str, Any]:+ import sqlite3++ sha = _sha256(data)+ now = time.time()++ with self._add_lock, self._connect() as conn:+ # Check for existing active entry with same hash+ existing = conn.execute(+ "SELECT * FROM library_files WHERE sha256 = ? AND is_deleted = 0",+ (sha,),+ ).fetchone()+ if existing is not None:+ return self._row_to_entry(dict(existing))++ # Generate unique id and path+ file_id = str(uuid.uuid4())+ ext = Path(filename).suffix or ""+ library_path = f"{file_id}{ext}"++ # Ensure directory exists and write atomically+ self._ensure_root()+ self._write_file(library_path, data)++ try:+ conn.execute(+ """+ INSERT INTO library_files+ (id, sha256, filename, mime_type, size_bytes, library_path,+ created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (file_id, sha, filename, mime_type, len(data), library_path, now, now),+ )+ conn.commit()+ except sqlite3.IntegrityError:+ # Lost a race against the partial unique index — the+ # in-process _add_lock only serializes this process, so a+ # second worker process could still get here first. Discard+ # the file we just wrote and return the winning entry.+ self._delete_file(library_path)+ winner = conn.execute(+ "SELECT * FROM library_files WHERE sha256 = ? AND is_deleted = 0",+ (sha,),+ ).fetchone()+ if winner is not None:+ return self._row_to_entry(dict(winner))+ raise++ return {+ "id": file_id,+ "sha256": sha,+ "filename": filename,+ "mime_type": mime_type,+ "size_bytes": len(data),+ "library_path": library_path,+ "created_at": now,+ "updated_at": now,+ "is_deleted": False,+ "deleted_at": None,+ }++ async def get_file(self, file_id: str) -> dict[str, Any] | None:+ """Return the entry for *file_id*, or None if not found."""+ return await asyncio.to_thread(self._get_file_sync, file_id)++ def _get_file_sync(self, file_id: str) -> dict[str, Any] | None:+ with self._connect() as conn:+ row = conn.execute(+ "SELECT * FROM library_files WHERE id = ?",+ (file_id,),+ ).fetchone()+ if row is None:+ return None+ return self._row_to_entry(dict(row))++ async def delete_file(self, file_id: str) -> bool:+ """Soft-delete a library entry (sets is_deleted=1)."""+ return await asyncio.to_thread(self._delete_file_sync, file_id)++ def _delete_file_sync(self, file_id: str) -> bool:+ now = time.time()+ with self._connect() as conn:+ # Idempotent: return True whether the file was freshly deleted or already deleted.+ exists = conn.execute("SELECT 1 FROM library_files WHERE id = ?", (file_id,)).fetchone()+ if exists is None:+ return False+ conn.execute(+ "UPDATE library_files SET is_deleted = 1, deleted_at = ?, updated_at = ? WHERE id = ? AND is_deleted = 0",+ (now, now, file_id),+ )+ conn.commit()+ return True++ async def hard_delete_file(self, file_id: str) -> bool:+ """Permanently delete — only succeeds for already-soft-deleted entries."""+ return await asyncio.to_thread(self._hard_delete_file_sync, file_id)++ def _hard_delete_file_sync(self, file_id: str) -> bool:+ with self._connect() as conn:+ # Must be soft-deleted first+ row = conn.execute(+ "SELECT library_path FROM library_files WHERE id = ? AND is_deleted = 1",+ (file_id,),+ ).fetchone()+ if row is None:+ return False++ library_path = row["library_path"]++ # Delete from DB+ conn.execute("DELETE FROM library_files WHERE id = ?", (file_id,))+ conn.commit()++ # Delete file from disk (outside the with-block so we don't hold the conn)+ self._delete_file(library_path)+ return True++ async def restore_file(self, file_id: str) -> bool:+ """Restore a soft-deleted entry (clears is_deleted)."""+ return await asyncio.to_thread(self._restore_file_sync, file_id)++ def _restore_file_sync(self, file_id: str) -> bool:+ now = time.time()+ with self._connect() as conn:+ # Idempotent: return True if the file exists (whether already active or restored).+ exists = conn.execute("SELECT 1 FROM library_files WHERE id = ?", (file_id,)).fetchone()+ if exists is None:+ return False+ conn.execute(+ "UPDATE library_files SET is_deleted = 0, deleted_at = NULL, updated_at = ? WHERE id = ? AND is_deleted = 1",+ (now, file_id),+ )+ conn.commit()+ return True++ # ------------------------------------------------------------------+ # Listing and search+ # ------------------------------------------------------------------++ async def list_files(+ self,+ limit: int = 50,+ offset: int = 0,+ ) -> list[dict[str, Any]]:+ """List active library entries, newest first."""+ return await asyncio.to_thread(self._list_files_sync, limit, offset)++ def _list_files_sync(self, limit: int, offset: int) -> list[dict[str, Any]]:+ with self._connect() as conn:+ rows = conn.execute(+ """+ SELECT * FROM library_files+ WHERE is_deleted = 0+ ORDER BY created_at DESC, id DESC+ LIMIT ? OFFSET ?+ """,+ (limit, offset),+ ).fetchall()+ return [self._row_to_entry(dict(row)) for row in rows]++ async def search_files(self, query: str) -> list[dict[str, Any]]:+ """Search library entries by filename (case-insensitive substring)."""+ return await asyncio.to_thread(self._search_files_sync, query.strip())++ def _search_files_sync(self, query: str) -> list[dict[str, Any]]:+ if not query:+ return []+ pattern = f"%{query}%"+ with self._connect() as conn:+ rows = conn.execute(+ """+ SELECT * FROM library_files+ WHERE is_deleted = 0 AND filename LIKE ?+ ORDER BY created_at DESC, id DESC+ """,+ (pattern,),+ ).fetchall()+ return [self._row_to_entry(dict(row)) for row in rows]++ # ------------------------------------------------------------------+ # Path resolution+ # ------------------------------------------------------------------++ def resolve_path(self, file_id: str) -> Path | None:+ """Return the absolute Path to the stored file, or None if not found / deleted."""+ with self._connect() as conn:+ row = conn.execute(+ "SELECT library_path FROM library_files WHERE id = ? AND is_deleted = 0",+ (file_id,),+ ).fetchone()+ if row is None:+ return None+ path = self._file_path(row["library_path"])+ if not path.is_file():+ return None+ return path++ # ------------------------------------------------------------------+ # Helpers+ # ------------------------------------------------------------------++ @staticmethod+ def _row_to_entry(row: dict[str, Any]) -> dict[str, Any]:+ """Convert a sqlite3.Row dict to a clean entry dict."""+ return {+ "id": row["id"],+ "sha256": row["sha256"],+ "filename": row["filename"],+ "mime_type": row["mime_type"],+ "size_bytes": row["size_bytes"],+ "library_path": row["library_path"],+ "created_at": row["created_at"],+ "updated_at": row["updated_at"],+ "is_deleted": bool(row["is_deleted"]),+ "deleted_at": row["deleted_at"],+ }+++# ---------------------------------------------------------------------------+# Process-wide singleton+# ---------------------------------------------------------------------------++_instances: dict[str, FileLibraryStore] = {}+++def get_file_library_store() -> FileLibraryStore:+ """Return the FileLibraryStore singleton scoped to the current user.++ ``get_path_service().get_user_root()`` is resolved on every call (it is+ request-scoped via a contextvar — see ``deeptutor.multi_user.paths``) and+ the instance cache is keyed by that resolved root, mirroring+ ``get_attachment_store`` in ``attachment_store.py``. Caching under a+ constant key here would pin every user to whichever user's request+ happened to populate the cache first.+ """+ user_root = get_path_service().get_user_root()+ key = str(user_root)+ if key not in _instances:+ db_dir = user_root.joinpath(*_LIBRARY_DB_SUBDIR)+ db_dir.mkdir(parents=True, exist_ok=True)+ db_path = db_dir / "library.db"+ root = user_root.joinpath(*_LIBRARY_FILES_SUBDIR).resolve()+ _instances[key] = FileLibraryStore(db_path=db_path, root=root)+ return _instances[key]+++def reset_file_library_store() -> None:+ """Clear the process-wide singleton (for testing)."""+ _instances.clear()diff --git a/tests/api/test_file_library_router.py b/tests/api/test_file_library_router.pynew file mode 100644index 000000000..c0fb4c945--- /dev/null+++ b/tests/api/test_file_library_router.py@@ -0,0 +1,336 @@+"""Request-scoped regression coverage for the file library API (issue #1437)."""++from __future__ import annotations++from collections.abc import Callable+from pathlib import Path++from fastapi import FastAPI+from fastapi.testclient import TestClient+import pytest++from deeptutor.services.auth import TokenPayload+from deeptutor.services.storage.file_library import reset_file_library_store++LibraryAppFactory = Callable[..., tuple[TestClient, Path]]+++def library_app(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> LibraryAppFactory:+ """Build a standalone FastAPI app with the file_library router.++ Each test gets an isolated per-user workspace tree under ``tmp_path`` and+ a fresh FileLibraryStore singleton (reset on teardown, since the store+ cache is a process-wide module-level dict). Auth is disabled by default+ so most tests don't need JWT tokens; pass ``auth_enabled=True`` and+ ``tokens`` (mirroring ``tests/api/test_output_files.py``) to exercise+ per-user isolation.+ """+ from deeptutor.api.routers import auth as auth_router+ from deeptutor.api.routers import file_library+ from deeptutor.multi_user import paths as multi_user_paths++ admin_root = tmp_path / "data"+ users_root = admin_root / "users"+ monkeypatch.setattr(multi_user_paths, "ADMIN_WORKSPACE_ROOT", admin_root)+ monkeypatch.setattr(multi_user_paths, "USERS_ROOT", users_root)+ monkeypatch.setattr(multi_user_paths, "_path_services", {})++ def make_app(+ auth_enabled: bool = False,+ tokens: dict[str, TokenPayload | None] | None = None,+ ) -> tuple[TestClient, Path]:+ monkeypatch.setattr(auth_router, "AUTH_ENABLED", auth_enabled)+ if tokens is not None:+ monkeypatch.setattr(auth_router, "decode_token", lambda token: tokens.get(token))+ app = FastAPI()+ app.include_router(file_library.router, prefix="/files/library")+ return TestClient(app), admin_root++ yield make_app+ reset_file_library_store()+++# ── tests ─────────────────────────────────────────────────────────────────+++def test_add_file_returns_entry(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ response = client.post(+ "/files/library/",+ data={"filename": "report.txt", "mime_type": "text/plain"},+ files={"file": ("report.txt", b"Hello, world!", "text/plain")},+ )+ assert response.status_code == 200, response.json()+ data = response.json()+ assert data["filename"] == "report.txt"+ assert len(data["sha256"]) == 64+ assert data["size_bytes"] == 13+ assert data["is_deleted"] is False+ assert data["id"]+++def test_add_file_deduplicates_by_hash(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ payload = {"filename": "dup.txt", "mime_type": "text/plain"}+ files = {"file": ("dup.txt", b"same content", "text/plain")}+ r1 = client.post("/files/library/", data=payload, files=files)+ r2 = client.post("/files/library/", data=payload, files=files)+ assert r1.status_code == r2.status_code == 200+ assert r1.json()["id"] == r2.json()["id"]+++def test_add_file_different_content_gives_different_id(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r1 = client.post(+ "/files/library/",+ data={"filename": "a.txt", "mime_type": ""},+ files={"file": ("a.txt", b"content A", "")},+ )+ r2 = client.post(+ "/files/library/",+ data={"filename": "a.txt", "mime_type": ""},+ files={"file": ("a.txt", b"content B", "")},+ )+ assert r1.json()["id"] != r2.json()["id"]+++def test_list_files_returns_active(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ client.post(+ "/files/library/",+ data={"filename": "f1.txt", "mime_type": ""},+ files={"file": ("f1.txt", b"data1", "")},+ )+ client.post(+ "/files/library/",+ data={"filename": "f2.txt", "mime_type": ""},+ files={"file": ("f2.txt", b"data2", "")},+ )+ response = client.get("/files/library/")+ assert response.status_code == 200+ entries = response.json()+ assert len(entries) == 2+ assert {e["filename"] for e in entries} == {"f1.txt", "f2.txt"}+++def test_list_files_excludes_deleted(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "todelete.txt", "mime_type": ""},+ files={"file": ("todelete.txt", b"delete me", "")},+ )+ file_id = r.json()["id"]+ client.delete(f"/files/library/{file_id}")+ entries = client.get("/files/library/").json()+ assert file_id not in {e["id"] for e in entries}+++def test_list_files_respects_limit_offset(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ for i in range(5):+ client.post(+ "/files/library/",+ data={"filename": f"f{i}.txt", "mime_type": ""},+ files={"file": (f"f{i}.txt", f"d{i}".encode(), "")},+ )+ page1 = client.get("/files/library/?limit=2&offset=0").json()+ page2 = client.get("/files/library/?limit=2&offset=2").json()+ assert len(page1) == 2+ assert len(page2) == 2+ assert page1[0]["id"] != page2[0]["id"]+++def test_search_files_returns_matches(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ client.post(+ "/files/library/",+ data={"filename": "quarterly_report.pdf", "mime_type": ""},+ files={"file": ("quarterly_report.pdf", b"Q3 report", "")},+ )+ client.post(+ "/files/library/",+ data={"filename": "photo.jpg", "mime_type": ""},+ files={"file": ("photo.jpg", b"photo bytes", "")},+ )+ results = client.get("/files/library/search?q=report").json()+ assert len(results) == 1+ assert results[0]["filename"] == "quarterly_report.pdf"+++def test_search_files_no_match_returns_empty(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ client.post(+ "/files/library/",+ data={"filename": "alpha.txt", "mime_type": ""},+ files={"file": ("alpha.txt", b"alpha", "")},+ )+ results = client.get("/files/library/search?q=beta").json()+ assert results == []+++def test_search_files_excludes_deleted(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "to_search.txt", "mime_type": ""},+ files={"file": ("to_search.txt", b"search me", "")},+ )+ file_id = r.json()["id"]+ client.delete(f"/files/library/{file_id}")+ results = client.get("/files/library/search?q=search").json()+ assert all(e["id"] != file_id for e in results)+++def test_get_file_returns_entry(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "myfile.txt", "mime_type": "text/plain"},+ files={"file": ("myfile.txt", b"content", "text/plain")},+ )+ file_id = r.json()["id"]+ entry = client.get(f"/files/library/{file_id}").json()+ assert entry["id"] == file_id+ assert entry["filename"] == "myfile.txt"+++def test_get_file_nonexistent_returns_404(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ response = client.get("/files/library/nonexistent-id")+ assert response.status_code == 404+++def test_delete_file_soft_deletes(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "delme.txt", "mime_type": ""},+ files={"file": ("delme.txt", b"delete", "")},+ )+ file_id = r.json()["id"]+ response = client.delete(f"/files/library/{file_id}")+ assert response.status_code == 200+ assert response.json()["deleted"] is True+ entry = client.get(f"/files/library/{file_id}").json()+ assert entry["is_deleted"] is True+++def test_delete_file_nonexistent_returns_404(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ response = client.delete("/files/library/nonexistent-id")+ assert response.status_code == 404+++def test_delete_file_idempotent(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "dupdel.txt", "mime_type": ""},+ files={"file": ("dupdel.txt", b"dup", "")},+ )+ file_id = r.json()["id"]+ r1 = client.delete(f"/files/library/{file_id}")+ r2 = client.delete(f"/files/library/{file_id}")+ assert r1.status_code == r2.status_code == 200+++def test_restore_file_clears_deleted_flag(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "restoreme.txt", "mime_type": ""},+ files={"file": ("restoreme.txt", b"restore", "")},+ )+ file_id = r.json()["id"]+ client.delete(f"/files/library/{file_id}")+ response = client.post(f"/files/library/{file_id}/restore")+ assert response.status_code == 200+ assert response.json()["restored"] is True+ entry = client.get(f"/files/library/{file_id}").json()+ assert entry["is_deleted"] is False+++def test_restore_file_nonexistent_returns_404(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ response = client.post("/files/library/nonexistent-id/restore")+ assert response.status_code == 404+++def test_restore_file_idempotent(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "active.txt", "mime_type": ""},+ files={"file": ("active.txt", b"active", "")},+ )+ file_id = r.json()["id"]+ r1 = client.post(f"/files/library/{file_id}/restore")+ r2 = client.post(f"/files/library/{file_id}/restore")+ assert r1.status_code == r2.status_code == 200+++def test_download_library_file(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ content = b"downloadable content"+ r = client.post(+ "/files/library/",+ data={"filename": "download.txt", "mime_type": "text/plain"},+ files={"file": ("download.txt", content, "text/plain")},+ )+ file_id = r.json()["id"]+ response = client.get(f"/files/library/{file_id}/download")+ assert response.status_code == 200+ assert response.content == content+++def test_download_deleted_file_returns_404(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ r = client.post(+ "/files/library/",+ data={"filename": "del.txt", "mime_type": ""},+ files={"file": ("del.txt", b"del", "")},+ )+ file_id = r.json()["id"]+ client.delete(f"/files/library/{file_id}")+ response = client.get(f"/files/library/{file_id}/download")+ assert response.status_code == 404+++def test_download_nonexistent_returns_404(library_app: LibraryAppFactory) -> None:+ client, _ = library_app()+ response = client.get("/files/library/nonexistent-id/download")+ assert response.status_code == 404+++def test_upload_and_list_are_isolated_between_users(library_app: LibraryAppFactory) -> None:+ """Regression test: the FileLibraryStore singleton used to be keyed by a+ constant ("default") instead of the resolved per-user root, so the+ second authenticated user to hit any endpoint transparently shared the+ first user's library (list/get/download all leaked across accounts).+ """+ tokens = {+ "alice-token": TokenPayload(username="alice", role="user", user_id="u_alice"),+ "bob-token": TokenPayload(username="bob", role="user", user_id="u_bob"),+ }+ client, _ = library_app(auth_enabled=True, tokens=tokens)++ with client:+ client.cookies.set("dt_token", "alice-token")+ upload = client.post(+ "/files/library/",+ data={"filename": "alice-only.txt", "mime_type": "text/plain"},+ files={"file": ("alice-only.txt", b"alice's secret file", "text/plain")},+ )+ assert upload.status_code == 200+ alice_file_id = upload.json()["id"]++ client.cookies.set("dt_token", "bob-token")+ bob_list = client.get("/files/library/")+ bob_get = client.get(f"/files/library/{alice_file_id}")+ bob_download = client.get(f"/files/library/{alice_file_id}/download")++ assert bob_list.json() == []+ assert bob_get.status_code == 404+ assert bob_download.status_code == 404diff --git a/tests/services/storage/test_file_library.py b/tests/services/storage/test_file_library.pynew file mode 100644index 000000000..e625e1363--- /dev/null+++ b/tests/services/storage/test_file_library.py@@ -0,0 +1,374 @@+"""Tests for the Persistent File Library feature (issue #1437)."""++from __future__ import annotations++import asyncio+import hashlib+from pathlib import Path+import tempfile++import pytest++from deeptutor.services.storage.file_library import (+ FileLibraryStore,+ get_file_library_store,+ reset_file_library_store,+)++# ---------------------------------------------------------------------------+# Fixtures+# ---------------------------------------------------------------------------+++def tmp_db_path(tmp_path: Path) -> Path:+ return tmp_path / "file_library.db"+++def store(tmp_db_path: Path) -> FileLibraryStore:+ reset_file_library_store()+ return FileLibraryStore(db_path=tmp_db_path)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _content(data: bytes) -> tuple[str, str]:+ """Return (sha256, base_name) for the data."""+ return _sha256(data), "file.pdf"+++# ---------------------------------------------------------------------------+# add_file+# ---------------------------------------------------------------------------+++def test_add_file_returns_entry(store: FileLibraryStore) -> None:+ """add_file must return a complete library entry."""+ data = b"Hello, World!"+ entry = asyncio.run(store.add_file(data=data, filename="hello.txt", mime_type="text/plain"))+ assert entry["id"] is not None+ assert entry["sha256"] == _sha256(data)+ assert entry["filename"] == "hello.txt"+ assert entry["mime_type"] == "text/plain"+ assert entry["size_bytes"] == len(data)+ assert entry["is_deleted"] is False+++def test_add_file_persists_to_disk(store: FileLibraryStore) -> None:+ """The file bytes must be stored on disk under the library root."""+ data = b"Test content"+ entry = asyncio.run(store.add_file(data=data, filename="test.txt", mime_type="text/plain"))+ resolved = store.resolve_path(entry["id"])+ assert resolved is not None+ assert resolved.read_bytes() == data+++def test_add_file_deduplicates_by_hash(store: FileLibraryStore) -> None:+ """Uploading identical content must return the existing entry, not create a duplicate."""+ data = b"Duplicate content"+ e1 = asyncio.run(+ store.add_file(data=data, filename="original.pdf", mime_type="application/pdf")+ )+ e2 = asyncio.run(store.add_file(data=data, filename="copy.pdf", mime_type="application/pdf"))+ assert e1["id"] == e2["id"]+ assert e1["sha256"] == e2["sha256"]+++def test_add_file_different_content_gives_different_hash(store: FileLibraryStore) -> None:+ """Different byte content must produce different hashes."""+ e1 = asyncio.run(store.add_file(data=b"Content A", filename="a.txt", mime_type="text/plain"))+ e2 = asyncio.run(store.add_file(data=b"Content B", filename="b.txt", mime_type="text/plain"))+ assert e1["sha256"] != e2["sha256"]+ assert e1["id"] != e2["id"]+++def test_add_file_concurrent_uploads_of_same_content_do_not_duplicate(+ store: FileLibraryStore,+) -> None:+ """Regression test: concurrent uploads of identical content used to all+ miss the dedup SELECT before any of them committed its INSERT (a TOCTOU+ race across the OS threads ``asyncio.to_thread`` dispatches to), each+ creating its own duplicate row and file on disk instead of deduplicating.+ """+ import threading++ data = b"same content uploaded from multiple tabs at once"+ n_threads = 8+ barrier = threading.Barrier(n_threads)+ results: list[dict] = [None] * n_threads # type: ignore[list-item]++ def upload(i: int) -> None:+ barrier.wait()+ results[i] = store._add_file_sync(data, f"upload-{i}.txt", "text/plain")++ threads = [threading.Thread(target=upload, args=(i,)) for i in range(n_threads)]+ for t in threads:+ t.start()+ for t in threads:+ t.join()++ ids = {r["id"] for r in results}+ assert len(ids) == 1, f"expected a single deduplicated entry, got {len(ids)}: {ids}"++ entries = asyncio.run(store.list_files())+ assert len(entries) == 1+++# ---------------------------------------------------------------------------+# list_files+# ---------------------------------------------------------------------------+++def test_list_files_returns_all_active(store: FileLibraryStore) -> None:+ """list_files must return every non-deleted entry, newest first."""+ # Track IDs and creation times of files we create to verify relative ordering.+ own_ids = []+ own_created_ats = []+ for i in range(5):+ e = asyncio.run(+ store.add_file(+ data=f"Content {i}".encode(), filename=f"file{i}.txt", mime_type="text/plain"+ )+ )+ own_ids.append(e["id"])+ own_created_ats.append(e["created_at"])+ entries = asyncio.run(store.list_files())+ # Among the entries we created, verify newest-first ordering using timestamps.+ own_results = [e for e in entries if e["id"] in own_ids]+ assert len(own_results) == 5+ result_created_ats = [e["created_at"] for e in own_results]+ # Sort by created_at DESC to get the expected order.+ expected_order = [eid for _, eid in sorted(zip(own_created_ats, own_ids), reverse=True)]+ assert [e["id"] for e in own_results] == expected_order+++def test_list_files_respects_limit_offset(store: FileLibraryStore) -> None:+ """limit and offset must paginate the result list."""+ for i in range(5):+ asyncio.run(+ store.add_file(data=f"Data {i}".encode(), filename=f"f{i}.txt", mime_type="text/plain")+ )+ page1 = asyncio.run(store.list_files(limit=2, offset=0))+ page2 = asyncio.run(store.list_files(limit=2, offset=2))+ assert len(page1) == 2+ assert len(page2) == 2+ assert page1[0]["id"] != page2[0]["id"]+++def test_list_files_excludes_deleted(store: FileLibraryStore) -> None:+ """Soft-deleted entries must not appear in list_files."""+ e1 = asyncio.run(store.add_file(data=b"Keep me", filename="keep.txt", mime_type="text/plain"))+ e2 = asyncio.run(+ store.add_file(data=b"Delete me", filename="delete.txt", mime_type="text/plain")+ )+ asyncio.run(store.delete_file(e2["id"]))+ entries = asyncio.run(store.list_files())+ ids = [e["id"] for e in entries]+ assert e1["id"] in ids+ assert e2["id"] not in ids+++# ---------------------------------------------------------------------------+# search_files+# ---------------------------------------------------------------------------+++def test_search_files_by_filename(store: FileLibraryStore) -> None:+ """search_files must match on filename."""+ asyncio.run(+ store.add_file(+ data=b"Content", filename="project_proposal.pdf", mime_type="application/pdf"+ )+ )+ asyncio.run(store.add_file(data=b"Content", filename="notes.txt", mime_type="text/plain"))+ results = asyncio.run(store.search_files("project"))+ assert len(results) == 1+ assert results[0]["filename"] == "project_proposal.pdf"+++def test_search_files_no_match_returns_empty(store: FileLibraryStore) -> None:+ """A query that matches nothing must return an empty list."""+ asyncio.run(store.add_file(data=b"Content", filename="other.txt", mime_type="text/plain"))+ results = asyncio.run(store.search_files("nonexistent_term_xyz"))+ assert results == []+++def test_search_files_excludes_deleted(store: FileLibraryStore) -> None:+ """Deleted entries must not appear in search results."""+ e = asyncio.run(+ store.add_file(data=b"Important document", filename="doc.pdf", mime_type="application/pdf")+ )+ asyncio.run(store.delete_file(e["id"]))+ results = asyncio.run(store.search_files("Important"))+ assert results == []+++# ---------------------------------------------------------------------------+# delete_file (soft delete)+# ---------------------------------------------------------------------------+++def test_delete_file_soft_deletes(store: FileLibraryStore) -> None:+ """delete_file must set is_deleted=True without removing the row."""+ e = asyncio.run(+ store.add_file(data=b"Content", filename="todelete.txt", mime_type="text/plain")+ )+ result = asyncio.run(store.delete_file(e["id"]))+ assert result is True+ entry = asyncio.run(store.get_file(e["id"]))+ assert entry is not None+ assert entry["is_deleted"] is True+++def test_delete_file_idempotent(store: FileLibraryStore) -> None:+ """Deleting an already-deleted entry must return True without error."""+ e = asyncio.run(store.add_file(data=b"Content", filename="file.txt", mime_type="text/plain"))+ asyncio.run(store.delete_file(e["id"]))+ result = asyncio.run(store.delete_file(e["id"]))+ assert result is True+++def test_delete_file_nonexistent_returns_false(store: FileLibraryStore) -> None:+ """Deleting a non-existent ID must return False."""+ result = asyncio.run(store.delete_file("nonexistent_id"))+ assert result is False+++# ---------------------------------------------------------------------------+# hard_delete_file+# ---------------------------------------------------------------------------+++def test_hard_delete_file_removes_row(store: FileLibraryStore) -> None:+ """hard_delete_file must physically remove the row from the database."""+ e = asyncio.run(+ store.add_file(data=b"Content", filename="permanent.txt", mime_type="text/plain")+ )+ asyncio.run(store.delete_file(e["id"])) # must be soft-deleted first+ result = asyncio.run(store.hard_delete_file(e["id"]))+ assert result is True+ entry = asyncio.run(store.get_file(e["id"]))+ assert entry is None+++def test_hard_delete_file_without_soft_delete_fails(store: FileLibraryStore) -> None:+ """hard_delete_file must refuse to delete a non-deleted entry."""+ e = asyncio.run(store.add_file(data=b"Content", filename="file.txt", mime_type="text/plain"))+ result = asyncio.run(store.hard_delete_file(e["id"]))+ assert result is False+++# ---------------------------------------------------------------------------+# restore_file+# ---------------------------------------------------------------------------+++def test_restore_file_clears_deleted_flag(store: FileLibraryStore) -> None:+ """restore_file must set is_deleted=False."""+ e = asyncio.run(+ store.add_file(data=b"Content", filename="restorable.txt", mime_type="text/plain")+ )+ asyncio.run(store.delete_file(e["id"]))+ result = asyncio.run(store.restore_file(e["id"]))+ assert result is True+ entry = asyncio.run(store.get_file(e["id"]))+ assert entry is not None+ assert entry["is_deleted"] is False+++def test_restore_file_idempotent(store: FileLibraryStore) -> None:+ """Restoring an active entry must return True without error."""+ e = asyncio.run(store.add_file(data=b"Content", filename="active.txt", mime_type="text/plain"))+ result = asyncio.run(store.restore_file(e["id"]))+ assert result is True+++# ---------------------------------------------------------------------------+# get_file+# ---------------------------------------------------------------------------+++def test_get_file_returns_entry(store: FileLibraryStore) -> None:+ """get_file must return the full entry dict for an existing ID."""+ e = asyncio.run(store.add_file(data=b"Content", filename="getme.txt", mime_type="text/plain"))+ fetched = asyncio.run(store.get_file(e["id"]))+ assert fetched is not None+ assert fetched["id"] == e["id"]+ assert fetched["filename"] == "getme.txt"+++def test_get_file_deleted_returns_entry_with_flag(store: FileLibraryStore) -> None:+ """get_file must still return the entry (with is_deleted=True) for soft-deleted files."""+ e = asyncio.run(store.add_file(data=b"Content", filename="deleted.txt", mime_type="text/plain"))+ asyncio.run(store.delete_file(e["id"]))+ fetched = asyncio.run(store.get_file(e["id"]))+ assert fetched is not None+ assert fetched["is_deleted"] is True+++def test_get_file_nonexistent_returns_none(store: FileLibraryStore) -> None:+ """get_file must return None for a non-existent ID."""+ result = asyncio.run(store.get_file("does_not_exist"))+ assert result is None+++# ---------------------------------------------------------------------------+# resolve_path+# ---------------------------------------------------------------------------+++def test_resolve_path_returns_existing_file(store: FileLibraryStore) -> None:+ """resolve_path must return the Path to the stored file for a valid ID."""+ e = asyncio.run(+ store.add_file(data=b"PDF content here", filename="doc.pdf", mime_type="application/pdf")+ )+ path = store.resolve_path(e["id"])+ assert path is not None+ assert path.exists()+ assert path.read_bytes() == b"PDF content here"+++def test_resolve_path_deleted_returns_none(store: FileLibraryStore) -> None:+ """resolve_path must return None for a soft-deleted entry."""+ e = asyncio.run(+ store.add_file(data=b"Content", filename="deleted_file.txt", mime_type="text/plain")+ )+ asyncio.run(store.delete_file(e["id"]))+ path = store.resolve_path(e["id"])+ assert path is None+++def test_resolve_path_nonexistent_returns_none(store: FileLibraryStore) -> None:+ """resolve_path must return None for a non-existent ID."""+ path = store.resolve_path("no_such_id")+ assert path is None+++# ---------------------------------------------------------------------------+# Singleton / reset+# ---------------------------------------------------------------------------+++def test_get_file_library_store_returns_singleton(store: FileLibraryStore) -> None:+ """get_file_library_store must return the process-wide singleton."""+ reset_file_library_store()+ s1 = get_file_library_store()+ s2 = get_file_library_store()+ assert s1 is s2+++def test_reset_clears_singleton() -> None:+ """reset_file_library_store must clear the singleton so a new instance is created."""+ reset_file_library_store()+ s1 = get_file_library_store()+ reset_file_library_store()+ s2 = get_file_library_store()+ assert s1 is not s2