Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

91.1 KB
Raw Blame
"""
Zotero sync service.

Imports items from a Zotero library/collection into the LDR document library
and keeps them in sync. Items become :class:`Document` rows (with extracted
text, optional encrypted PDF blob, and RAG auto-indexing) inside a dedicated
:class:`Collection`, exactly like uploads/research downloads — so they are
searchable during research with no extra plumbing.

Sync algorithm (per collection), using cheap version maps:

1. Ask Zotero for ``{itemKey: version}`` of current top-level items.
2. Map keys not present anymore  -> remove the local document.
3. Map keys that are new, version-bumped, or whose local document went
   missing -> (re)fetch full data, download the best PDF (or import
   metadata-only), and upsert the document + mapping row.
4. Persist the library version as the new high-water mark.

Known limitations (v1):

- With MULTIPLE synced collections, an item moved from collection A to B is
  removed by A's sync before B has imported it: the document is deleted and
  re-created under a new id once B next syncs successfully (briefly absent
  from the library if B's sync fails first). Whole-library (single-target)
  configs are unaffected.
- Toggling ``import_items_without_pdf`` (or the tag filter) does not apply
  to already-skipped items on SCHEDULED syncs — run a manual "Sync now"
  (which re-examines skipped items), or wait for the items to change in
  Zotero.
"""

import hashlib
import os
import re
import threading
import uuid
from dataclasses import dataclass, field
from datetime import date, datetime, UTC
from pathlib import Path
from typing import Dict, List, Optional, Tuple

from loguru import logger

from ...constants import FILE_PATH_TEXT_ONLY
from ...config.paths import get_library_directory
from ...database.library_init import get_source_type_id
from ...database.models.library import (
    Collection,
    Document,
    DocumentBlob,
    DocumentChunk,
    DocumentCollection,
    DocumentStatus,
)
from ...database.models.zotero import ZoteroItemMap, ZoteroSyncState
from ...database.session_context import get_user_db_session, safe_rollback
from ...security import (
    sanitize_filename,
    scrub_error,
    UnsafeFilenameError,
)
from ...settings.manager import SettingsManager
from ...settings.exceptions import SettingsValueError
from ...utilities.type_utils import to_bool
from ..deletion.utils.cascade_helper import CascadeHelper
from ..services.pdf_storage_manager import (
    DEFAULT_MAX_PDF_SIZE_MB,
    PDFStorageManager,
    resolve_pdf_storage_mode,
)
from ..utils import apply_user_subdir, ensure_in_collection
from .client import (
    ZOTERO_KEY_REJECTED_MESSAGE,
    ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
    ZOTERO_RESOURCE_NOT_FOUND_MESSAGE,
    ZoteroClient,
    ZoteroError,
    ZoteroItem,
    ZoteroTransientError,
)


# Configuration guidance. Like the three in ``client.py`` these are constant,
# author-written text — they are not derived from an exception at all; the two
# below are ordinary return values of ``_resolve_library_id``.
ZOTERO_API_KEY_REQUIRED_MESSAGE = (
    "A Zotero API key is required (unless using the local API)."
)
ZOTERO_GROUP_ID_REQUIRED_MESSAGE = (
    "Zotero group libraries need the numeric group ID — use the group "
    "picker, or the number in the group's URL on zotero.org."
)
ZOTERO_USER_ID_UNRESOLVED_MESSAGE = (
    "Could not determine the Zotero userID from the API key — check the key, "
    "or enter the numeric userID shown at zotero.org/settings/keys."
)

# The set of messages that may be shown to a browser. It is written as a
# dict mapping each message to ITSELF so ``client_safe_zotero_message`` can
# look an exception's text up and hand back THIS module's constant rather
# than the string it was looked up with — no exception-derived value crosses
# the HTTP boundary. A miss — every message that interpolates an HTTP status,
# a retry count, an item count or an exception class name, and anything a
# future raise site invents — yields nothing and the caller substitutes a
# generic message.
#
# Not all six are reachable as lookup KEYS, and the difference matters when
# reading this file. Five of them do travel inside an exception:
# ``ZOTERO_KEY_REJECTED_MESSAGE`` / ``ZOTERO_RESOURCE_NOT_FOUND_MESSAGE`` /
# ``ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE`` are raised by ``client._request``,
# and ``ZOTERO_GROUP_ID_REQUIRED_MESSAGE`` /
# ``ZOTERO_USER_ID_UNRESOLVED_MESSAGE`` are returned by
# ``_resolve_library_id`` and re-raised as ``ZoteroError`` by
# ``list_collections`` / ``list_groups``. ``ZOTERO_API_KEY_REQUIRED_MESSAGE``
# never is: ``test_connection`` returns it as a dict value, which the router
# forwards via ``result.get("error")`` without a lookup. It is listed here
# because this collection doubles as the inventory of client-visible Zotero
# strings, not because anything looks it up.
CLIENT_SAFE_ZOTERO_MESSAGES = {
    message: message
    for message in (
        ZOTERO_KEY_REJECTED_MESSAGE,
        ZOTERO_RESOURCE_NOT_FOUND_MESSAGE,
        ZOTERO_LIBRARY_ID_NOT_NUMERIC_MESSAGE,
        ZOTERO_API_KEY_REQUIRED_MESSAGE,
        ZOTERO_GROUP_ID_REQUIRED_MESSAGE,
        ZOTERO_USER_ID_UNRESOLVED_MESSAGE,
    )
}


def client_safe_zotero_message(exc: BaseException, fallback: str) -> str:
    """Return the curated text for ``exc``, or ``fallback``.

    The return value is always either a module constant from
    ``CLIENT_SAFE_ZOTERO_MESSAGES`` or the caller's own literal — never the
    exception's string — so this is a boundary, not a scrubber.
    """
    try:
        text = str(exc)
    except Exception:
        return fallback
    return CLIENT_SAFE_ZOTERO_MESSAGES.get(text) or fallback


@dataclass
class ZoteroConfig:
    """Snapshot of the user's Zotero settings."""

    # On by default — inert until an API key is configured; the toggle is an
    # opt-out kill-switch, not a required opt-in step.
    enabled: bool = True
    # nosemgrep: semgrep.rules.hardcoded-secret-detection, reason: Empty API-key default; not a credential
    api_key: str = ""
    library_type: str = "user"
    library_id: str = ""
    collection_keys: List[str] = field(default_factory=list)
    import_tags: List[str] = field(default_factory=list)
    # Off by default: metadata/abstract-only documents carry no full text,
    # which is what LDR's research actually needs.
    import_items_without_pdf: bool = False
    import_annotations: bool = False
    # Text-only by default: the extracted text is what research uses, and it
    # keeps the encrypted DB small. "database" additionally keeps the PDF.
    pdf_storage_mode: str = "none"
    auto_sync_enabled: bool = False
    sync_interval_minutes: int = 360
    use_local_api: bool = False

    @property
    def is_configured(self) -> bool:
        # Local API mode needs no API key (it talks to the running desktop
        # Zotero on localhost); the web API needs one. A library ID is only
        # required for GROUP libraries: a personal library is identified by
        # the key itself (resolved via /keys/current), and the local API
        # addresses the current desktop user as user 0.
        has_auth = self.use_local_api or bool(self.api_key)
        needs_id = self.library_type == "group"
        return bool(
            self.enabled and has_auth and (self.library_id or not needs_id)
        )

    @property
    def targets(self) -> List[str]:
        """Collection keys to sync; ``[""]`` means the whole library."""
        return self.collection_keys or [""]


# Per-user sync locks. A single non-blocking lock per username serialises ALL
# sync entry points (the manual "Sync now" daemon thread AND the scheduled
# auto-sync job), so two concurrent runs can't write the same per-user
# SQLCipher DB and race on the ZoteroItemMap unique constraint.
_user_sync_locks: dict[str, threading.Lock] = {}
_user_sync_locks_guard = threading.Lock()

# Live progress of the currently running sync, per user — read by the status
# endpoint while a sync runs so the UI can show a real progress bar.
# In-memory on purpose: progress is transient, and both sync entry points
# (manual daemon thread, scheduler job) run in this process.
_user_sync_progress: dict[str, Dict] = {}
_user_sync_progress_guard = threading.Lock()


def _get_user_sync_lock(username: str) -> threading.Lock:
    with _user_sync_locks_guard:
        lock = _user_sync_locks.get(username)
        if lock is None:
            lock = threading.Lock()
            _user_sync_locks[username] = lock
        return lock


class ZoteroSyncService:
    """Service that imports / syncs Zotero items into the library."""

    def __init__(
        self,
        username: str,
        password: Optional[str] = None,  # gitleaks:allow
    ):
        self.username = username
        self.password = password  # gitleaks:allow
        # Cached /keys/current lookup ("" = resolution failed) so one service
        # instance resolves the key's userID at most once.
        self._resolved_user_id: Optional[str] = None

    # -- settings ----------------------------------------------------------

    def get_config(self) -> ZoteroConfig:
        """Read the user's Zotero settings from their encrypted database."""
        with get_user_db_session(self.username, self.password) as session:
            sm = SettingsManager(session)
            raw_keys = sm.get_setting("zotero.collection_keys", "") or ""
            collection_keys = [
                k.strip() for k in str(raw_keys).split(",") if k.strip()
            ]
            raw_tags = sm.get_setting("zotero.import_tags", "") or ""
            import_tags = [
                t.strip() for t in str(raw_tags).split(",") if t.strip()
            ]
            try:
                interval = int(
                    sm.get_setting("zotero.sync_interval_minutes", 360) or 360
                )
            except SettingsValueError:
                raise
            except (TypeError, ValueError):
                interval = 360
            return ZoteroConfig(
                enabled=sm.get_bool_setting("zotero.enabled", True),
                api_key=str(sm.get_setting("zotero.api_key", "") or "").strip(),
                library_type=str(
                    sm.get_setting("zotero.library_type", "user") or "user"
                ).strip(),
                library_id=str(
                    sm.get_setting("zotero.library_id", "") or ""
                ).strip(),
                collection_keys=collection_keys,
                import_tags=import_tags,
                import_items_without_pdf=sm.get_bool_setting(
                    "zotero.import_items_without_pdf", False
                ),
                import_annotations=sm.get_bool_setting(
                    "zotero.import_annotations", False
                ),
                pdf_storage_mode=str(
                    sm.get_setting("zotero.pdf_storage_mode", "none") or "none"
                ).strip(),
                auto_sync_enabled=sm.get_bool_setting(
                    "zotero.auto_sync_enabled", False
                ),
                sync_interval_minutes=interval,
                use_local_api=sm.get_bool_setting(
                    "zotero.use_local_api", False
                ),
            )

    def _make_client(self, cfg: ZoteroConfig) -> ZoteroClient:
        return ZoteroClient(
            api_key=cfg.api_key,
            library_type=cfg.library_type,
            library_id=cfg.library_id,
            local=cfg.use_local_api,
        )

    def _resolve_library_id(self, cfg: ZoteroConfig) -> Optional[str]:
        """Normalize ``cfg.library_id`` in place; returns an error or None.

        A personal library needs no manually entered ID: the API key
        identifies its owner, so an empty or non-numeric value (a username,
        say) is resolved to the numeric userID via ``/keys/current``. Local
        mode addresses the desktop's current user as ``0``. Only group
        libraries must carry an explicit numeric group ID.

        Called by the operational entry points (test/list/sync) — NOT by
        :meth:`get_config`, which must stay network-free (the config
        endpoint reads it on every page load).
        """
        lid = cfg.library_id
        if cfg.library_type == "group":
            if not lid.isdigit():
                return ZOTERO_GROUP_ID_REQUIRED_MESSAGE
            return None
        if cfg.use_local_api:
            if not lid:
                # The local API addresses the desktop's current user as 0.
                cfg.library_id = "0"
            return None
        if lid.isdigit():
            return None
        # Personal library with an empty or non-numeric ID (e.g. a username):
        # the key knows its owner — resolve and use the real userID.
        if self._resolved_user_id is None:
            try:
                probe = ZoteroClient(
                    api_key=cfg.api_key, library_type="user", library_id="0"
                )
                with probe:
                    user_id = probe.get_current_key_info().get("userID")
                self._resolved_user_id = str(user_id) if user_id else ""
            except ZoteroError:
                logger.debug(
                    "Zotero: could not resolve the key's userID via "
                    "/keys/current",
                    exc_info=True,
                )
                self._resolved_user_id = ""
        if self._resolved_user_id:
            if lid:
                logger.info(
                    f"Zotero: library ID {lid!r} is not numeric — using the "
                    f"API key's userID {self._resolved_user_id} instead"
                )
            cfg.library_id = self._resolved_user_id
            return None
        return ZOTERO_USER_ID_UNRESOLVED_MESSAGE

    def _library_root(self) -> Path:
        # Per-user library root (issue #5521), mirroring the DownloadService
        # write path: the base storage directory from this user's settings,
        # narrowed to the per-user subdirectory via ``apply_user_subdir``
        # (shared mode is an operator-gated env opt-in). Today
        # ``zotero.pdf_storage_mode`` only offers ``database`` (encrypted) and
        # ``none`` (text-only), so this root is a formality for the DB-blob
        # path — but building the PDFStorageManager on the per-user root (and
        # routing the mode through ``resolve_pdf_storage_mode`` at the call
        # site) keeps this write path from ever escaping per-user isolation or
        # the unencrypted-filesystem gate if the mode set ever changes.
        with get_user_db_session(self.username, self.password) as session:
            sm = SettingsManager(session)
            storage_path = sm.get_setting(
                "research_library.storage_path", str(get_library_directory())
            )
            shared_library = sm.get_setting(
                "research_library.shared_library", False
            )
        base = Path(os.path.expandvars(storage_path)).expanduser().resolve()
        return apply_user_subdir(base, self.username, shared_library)

    # -- public operations -------------------------------------------------

    def test_connection(self) -> Dict:
        """Validate credentials. Returns ``{success, library_version, ...}``."""
        cfg = self.get_config()
        if not cfg.use_local_api and not cfg.api_key:
            return {
                "success": False,
                "error": ZOTERO_API_KEY_REQUIRED_MESSAGE,
            }
        resolve_error = self._resolve_library_id(cfg)
        if resolve_error:
            return {"success": False, "error": resolve_error}
        try:
            with self._make_client(cfg) as client:
                version = client.test_connection()
                collections = client.get_collections()
            return {
                "success": True,
                "library_version": version,
                "collection_count": len(collections),
            }
        except ZoteroError as exc:
            # The exception's TEXT is safe to log here, unlike in the
            # bare-Exception arms elsewhere: every `ZoteroError` in this
            # package is constructed from author-written text whose only
            # interpolations are an HTTP status, a retry count, an item
            # count, `_MAX_PAGES` or `type(exc).__name__` — never an upstream
            # response body, a filesystem path or the API key. Logging only
            # the class name would leave an operator unable to tell "HTTP
            # 400, the library ID looks like a username" from "HTTP 404" once
            # the client-facing message has fallen back to the generic one.
            #
            # It still goes through `scrub_error` and into a local rather
            # than being interpolated straight from `exc`: the scrub is a
            # no-op on this text, but it is the repo-wide catch-site idiom
            # and `.pre-commit-hooks/check-sensitive-logging.py` rejects an
            # except-variable inside a `logger.warning` outright, so nobody
            # has to re-argue per-site safety.
            #
            # Still no traceback: `cfg` is a local of this frame and its
            # dataclass repr renders `api_key`, which loguru's `diagnose`
            # would print for every frame in an attached traceback.
            safe_msg = scrub_error(exc, cfg.api_key, self.password)
            logger.warning(
                f"Zotero: connection test failed "
                f"({type(exc).__name__}): {safe_msg}"
            )
            return {
                "success": False,
                "error": client_safe_zotero_message(
                    exc,
                    "Zotero connection failed. Check the configured API key "
                    "and library settings.",
                ),
            }

    def list_collections(self) -> List[Dict]:
        """List Zotero collections (for the UI picker)."""
        cfg = self.get_config()
        resolve_error = self._resolve_library_id(cfg)
        if resolve_error:
            raise ZoteroError(resolve_error)
        with self._make_client(cfg) as client:
            return client.get_collections()

    def list_groups(self) -> List[Dict]:
        """List the groups the configured API key can access (UI picker)."""
        cfg = self.get_config()
        resolve_error = self._resolve_library_id(cfg)
        if resolve_error:
            raise ZoteroError(resolve_error)
        with self._make_client(cfg) as client:
            return client.get_groups()

    @classmethod
    def is_user_syncing(cls, username: str) -> bool:
        """True if a sync is currently in progress for this user."""
        lock = _user_sync_locks.get(username)
        return bool(lock and lock.locked())

    @classmethod
    def get_sync_progress(cls, username: str) -> Optional[Dict]:
        """Live progress of the user's running sync, or None when idle."""
        if not cls.is_user_syncing(username):
            return None
        with _user_sync_progress_guard:
            progress = _user_sync_progress.get(username)
            return dict(progress) if progress else None

    def _set_progress(self, **fields) -> None:
        with _user_sync_progress_guard:
            _user_sync_progress.setdefault(self.username, {}).update(fields)

    def _clear_progress(self) -> None:
        with _user_sync_progress_guard:
            _user_sync_progress.pop(self.username, None)

    def sync_all(self, reprocess_skipped: bool = False) -> Dict:
        """Sync every configured collection (or the whole library).

        Serialised per user: if a sync (manual or scheduled) is already
        running for this user, returns immediately rather than starting a
        second concurrent writer against the same encrypted DB.

        ``reprocess_skipped`` re-examines items previously recorded without
        a document (skipped strays, no-PDF items, tag-filter misses) even
        though their Zotero version is unchanged. Manual "Sync now" sets it
        so settings changes and newly importable item shapes apply without
        waiting for the item to change in Zotero; scheduled syncs keep the
        cheap version-diff.
        """
        cfg = self.get_config()
        if not cfg.is_configured:
            return {
                "success": False,
                "error": "Zotero is not enabled/configured.",
            }
        # Resolve BEFORE the per-collection loop so the sync-state rows are
        # always keyed on the real numeric library ID, whatever the setting
        # holds (empty for personal libraries, or even a pasted username).
        resolve_error = self._resolve_library_id(cfg)
        if resolve_error:
            return {"success": False, "error": resolve_error}

        lock = _get_user_sync_lock(self.username)
        if not lock.acquire(blocking=False):
            logger.info(
                f"Zotero: a sync is already running for {self.username}; "
                "skipping this run"
            )
            return {
                "success": True,
                "already_running": True,
                "imported": 0,
                "updated": 0,
                "removed": 0,
                "skipped": 0,
                "errors": 0,
                "collections": [],
            }

        totals = {
            "imported": 0,
            "updated": 0,
            "removed": 0,
            "skipped": 0,
            "errors": 0,
            "collections": [],
        }
        try:
            self._set_progress(phase="starting", done=0, total=None)
            with self._make_client(cfg) as client:
                for collection_key in cfg.targets:
                    stats = self._sync_one(
                        client,
                        cfg,
                        collection_key,
                        reprocess_skipped=reprocess_skipped,
                    )
                    totals["imported"] += stats.get("imported", 0)
                    totals["updated"] += stats.get("updated", 0)
                    totals["removed"] += stats.get("removed", 0)
                    totals["skipped"] += stats.get("skipped", 0)
                    totals["errors"] += stats.get("errors", 0)
                    totals["collections"].append(stats)
        finally:
            self._clear_progress()
            lock.release()
        totals["success"] = all(
            c.get("status") != "failed" for c in totals["collections"]
        )
        return totals

    def get_status(self) -> List[Dict]:
        """Return the stored sync state for all configured collections."""
        with get_user_db_session(self.username, self.password) as session:
            rows = session.query(ZoteroSyncState).all()
            return [
                {
                    "library_type": r.library_type,
                    "library_id": r.library_id,
                    "collection_key": r.collection_key or None,
                    "ldr_collection_id": r.ldr_collection_id,
                    "last_version": r.last_version,
                    "last_status": r.last_status,
                    "last_error": r.last_error,
                    "item_count": r.item_count,
                    "last_run_counts": None
                    if r.last_imported_count is None
                    else {
                        "imported": r.last_imported_count,
                        "updated": r.last_updated_count,
                        "removed": r.last_removed_count,
                        "skipped": r.last_skipped_count,
                        "errors": r.last_error_count,
                    },
                    "last_synced_at": r.last_synced_at.isoformat()
                    if r.last_synced_at
                    else None,
                }
                for r in rows
            ]

    # -- per-collection sync ----------------------------------------------

    def _sync_one(
        self,
        client: ZoteroClient,
        cfg: ZoteroConfig,
        collection_key: str,
        reprocess_skipped: bool = False,
    ) -> Dict:
        """Sync a single collection (``""`` = whole library)."""
        stats = {
            "collection_key": collection_key or None,
            "imported": 0,
            "updated": 0,
            "removed": 0,
            # Deliberate skips (tag filter, no-PDF import disabled).
            "skipped": 0,
            # Contained per-item failures (rolled back, retried next sync).
            # Kept separate from "skipped" so they can be SURFACED: a sync
            # that completes with errors must not look identical to a clean
            # one.
            "errors": 0,
            "status": "completed",
        }
        new_or_updated_doc_ids: List[str] = []
        # Docs whose content changed in place: their stale FAISS vectors must be
        # purged before the re-index rebuilds them (see _ingest_item).
        reindexed_doc_ids: List[str] = []
        # Prior documents orphaned when an in-place edit dedups onto a different
        # existing doc: their stale vectors are purged like a removal.
        released_doc_ids: List[str] = []
        # Each id is appended only AFTER its own removal committed, so the
        # finally-block vector purge never touches a rolled-back removal.
        removed_doc_ids: List[str] = []
        # Subset of removed/released docs whose Document row was HARD-deleted:
        # their vectors must also leave the default Library collection's index
        # (a kept/foreign doc's default-collection vectors stay valid).
        hard_deleted_doc_ids: List[str] = []
        # (document_id, collection_id) -> FAISS int chunk ids, captured by
        # _release_document / _purge_collection_chunks just BEFORE they
        # eagerly delete the matching DocumentChunk rows (each in its own
        # per-item transaction, for that transaction's atomicity — a cascade
        # failure must roll the rows back too). The finally-block vector
        # purge below runs AFTER those rows are gone, so it needs these
        # captured ids to find the FAISS vectors instead of the row lookup
        # VectorIndex.delete would otherwise do. See _cleanup_removed_vectors.
        pending_chunk_ids: Dict[Tuple[str, str], List[int]] = {}
        ldr_collection_id: Optional[str] = None
        default_collection_id: Optional[str] = None
        try:
            with get_user_db_session(self.username, self.password) as session:
                ldr_collection_id, ldr_created = self._ensure_ldr_collection(
                    session, client, cfg, collection_key
                )
                state = self._get_or_create_state(
                    session, cfg, collection_key, ldr_collection_id
                )
                state.last_status = "syncing"
                session.commit()
                if ldr_created:
                    # Durable only now (the commit above). A search within
                    # the cache TTL must offer the fresh Zotero collection
                    # as a tool, not the pre-creation engine list (#6609).
                    from ...web_search_engines.search_engines_config import (
                        invalidate_collection_engines_cache,
                    )

                    invalidate_collection_engines_cache(self.username)

                self._set_progress(
                    phase="checking",
                    collection_key=collection_key or None,  # gitleaks:allow
                    done=0,
                    total=None,
                    current=None,
                )
                remote_versions, library_version = client.get_top_item_versions(
                    collection_key or None
                )
                rows = (
                    session.query(ZoteroItemMap)
                    .filter_by(ldr_collection_id=ldr_collection_id)
                    .all()
                )
                mapped = {r.zotero_item_key: r for r in rows}
                remote_keys = set(remote_versions)

                source_type_id = get_source_type_id(
                    self.username, "zotero", self.password
                )

                # The default "Library" collection shows ALL documents, so
                # imports are linked into it too (like uploads and research
                # downloads). That membership is AMBIENT: the ownership /
                # removal logic below ignores it when deciding whether a
                # document is shared.
                default_row = (
                    session.query(Collection.id)
                    .filter_by(is_default=True)
                    .first()
                )
                default_collection_id = default_row[0] if default_row else None

                # 1) Removals — but NEVER read an empty remote set as "delete
                # everything". A truncated/transient empty response would
                # otherwise wipe the whole collection (docs + blobs + chunks).
                to_remove = set(mapped) - remote_keys
                if to_remove and (remote_keys or not mapped):
                    self._set_progress(
                        phase="removing", done=0, total=len(to_remove)
                    )
                if remote_keys or not mapped:
                    for removal_index, key in enumerate(to_remove, start=1):
                        # Per-item transaction: one document whose cascade
                        # fails must not abort the whole batch (or the sync).
                        # Its removal rolls back cleanly — the map row
                        # survives, so it is re-detected and retried next
                        # sync — while every other removal proceeds.
                        try:
                            rid = self._remove_item(
                                session,
                                mapped[key],
                                source_type_id,
                                default_collection_id,
                                pending_chunk_ids,
                            )
                            session.commit()
                        except Exception:
                            safe_rollback(session, "zotero removal")
                            logger.exception(
                                f"Zotero: failed to remove item {key}"
                            )
                            stats["errors"] += 1
                            continue
                        if rid:
                            removed_doc_ids.append(rid)
                            if not self._document_exists(session, rid):
                                hard_deleted_doc_ids.append(rid)
                        stats["removed"] += 1
                        self._set_progress(done=removal_index)
                else:
                    logger.warning(
                        f"Zotero: empty item set for "
                        f"{collection_key or 'ALL'} while {len(mapped)} items "
                        "are mapped — skipping removals to avoid mass-deletion"
                    )

                # 2) Additions / changes. Reprocess a key when it is new, its
                # version changed, or its previously-imported document went
                # missing. On a scheduled sync we intentionally do NOT
                # reprocess solely because document_id is None: that is the
                # case for deliberately skipped (no-PDF, import-disabled,
                # stray) items, which would otherwise be re-fetched on every
                # sync forever. A manual sync (reprocess_skipped) re-examines
                # them so settings changes and newly importable shapes take
                # effect without waiting for the item to change in Zotero.
                to_process = [
                    key
                    for key, version in remote_versions.items()
                    if key not in mapped
                    or mapped[key].zotero_version != version
                    or (reprocess_skipped and mapped[key].document_id is None)
                    or (
                        mapped[key].document_id is not None
                        and not self._document_exists(
                            session, mapped[key].document_id
                        )
                    )
                ]

                # Route the mode through the operator gate and write to the
                # per-user root — mirroring the DownloadService write path — so
                # this construction cannot bypass the PR's own enforcement even
                # if ``zotero.pdf_storage_mode`` ever gains a ``filesystem``
                # option. ``resolve_pdf_storage_mode`` coerces a gated
                # ``filesystem`` value to the encrypted ``database`` default;
                # today it is a no-op for the ``database``/``none`` choices.
                pdf_storage = PDFStorageManager(
                    library_root=self._library_root(),
                    storage_mode=resolve_pdf_storage_mode(cfg.pdf_storage_mode),
                    max_pdf_size_mb=DEFAULT_MAX_PDF_SIZE_MB,
                )

                self._set_progress(
                    phase="importing",
                    done=0,
                    total=len(to_process),
                    current=None,
                )
                returned_keys: set = set()
                for item in client.get_items(to_process):
                    returned_keys.add(item.key)
                    self._set_progress(
                        done=len(returned_keys),
                        current=(item.data.get("title") or item.key)[:120],
                    )
                    # A top-level stored PDF with no bibliographic parent (a
                    # PDF dropped straight into Zotero) IS importable — it
                    # falls through to ingestion as its own document. Other
                    # attachment/note strays are not.
                    if not item.is_standalone_pdf_attachment and (
                        item.data.get("parentItem")
                        or item.item_type in ("attachment", "note")
                    ):
                        # Record the version so it isn't re-fetched every
                        # sync. A child that slipped into /top is plumbing
                        # (not counted); a genuine top-level stray (a note,
                        # or a non-PDF / linked-file attachment) counts as
                        # skipped so the sync result doesn't silently read
                        # as "nothing found".
                        self._touch_map_version(
                            session,
                            ldr_collection_id,
                            item.key,
                            item.version,
                        )
                        if not item.data.get("parentItem"):
                            stats["skipped"] += 1
                        continue
                    if cfg.import_tags and not self._item_has_tags(
                        item, cfg.import_tags
                    ):
                        # Doesn't match the tag filter — record the version so
                        # it isn't re-fetched every sync. Additive filter: we
                        # do NOT remove items imported before the filter was
                        # set (removals come only from the version-map diff).
                        self._touch_map_version(
                            session,
                            ldr_collection_id,
                            item.key,
                            item.version,
                        )
                        stats["skipped"] += 1
                        continue
                    # The document this item currently maps to (if any) before
                    # ingest may repoint it onto a DIFFERENT existing doc via
                    # content-hash dedup.
                    prior_row = mapped.get(item.key)
                    prior_doc_id = prior_row.document_id if prior_row else None
                    try:
                        doc_id, action, reindexed = self._ingest_item(
                            session,
                            client,
                            cfg,
                            item,
                            ldr_collection_id,
                            source_type_id,
                            pdf_storage,
                            default_collection_id,
                            pending_chunk_ids,
                        )
                    except ZoteroTransientError:
                        # A rate-limit / 5xx (from a PDF/full-text fetch inside
                        # _ingest_item) will hit every remaining item too. Abort
                        # the batch and let the outer handler mark the sync
                        # failed so it retries next run, rather than hammering
                        # items 2..N against the limit and burning the budget.
                        safe_rollback(session, "zotero ingest")
                        raise
                    except Exception:
                        safe_rollback(session, "zotero ingest")
                        logger.exception(
                            f"Zotero: failed to ingest item {item.key}"
                        )
                        # Don't record a version — let it retry next sync.
                        stats["errors"] += 1
                        continue

                    # Map upsert + (on a dedup remap) release of the orphaned
                    # prior doc, in ONE transaction: committing the repoint on
                    # its own first would strand the prior doc forever if the
                    # release then failed — the item's new version would
                    # already be recorded, so no later sync would retry it.
                    # Per-item isolation: a failure rolls this item back
                    # cleanly (ingest included; retried next sync since its
                    # version was not recorded) without aborting the batch.
                    try:
                        self._upsert_map(
                            session, ldr_collection_id, item, doc_id
                        )
                        released = None
                        if (
                            prior_row
                            and prior_doc_id
                            and prior_doc_id != doc_id
                        ):
                            released = self._release_document(
                                session,
                                prior_doc_id,
                                ldr_collection_id,
                                prior_row.id,
                                source_type_id,
                                default_collection_id,
                                pending_chunk_ids,
                            )
                        session.commit()
                    except Exception:
                        safe_rollback(session, "zotero map update")
                        logger.exception(
                            f"Zotero: failed to record mapping for item "
                            f"{item.key}"
                        )
                        stats["errors"] += 1
                        continue
                    if released:
                        released_doc_ids.append(released)
                        if not self._document_exists(session, released):
                            hard_deleted_doc_ids.append(released)

                    if action == "imported":
                        stats["imported"] += 1
                        new_or_updated_doc_ids.append(doc_id)
                    elif action == "updated":
                        stats["updated"] += 1
                        new_or_updated_doc_ids.append(doc_id)
                        if reindexed:
                            reindexed_doc_ids.append(doc_id)
                    else:
                        stats["skipped"] += 1

                # Keys we asked for but Zotero didn't return (trashed,
                # permission-changed, etc.): record their version so they
                # aren't re-requested on every subsequent sync.
                for key in set(to_process) - returned_keys:
                    self._touch_map_version(
                        session,
                        ldr_collection_id,
                        key,
                        remote_versions.get(key, 0),
                    )
                session.commit()

                # 3) Persist high-water mark. Contained per-item failures
                # must stay visible: a run that skipped items because their
                # removal/ingest kept failing would otherwise look identical
                # to a clean one (green badge, last_error wiped) while the
                # same items silently fail on every sync.
                state.last_version = library_version
                state.last_status = "completed"
                state.last_error = (
                    f"{stats['errors']} item(s) failed and will be retried "
                    "next sync (see server log)"
                    if stats["errors"]
                    else None
                )
                state.last_synced_at = datetime.now(UTC)
                state.item_count = (
                    session.query(ZoteroItemMap)
                    .filter_by(ldr_collection_id=ldr_collection_id)
                    .filter(ZoteroItemMap.document_id.isnot(None))
                    .count()
                )
                # Counts of this completed run. A later failed attempt keeps
                # them (_mark_failed only touches last_status/last_error), so
                # they always describe the run of last_synced_at.
                state.last_imported_count = stats["imported"]
                state.last_updated_count = stats["updated"]
                state.last_removed_count = stats["removed"]
                state.last_skipped_count = stats["skipped"]
                state.last_error_count = stats["errors"]
                session.commit()
        except ZoteroError as exc:
            stats["status"] = "failed"
            stats["error"] = client_safe_zotero_message(
                exc, "Zotero request failed. Check the integration settings."
            )
            # The exception's text is safe here for the same reason as in
            # `test_connection`, and reaches the log the same way (scrubbed
            # into a local): every `ZoteroError` message in this package is
            # author-written, interpolating at most an HTTP status, a retry
            # count, an item count or an exception class name. Without it the
            # log records only "ZoteroError" whenever the allowlist misses
            # and the client sees the generic fallback — exactly the case an
            # operator needs the detail for. No traceback: `cfg` is a
            # parameter of this frame and renders `api_key`.
            safe_msg = scrub_error(exc, cfg.api_key, self.password)
            logger.warning(
                f"Zotero: sync failed for collection "
                f"{collection_key or 'ALL'} ({type(exc).__name__}): "
                f"{safe_msg}"
            )
            self._mark_failed(cfg, collection_key, stats["error"])
            return stats
        except Exception as exc:
            stats["status"] = "failed"
            stats["error"] = "Zotero sync failed. See server logs for details."
            # This handler is the one that flattens the client-visible
            # message, so the server-side record has to carry the cause.
            # Deliberately not logger.exception: `cfg` is a parameter of this
            # method and ZoteroConfig's dataclass repr renders `api_key`,
            # while `self.password` (the SQLCipher passphrase handed to
            # get_user_db_session inside this try) is live in the frame too.
            # An attached traceback renders both under loguru's `diagnose`.
            # That is a narrow window — only the ephemeral stderr sink can
            # have `diagnose` on, and only when LDR_APP_DEBUG *and*
            # LDR_LOGURU_DIAGNOSE are both set; the database, frontend and
            # file sinks are pinned to `diagnose=False`
            # (utilities/log_utils.py) — but an operator debugging a failing
            # sync is precisely who turns those on. Same shape as the
            # credential-frame handlers in web/queue/processor_v2.py: scrub
            # against the known secrets, then log without the traceback
            # chain. `scrub_error` (not bare `redact_secrets`) so the
            # credential-shape pass runs too and cannot drift from the other
            # catch sites — compare scheduler/background.py's Zotero handler.
            safe_msg = scrub_error(exc, cfg.api_key, self.password)
            logger.warning(
                f"Zotero: sync failed for collection "
                f"{collection_key or 'ALL'} ({type(exc).__name__}): "
                f"{safe_msg}"
            )
            self._mark_failed(cfg, collection_key, stats["error"])
            return stats
        finally:
            # Purge stale FAISS vectors for DURABLY-COMMITTED removals and
            # in-place content updates — even when the sync later fails partway
            # through the additions phase. Those docs' DB chunks are already
            # gone, so skipping this on the failure path would strand ORPHANED
            # vectors that keep surfacing in semantic search and are never
            # re-detected by a future sync (the map row was deleted). Runs
            # before the auto-index below, so an edited doc's old vectors are
            # cleared first. _cleanup_removed_vectors is best-effort and no-ops
            # when the collection was never RAG-indexed.
            #
            # Every id in these lists was appended only AFTER its own per-item
            # commit, so each is durable — a rolled-back removal/update never
            # reaches here and cannot lose a still-valid doc's vectors.
            if ldr_collection_id and self.password:
                if reindexed_doc_ids:
                    self._cleanup_removed_vectors(
                        reindexed_doc_ids,
                        ldr_collection_id,
                        pending_chunk_ids=pending_chunk_ids,
                    )
                if released_doc_ids:
                    self._cleanup_removed_vectors(
                        released_doc_ids,
                        ldr_collection_id,
                        pending_chunk_ids=pending_chunk_ids,
                    )
                if removed_doc_ids:
                    self._cleanup_removed_vectors(
                        removed_doc_ids,
                        ldr_collection_id,
                        pending_chunk_ids=pending_chunk_ids,
                    )
                # The default Library collection carries every synced doc too
                # (ambient membership), so its index needs the same care:
                # in-place updates invalidate its copy of the vectors, and a
                # hard-deleted document must not linger as dead hits there.
                # Kept/foreign releases are deliberately NOT purged from it —
                # their default-collection vectors are still valid.
                if (
                    default_collection_id
                    and default_collection_id != ldr_collection_id
                ):
                    if reindexed_doc_ids:
                        self._cleanup_removed_vectors(
                            reindexed_doc_ids,
                            default_collection_id,
                            pending_chunk_ids=pending_chunk_ids,
                        )
                    if hard_deleted_doc_ids:
                        self._cleanup_removed_vectors(
                            hard_deleted_doc_ids,
                            default_collection_id,
                            pending_chunk_ids=pending_chunk_ids,
                        )

            # Auto-index outside the sync transaction (best-effort, async).
            # Deliberately in the finally, ON FAILURE PATHS TOO: every id in
            # new_or_updated_doc_ids was committed per-item, and a sync that
            # fails on item N must not leave items 1..N-1 permanently
            # unindexed — their versions already match, so no future sync
            # reprocesses them, and the background reconciler only runs when
            # the document-scheduler settings are enabled.
            if new_or_updated_doc_ids and ldr_collection_id and self.password:
                try:
                    from ...web.routers.rag import trigger_auto_index

                    trigger_auto_index(
                        new_or_updated_doc_ids,
                        ldr_collection_id,
                        self.username,
                        self.password,
                    )
                    # Keep the default Library collection's index fresh too.
                    if (
                        default_collection_id
                        and default_collection_id != ldr_collection_id
                    ):
                        trigger_auto_index(
                            new_or_updated_doc_ids,
                            default_collection_id,
                            self.username,
                            self.password,
                        )
                except Exception:
                    logger.exception("Zotero: failed to trigger auto-indexing")

        return stats

    def _cleanup_removed_vectors(
        self,
        document_ids: List[str],
        ldr_collection_id: str,
        pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
    ) -> None:
        """Remove the given documents' vectors from the collection's FAISS
        index. No-op if the collection was never RAG-indexed. Best-effort —
        never raises (it runs inside a ``finally`` where a propagating exception
        would mask the real sync error), so the imports live inside the try.

        The DocumentChunk rows for these documents are ALREADY GONE by the
        time this runs (the per-item transactions that released/removed/
        reindexed them deleted them eagerly, for their own atomicity — see
        ``_release_document`` / ``_purge_collection_chunks``), so the usual
        source_id lookup in ``VectorIndex.delete`` would find nothing.
        ``pending_chunk_ids`` (keyed by ``(document_id, ldr_collection_id)``)
        carries the ids those per-item transactions captured BEFORE deleting
        the rows, so ``remove_documents_from_index`` can purge the exact
        FAISS vectors via ``VectorIndex.delete_ids`` instead.
        """
        try:
            from ...database.models.library import RAGIndex
            from ..services.library_rag_service import LibraryRAGService

            collection_name = f"collection_{ldr_collection_id}"
            with get_user_db_session(self.username, self.password) as session:
                rag_index = (
                    session.query(RAGIndex)
                    .filter_by(collection_name=collection_name, is_current=True)
                    .first()
                )
                if not rag_index:
                    return  # collection isn't indexed — nothing to clean
                embedding_model = rag_index.embedding_model
                embedding_provider = (
                    rag_index.embedding_model_type.value
                    if rag_index.embedding_model_type
                    else None
                )
                chunk_size = rag_index.chunk_size
                chunk_overlap = rag_index.chunk_overlap
                # This is a DELETE path, so the stored index_type MUST be
                # threaded through: LibraryRAGService defaults index_type="flat",
                # and removing from a real HNSW collection under the wrong type
                # would take the in-place remove_ids path (unsupported for HNSW)
                # and silently fail instead of the rebuild path. distance_metric
                # / normalize_vectors are threaded too for parity with the
                # search engines. NULL (legacy rows) → the service defaults.
                index_type = rag_index.index_type or "flat"
                distance_metric = rag_index.distance_metric or "cosine"
                normalize_vectors = to_bool(
                    rag_index.normalize_vectors, default=True
                )

            chunk_ids_by_document = None
            if pending_chunk_ids:
                chunk_ids_by_document = {
                    doc_id: ids
                    for doc_id in document_ids
                    if (
                        ids := pending_chunk_ids.get(
                            (doc_id, ldr_collection_id)
                        )
                    )
                }

            with LibraryRAGService(
                username=self.username,
                embedding_model=embedding_model,
                embedding_provider=embedding_provider,
                chunk_size=chunk_size,
                chunk_overlap=chunk_overlap,
                index_type=index_type,
                distance_metric=distance_metric,
                normalize_vectors=normalize_vectors,
                db_password=self.password,
            ) as rag_service:
                removed = rag_service.remove_documents_from_index(
                    document_ids,
                    ldr_collection_id,
                    chunk_ids_by_document=chunk_ids_by_document,
                )
            logger.info(
                f"Zotero: cleared {removed} FAISS vectors for "
                f"{len(document_ids)} document(s) in {collection_name}"
            )
        except Exception:
            logger.warning(
                "Zotero: failed to clear FAISS vectors for removed documents"
            )

    def _mark_failed(
        self, cfg: ZoteroConfig, collection_key: str, error: str
    ) -> None:
        """Best-effort: record a failed status on the sync-state row."""
        ck = collection_key or ""
        try:
            with get_user_db_session(self.username, self.password) as session:
                state = (
                    session.query(ZoteroSyncState)
                    .filter_by(
                        library_type=cfg.library_type,
                        library_id=cfg.library_id,
                        collection_key=ck,
                    )
                    .first()
                )
                if state:
                    state.last_status = "failed"
                    state.last_error = error[:2000]
                    session.commit()
        except Exception:
            logger.debug("Zotero: could not record failed state", exc_info=True)

    # -- LDR collection / state helpers -----------------------------------

    def _ensure_ldr_collection(
        self,
        session,
        client: ZoteroClient,
        cfg: ZoteroConfig,
        collection_key: str,
    ) -> Tuple[str, bool]:
        """Find or create the LDR collection backing this Zotero collection.

        Returns ``(collection_id, created)``; callers must invalidate the
        collection-engine cache only AFTER the transaction that makes a
        newly created row durable commits — invalidating at flush time
        would let a refill in the flush→commit window re-cache the
        pre-creation engine list (#6609).
        """
        ck = collection_key or ""
        state = (
            session.query(ZoteroSyncState)
            .filter_by(
                library_type=cfg.library_type,
                library_id=cfg.library_id,
                collection_key=ck,
            )
            .first()
        )
        if state:
            existing = (
                session.query(Collection)
                .filter_by(id=state.ldr_collection_id)
                .first()
            )
            if existing:
                return existing.id, False

        # Determine a friendly name.
        if collection_key:
            name = client.get_collection_name(collection_key) or collection_key
            display = f"Zotero: {name}"
            description = (
                f"Imported from Zotero collection '{name}' ({collection_key})."
            )
        else:
            display = "Zotero Library"
            description = "Imported from the entire Zotero library."

        collection_id = str(uuid.uuid4())
        session.add(
            Collection(
                id=collection_id,
                name=display,
                description=description,
                collection_type="zotero",
                is_default=False,
            )
        )
        session.flush()
        return collection_id, True

    def _get_or_create_state(
        self,
        session,
        cfg: ZoteroConfig,
        collection_key: str,
        ldr_collection_id: str,
    ) -> ZoteroSyncState:
        ck = collection_key or ""
        state = (
            session.query(ZoteroSyncState)
            .filter_by(
                library_type=cfg.library_type,
                library_id=cfg.library_id,
                collection_key=ck,
            )
            .first()
        )
        if state:
            # Keep the collection pointer fresh in case it was recreated.
            state.ldr_collection_id = ldr_collection_id
            return state
        state = ZoteroSyncState(
            library_type=cfg.library_type,
            library_id=cfg.library_id,
            collection_key=ck,
            ldr_collection_id=ldr_collection_id,
            last_version=0,
            last_status="pending",
        )
        session.add(state)
        session.flush()
        return state

    # -- item ingestion ----------------------------------------------------

    def _ingest_item(
        self,
        session,
        client: ZoteroClient,
        cfg: ZoteroConfig,
        item: ZoteroItem,
        ldr_collection_id: str,
        source_type_id: str,
        pdf_storage: PDFStorageManager,
        default_collection_id: Optional[str] = None,
        pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
    ) -> Tuple[Optional[str], str, bool]:
        """Create or update the LDR document for a Zotero item.

        ``pending_chunk_ids`` is forwarded to ``_purge_collection_chunks`` —
        see the note on ``_release_document``.

        Returns ``(document_id, action, reindexed_in_place)`` where action is
        ``"imported"`` | ``"updated"`` | ``"skipped"``. ``reindexed_in_place``
        is True only when an existing document's content changed and its stale
        RAG chunks were purged here — the caller must then clear the matching
        FAISS vectors before the re-index rebuilds them.
        """
        if item.is_standalone_pdf_attachment:
            # A PDF dropped into Zotero with no bibliographic parent: the
            # item IS its own attachment (it has no children to fetch).
            item.attachments = [item.as_attachment()]
        else:
            item.attachments = client.get_children(item.key)
        pdf_att = item.best_pdf_attachment()

        pdf_bytes = None
        zotero_fulltext = None
        if pdf_att:
            # In text-only mode we don't keep the PDF, so prefer Zotero's
            # already-extracted full text and skip the download + local parse
            # entirely. Falls back to downloading if Zotero has no indexed
            # text for the attachment.
            if cfg.pdf_storage_mode == "none":
                zotero_fulltext = client.get_attachment_fulltext(pdf_att.key)
            if not zotero_fulltext:
                pdf_bytes = client.download_attachment(pdf_att.key)
                # Validate the downloaded body really is a PDF. The /file
                # endpoint can redirect to an HTML error page; without this
                # we'd store that as file_type="pdf" and extract garbage.
                if pdf_bytes is not None and b"%PDF" not in pdf_bytes[:1024]:
                    logger.warning(
                        f"Zotero: attachment {pdf_att.key} did not return PDF "
                        "content; treating item as having no PDF"
                    )
                    pdf_bytes = None

        if pdf_bytes:
            content = pdf_bytes
            file_type = "pdf"
            mime_type = "application/pdf"
            text, extraction_method = self._safe_extract_text(pdf_bytes, item)
        elif zotero_fulltext:
            from ...text_processing import remove_surrogates

            text = remove_surrogates(zotero_fulltext)
            content = text.encode("utf-8", errors="ignore")
            file_type = "pdf"  # it is a PDF paper; we just reused Zotero's text
            mime_type = "application/pdf"
            extraction_method = "zotero_fulltext"
        else:
            if not cfg.import_items_without_pdf:
                return None, "skipped", False
            text = self._metadata_text(item)
            content = text.encode("utf-8", errors="ignore")
            file_type = "text"
            mime_type = "text/plain"
            extraction_method = "metadata"

        # Optionally append the user's annotations (highlights/comments) and
        # child notes to the searchable text. Kept out of the content hash so
        # it doesn't perturb dedup of the primary document.
        if cfg.import_annotations:
            extra = self._collect_annotations_text(client, item)
            if extra:
                text = f"{text}\n\n{extra}" if text else extra

        doc_hash = hashlib.sha256(content).hexdigest()

        # The document this item currently maps to (if any) — needed both to
        # detect an in-place content change and, on unchanged content, to
        # decide whether the searchable text may be refreshed safely.
        prior = (
            session.query(ZoteroItemMap)
            .filter_by(
                ldr_collection_id=ldr_collection_id, zotero_item_key=item.key
            )
            .first()
        )
        # -1 matches no row (Integer PK starts at 1) so the "any OTHER
        # mapping?" exclusion below stays correct when there is no prior row.
        prior_mapping_id = prior.id if prior else -1

        # Dedup: an identical document (same bytes) may already exist.
        # document_hash is globally UNIQUE, so this can match a document from
        # a different source (a manual upload or research download). Only
        # rewrite metadata on documents WE own (Zotero source); for a foreign
        # document just add the collection link — never clobber the user's
        # title/tags or take ownership of it.
        existing = (
            session.query(Document).filter_by(document_hash=doc_hash).first()
        )
        if existing:
            if existing.source_type_id == source_type_id:
                # Deliberately gated on ownership only (NOT exclusivity):
                # metadata edits must keep propagating to a doc shared across
                # two synced collections. For byte-identical twin ITEMS this
                # means last-synced-twin-wins on title/tags — an accepted
                # trade-off for content that is by definition the same paper.
                self._apply_metadata(existing, item)
            ensure_in_collection(session, existing.id, ldr_collection_id)
            if default_collection_id:
                # The default "Library" collection lists all documents.
                ensure_in_collection(
                    session, existing.id, default_collection_id
                )
            # The content bytes are unchanged, but the searchable text may
            # not be: annotations/notes are appended AFTER hashing (so they
            # don't perturb dedup), and a previously failed PDF extraction
            # may have fallen back to metadata text. Refresh it — but only on
            # a document this item exclusively owns; rewriting a shared or
            # foreign doc's text would change what its other references
            # surface.
            if (text or "") != (
                existing.text_content or ""
            ) and self._exclusive_to_mapping(
                session,
                existing,
                prior_mapping_id,
                ldr_collection_id,
                source_type_id,
                default_collection_id,
            ):
                existing.text_content = text
                existing.character_count = len(text) if text else 0
                existing.word_count = len(text.split()) if text else 0
                existing.extraction_method = extraction_method
                self._purge_collection_chunks(
                    session,
                    existing.id,
                    ldr_collection_id,
                    default_collection_id,
                    pending_chunk_ids,
                )
                return existing.id, "updated", True
            # Content is byte-identical (matched by hash), so the existing
            # chunks/vectors are still valid — no purge needed.
            return existing.id, "updated", False

        # Is this a re-import of an item we already mapped (content changed)?
        doc = None
        if prior and prior.document_id:
            doc = (
                session.query(Document).filter_by(id=prior.document_id).first()
            )
            # An in-place rewrite is only safe on a document this item
            # exclusively owns. A dedup-adopted user upload, a byte-identical
            # twin's shared doc, or a doc linked into another collection must
            # never be mutated under its other references — fork a fresh
            # Document instead; the caller's remap logic then releases this
            # item's claim on the old one (_release_document keeps shared and
            # foreign documents intact).
            if doc is not None and not self._exclusive_to_mapping(
                session,
                doc,
                prior_mapping_id,
                ldr_collection_id,
                source_type_id,
                default_collection_id,
            ):
                doc = None

        created = doc is None
        if doc is None:
            doc = Document(
                id=str(uuid.uuid4()),
                source_type_id=source_type_id,
            )
            session.add(doc)

        store_pdf_in_db = (
            cfg.pdf_storage_mode == "database" and file_type == "pdf"
        )

        doc.document_hash = doc_hash
        doc.filename = self._filename_for(item, file_type)
        doc.file_size = len(content)
        doc.file_type = file_type
        doc.mime_type = mime_type
        doc.text_content = text
        doc.character_count = len(text) if text else 0
        doc.word_count = len(text.split()) if text else 0
        doc.extraction_method = extraction_method
        doc.extraction_source = "zotero"
        doc.status = DocumentStatus.COMPLETED
        doc.processed_at = datetime.now(UTC)
        doc.storage_mode = "database" if store_pdf_in_db else "none"
        doc.file_path = None if store_pdf_in_db else FILE_PATH_TEXT_ONLY
        self._apply_metadata(doc, item)
        session.flush()

        if store_pdf_in_db:
            try:
                pdf_storage.save_pdf(
                    pdf_content=content,
                    document=doc,
                    session=session,
                    filename=doc.filename,
                )
            except Exception:
                logger.exception(
                    f"Zotero: failed to store PDF blob for {item.key}"
                )
                # The blob write failed, so there is no PDF to serve. Leave the
                # doc searchable via its extracted text but downgrade it to
                # text-only, otherwise ZoteroItemMap.has_pdf (keyed off
                # file_type=="pdf") would advertise a PDF that load_pdf() — which
                # looks up the missing blob by document_id — can never return.
                doc.file_type = "text"
                doc.mime_type = "text/plain"
                doc.storage_mode = "none"
                doc.file_path = FILE_PATH_TEXT_ONLY
                # On a re-sync a stale blob from a previous import may linger;
                # drop it so load_pdf() can't serve an outdated PDF for what is
                # now a text-only doc.
                session.query(DocumentBlob).filter_by(
                    document_id=doc.id
                ).delete(synchronize_session=False)
        elif not created:
            # Re-sync of an item previously imported WITH a database-stored
            # PDF that now has no usable PDF (removed in Zotero, or the
            # re-downloaded body failed the %PDF check). The doc is being
            # marked text-only (storage_mode="none"), so drop the stale
            # encrypted blob — otherwise PDFStorageManager.load_pdf(), which
            # keys off document_id and ignores file_type, would keep serving
            # the orphaned PDF.
            removed = (
                session.query(DocumentBlob)
                .filter_by(document_id=doc.id)
                .delete(synchronize_session=False)
            )
            if removed:
                logger.info(
                    f"Zotero: removed stale PDF blob for {item.key} "
                    "(item no longer has a usable PDF)"
                )

        ensure_in_collection(session, doc.id, ldr_collection_id)
        if default_collection_id:
            # The default "Library" collection lists all documents.
            ensure_in_collection(session, doc.id, default_collection_id)
        # On an in-place content change the document's previous RAG chunks are
        # now stale: chunking is content-derived and _store_chunks_to_db dedups
        # by chunk hash, so a re-index would ADD the new chunks while the old
        # ones linger and keep surfacing outdated text in search. Purge this
        # collection's chunks for the doc now (atomic with the content update)
        # and force a re-index by clearing the indexed flag; the caller clears
        # the matching FAISS vectors before that re-index runs.
        if not created:
            self._purge_collection_chunks(
                session,
                doc.id,
                ldr_collection_id,
                default_collection_id,
                pending_chunk_ids,
            )

        return doc.id, ("imported" if created else "updated"), (not created)

    @staticmethod
    def _exclusive_to_mapping(
        session,
        doc: Document,
        mapping_id,
        coll_id: str,
        source_type_id: str,
        default_collection_id: Optional[str] = None,
    ) -> bool:
        """True when ``doc`` belongs to this item mapping alone: Zotero owns
        it, no OTHER :class:`ZoteroItemMap` row points at it, and it isn't
        linked into any other collection. Only such a document may be
        rewritten in place — anything else (a dedup-adopted user upload, a
        byte-identical twin's shared doc, a doc the user linked into another
        collection) would be corrupted under its other references.

        Membership in the default "Library" collection is AMBIENT (every
        import is linked there so the main library view lists it) and does
        not count as another reference.
        """
        if doc.source_type_id != source_type_id:
            return False
        shared_mapping = (
            session.query(ZoteroItemMap.id)
            .filter(
                ZoteroItemMap.document_id == doc.id,
                ZoteroItemMap.id != mapping_id,
            )
            .first()
            is not None
        )
        if shared_mapping:
            return False
        ambient = {coll_id}
        if default_collection_id:
            ambient.add(default_collection_id)
        linked_elsewhere = (
            session.query(DocumentCollection.document_id)
            .filter(
                DocumentCollection.document_id == doc.id,
                DocumentCollection.collection_id.notin_(ambient),
            )
            .first()
            is not None
        )
        return not linked_elsewhere

    @staticmethod
    def _purge_collection_chunks(
        session,
        doc_id: str,
        coll_id: str,
        default_collection_id: Optional[str] = None,
        pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
    ) -> None:
        """Purge a doc's RAG chunks and clear the link's indexed flag, forcing
        a re-index after an in-place text change — for this collection AND
        (when given) the default Library collection, whose ambient copy of
        the chunks is derived from the same now-changed text.

        Raises on failure so the whole per-item transaction rolls back (the
        item retries next sync) — swallowing here would let the caller purge
        FAISS vectors for chunks that still exist.

        ``pending_chunk_ids`` — see the note on ``_release_document``: when
        supplied, each collection's chunk ids are captured into it BEFORE
        being eagerly deleted below, so the later batched
        ``_cleanup_removed_vectors`` pass can purge those exact FAISS ids
        via ``VectorIndex.delete_ids`` instead of a now-futile source_id
        lookup. ``None`` (what direct unit tests pass) skips capture.
        """
        targets = [coll_id]
        if default_collection_id and default_collection_id != coll_id:
            targets.append(default_collection_id)
        for cid in targets:
            if pending_chunk_ids is not None:
                ZoteroSyncService._capture_chunk_ids(
                    pending_chunk_ids, session, doc_id, cid
                )
            CascadeHelper.delete_document_chunks(
                session, doc_id, collection_name=f"collection_{cid}"
            )
            link = (
                session.query(DocumentCollection)
                .filter_by(document_id=doc_id, collection_id=cid)
                .first()
            )
            if link:
                link.indexed = False

    def _collect_annotations_text(
        self, client: ZoteroClient, item: ZoteroItem
    ) -> str:
        """Gather the item's PDF annotations + child notes as one text block.

        Best-effort: a failure fetching either must not break ingestion.
        """
        from ...text_processing import remove_surrogates

        annotations: List[str] = []
        for att in item.attachments or []:
            try:
                annotations.extend(client.get_annotations(att.key))
            except Exception:
                logger.debug(
                    f"Zotero: could not fetch annotations for {att.key}",
                    exc_info=True,
                )
        try:
            notes = client.get_notes(item.key)
        except Exception:
            logger.debug(
                f"Zotero: could not fetch notes for {item.key}", exc_info=True
            )
            notes = []

        sections: List[str] = []
        if annotations:
            sections.append(
                "Annotations:\n" + "\n".join(f"- {a}" for a in annotations)
            )
        if notes:
            sections.append("Notes:\n" + "\n\n".join(notes))
        return remove_surrogates("\n\n".join(sections)) if sections else ""

    def _safe_extract_text(
        self, pdf_bytes: bytes, item: ZoteroItem
    ) -> Tuple[Optional[str], str]:
        """Extract text from PDF bytes; returns ``(text, extraction_method)``.

        Falls back to metadata text (method ``"metadata"``) when extraction
        fails or yields nothing, so the document is still searchable — the
        method string keeps downstream consumers from assuming real PDF text
        when only the fallback was stored.
        """
        from ...document_loaders import extract_text_from_bytes
        from ...text_processing import remove_surrogates

        try:
            text = extract_text_from_bytes(pdf_bytes, ".pdf", item.key)
        except Exception:
            logger.debug(
                f"Zotero: PDF text extraction failed for {item.key}",
                exc_info=True,
            )
            text = None
        if not text:
            # Fall back to metadata so the document is still searchable.
            return self._metadata_text(item), "metadata"
        return remove_surrogates(text), "pdf_extraction"

    # -- metadata helpers --------------------------------------------------

    def _apply_metadata(self, doc: Document, item: ZoteroItem) -> None:
        data = item.data
        doc.title = (data.get("title") or doc.filename or item.key)[:5000]
        authors = self._authors(item)
        if authors:
            doc.authors = authors
        doi = (data.get("DOI") or "").strip()
        if doi:
            doc.doi = doi[:255]
        isbn = (data.get("ISBN") or "").strip()
        if isbn:
            doc.isbn = isbn[:20]
        published = self._parse_date(data.get("date"))
        if published:
            doc.published_date = published
        tags = [
            t.get("tag")
            for t in data.get("tags", [])
            if isinstance(t, dict) and t.get("tag")
        ]
        if tags:
            doc.tags = tags
        url = self._source_url(item)
        if url:
            doc.original_url = url

    @staticmethod
    def _item_has_tags(item: ZoteroItem, required: List[str]) -> bool:
        """True if the item carries ALL required tags (case-insensitive)."""
        item_tags = {
            (t.get("tag") or "").strip().lower()
            for t in item.data.get("tags", []) or []
            if isinstance(t, dict)
        }
        return all(r.strip().lower() in item_tags for r in required)

    @staticmethod
    def _authors(item: ZoteroItem) -> List[str]:
        names: List[str] = []
        for creator in item.data.get("creators", []) or []:
            if not isinstance(creator, dict):
                continue
            if creator.get("name"):
                names.append(creator["name"].strip())
            else:
                full = " ".join(
                    p
                    for p in (
                        creator.get("firstName", ""),
                        creator.get("lastName", ""),
                    )
                    if p
                ).strip()
                if full:
                    names.append(full)
        return names

    @staticmethod
    def _source_url(item: ZoteroItem) -> Optional[str]:
        data = item.data
        if data.get("url"):
            return str(data["url"]).strip()
        doi = (data.get("DOI") or "").strip()
        if doi:
            return f"https://doi.org/{doi}"
        return None

    @staticmethod
    def _parse_date(raw) -> Optional[date]:
        """Best-effort parse of Zotero's freeform date field."""
        if not raw:
            return None
        text = str(raw).strip()
        # Try full ISO first.
        for fmt in ("%Y-%m-%d", "%Y-%m"):
            try:
                return datetime.strptime(text[: len(fmt) + 2], fmt).date()
            except ValueError:
                continue
        match = re.search(r"(\d{4})", text)
        if match:
            year = int(match.group(1))
            if 1000 <= year <= 9999:
                return date(year, 1, 1)
        return None

    def _metadata_text(self, item: ZoteroItem) -> str:
        data = item.data
        parts: List[str] = []
        if data.get("title"):
            parts.append(f"Title: {data['title']}")
        authors = self._authors(item)
        if authors:
            parts.append(f"Authors: {', '.join(authors)}")
        if data.get("date"):
            parts.append(f"Date: {data['date']}")
        if data.get("publicationTitle"):
            parts.append(f"Publication: {data['publicationTitle']}")
        if data.get("DOI"):
            parts.append(f"DOI: {data['DOI']}")
        if data.get("url"):
            parts.append(f"URL: {data['url']}")
        tags = [
            t.get("tag")
            for t in data.get("tags", [])
            if isinstance(t, dict) and t.get("tag")
        ]
        if tags:
            parts.append(f"Tags: {', '.join(tags)}")
        if data.get("abstractNote"):
            parts.append(f"\nAbstract:\n{data['abstractNote']}")

        from ...text_processing import remove_surrogates

        return remove_surrogates("\n".join(parts)) if parts else item.key

    @staticmethod
    def _filename_for(item: ZoteroItem, file_type: str) -> str:
        title = (item.data.get("title") or "").strip()
        # Standalone attachments carry the filename as their title — don't
        # produce "paper.pdf.pdf".
        if title.lower().endswith(f".{file_type}".lower()):
            title = title[: -(len(file_type) + 1)]
        candidate = f"{title[:120]}.{file_type}" if title else None
        if candidate:
            try:
                return sanitize_filename(candidate)
            except UnsafeFilenameError:
                pass
        return f"{item.key}.{file_type}"

    # -- mapping / removal -------------------------------------------------

    def _upsert_map(
        self,
        session,
        ldr_collection_id: str,
        item: ZoteroItem,
        document_id: Optional[str],
    ) -> None:
        row = (
            session.query(ZoteroItemMap)
            .filter_by(
                ldr_collection_id=ldr_collection_id,
                zotero_item_key=item.key,
            )
            .first()
        )
        has_pdf = bool(
            document_id
            and (
                session.query(Document)
                .filter_by(id=document_id, file_type="pdf")
                .first()
            )
        )
        if row:
            row.zotero_version = item.version
            row.document_id = document_id
            row.has_pdf = has_pdf
            row.last_synced_at = datetime.now(UTC)
        else:
            session.add(
                ZoteroItemMap(
                    ldr_collection_id=ldr_collection_id,
                    zotero_item_key=item.key,
                    zotero_version=item.version,
                    document_id=document_id,
                    has_pdf=has_pdf,
                    last_synced_at=datetime.now(UTC),
                )
            )

    def _touch_map_version(
        self,
        session,
        ldr_collection_id: str,
        zotero_item_key: str,
        version: int,
    ) -> None:
        """Record a key's version without importing a document.

        Used for keys we deliberately don't import (a child/note that slipped
        into the top-level list, or a key Zotero didn't return) so the
        version-changed predicate doesn't re-queue them on every sync. Does
        not touch ``document_id`` (stays None / unchanged).
        """
        ik = zotero_item_key
        row = (
            session.query(ZoteroItemMap)
            .filter_by(
                ldr_collection_id=ldr_collection_id,
                zotero_item_key=ik,
            )
            .first()
        )
        if row:
            row.zotero_version = version
            row.last_synced_at = datetime.now(UTC)
        else:
            session.add(
                ZoteroItemMap(
                    ldr_collection_id=ldr_collection_id,
                    zotero_item_key=ik,
                    zotero_version=version,
                    document_id=None,
                    has_pdf=False,
                    last_synced_at=datetime.now(UTC),
                )
            )

    def _remove_item(
        self,
        session,
        row: ZoteroItemMap,
        source_type_id: str,
        default_collection_id: Optional[str] = None,
        pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
    ) -> Optional[str]:
        """Remove an item that no longer exists in Zotero.

        The document is only hard-deleted when nothing else references it AND
        it is a Zotero-owned document. Because dedup is global by content hash,
        one Document can be shared by multiple collections / Zotero mappings, or
        can be a user upload / research download that Zotero merely adopted via
        dedup; in those cases we must only drop *this* collection's link and the
        mapping row, never destroy a shared or foreign-owned document (and its
        blob/chunks) out from under the other references / the user.

        ``pending_chunk_ids`` — see :meth:`_release_document`.

        Returns the RELEASED document_id (so the caller can clear its FAISS
        vectors for this collection after the transaction), or None when the
        document is kept — either it has no document, or a byte-identical twin
        still maps to it in this collection (in which case its vectors must NOT
        be purged, or the surviving twin would vanish from search).
        """
        released = self._release_document(
            session,
            row.document_id,
            row.ldr_collection_id,
            row.id,
            source_type_id,
            default_collection_id,
            pending_chunk_ids,
        )
        session.delete(row)
        return released

    def _release_document(
        self,
        session,
        doc_id: Optional[str],
        coll_id: str,
        keep_mapping_id,
        source_type_id: str,
        default_collection_id: Optional[str] = None,
        pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
    ) -> Optional[str]:
        """Release a document from this collection: drop its collection link and
        RAG chunks, hard-deleting the document only when nothing else references
        it AND Zotero owns it. Never destroys a shared or foreign-owned document
        (dedup is global by content hash, so one Document may be shared across
        collections/mappings, or be a user upload Zotero merely adopted).

        ``keep_mapping_id`` is the ZoteroItemMap row that is going away or being
        repointed — excluded from the "is it shared?" check. Used both when an
        item is removed (:meth:`_remove_item`) and when an in-place edit dedups
        onto a *different* existing document, orphaning the item's prior doc.
        Returns ``doc_id`` so the caller can clear its FAISS vectors after the
        transaction.

        The chunk rows this method deletes below are the SAME rows a later,
        BATCHED ``_cleanup_removed_vectors`` call needs to find (by
        source_id + collection_name) to know which FAISS vectors to remove
        — but by the time that batched call runs, deleting the rows here
        (eagerly, so a cascade failure rolls back this whole transaction —
        see the comment above the ``if referenced_elsewhere`` branch below)
        has already made them unfindable. When the caller supplies
        ``pending_chunk_ids`` (keyed by ``(doc_id, collection_id)``), this
        captures each affected collection's chunk ids into it BEFORE
        deleting the rows, so the caller can purge those exact FAISS ids
        later via ``VectorIndex.delete_ids`` instead of the now-futile
        source_id lookup. ``None`` (the default, and what direct unit tests
        pass) skips capture and behaves exactly as before.
        """
        if not doc_id:
            return None
        # Another item in THIS collection still maps to the doc (byte-identical
        # dedup): it must stay linked + indexed here, so there is nothing to
        # release and no vectors to purge.
        if (
            session.query(ZoteroItemMap)
            .filter(
                ZoteroItemMap.document_id == doc_id,
                ZoteroItemMap.id != keep_mapping_id,
                ZoteroItemMap.ldr_collection_id == coll_id,
            )
            .first()
            is not None
        ):
            return None
        doc_owned_by_zotero = (
            session.query(Document.id)
            .filter_by(id=doc_id, source_type_id=source_type_id)
            .first()
            is not None
        )
        referenced_elsewhere = (
            session.query(ZoteroItemMap)
            .filter(
                ZoteroItemMap.document_id == doc_id,
                ZoteroItemMap.id != keep_mapping_id,
            )
            .first()
            is not None
        ) or (
            # Membership in the default "Library" collection is ambient
            # (every import is linked there) — it must not keep a removed
            # item's document alive.
            session.query(DocumentCollection)
            .filter(
                DocumentCollection.document_id == doc_id,
                DocumentCollection.collection_id.notin_(
                    {coll_id, default_collection_id}
                    if default_collection_id
                    else {coll_id}
                ),
            )
            .first()
            is not None
        )
        # A cascade failure below must PROPAGATE so the whole release (and the
        # map change it shares a transaction with) rolls back and the item is
        # retried next sync. Swallowing it would commit a half-release — the
        # map row gone but the doc/chunks still present — and the caller would
        # then purge FAISS vectors for a document that still exists.
        if referenced_elsewhere or not doc_owned_by_zotero:
            # Keep the document (shared with another collection/mapping, or a
            # user upload / research download Zotero only adopted via
            # content-hash dedup — never Zotero's to destroy), but drop this
            # collection's link AND its RAG chunks so it stops surfacing here.
            # The caller clears this collection's FAISS vectors for the returned
            # doc_id after the transaction.
            if pending_chunk_ids is not None:
                self._capture_chunk_ids(
                    pending_chunk_ids,
                    session,
                    doc_id,
                    coll_id,
                )
            CascadeHelper.delete_document_chunks(
                session, doc_id, collection_name=f"collection_{coll_id}"
            )
            session.query(DocumentCollection).filter_by(
                document_id=doc_id, collection_id=coll_id
            ).delete(synchronize_session=False)
        else:
            doc = session.query(Document).filter_by(id=doc_id).first()
            if doc:
                # DocumentChunk has no FK cascade — delete RAG chunks
                # explicitly before removing the document. Capture ids for
                # BOTH collections this doc can possibly be in — established
                # above (doc_owned_by_zotero and not referenced_elsewhere)
                # to be at most coll_id and default_collection_id.
                if pending_chunk_ids is not None:
                    self._capture_chunk_ids(
                        pending_chunk_ids, session, doc_id, coll_id
                    )
                    if (
                        default_collection_id
                        and default_collection_id != coll_id
                    ):
                        self._capture_chunk_ids(
                            pending_chunk_ids,
                            session,
                            doc_id,
                            default_collection_id,
                        )
                CascadeHelper.delete_document_chunks(session, doc.id)
                CascadeHelper.delete_document_completely(session, doc.id)
        return doc_id

    @staticmethod
    def _capture_chunk_ids(
        pending_chunk_ids: Dict[Tuple[str, str], List[int]],
        session,
        doc_id: str,
        collection_id: str,
    ) -> None:
        """Snapshot ``doc_id``'s chunk-row int ids for ``collection_id`` into
        ``pending_chunk_ids`` BEFORE they are eagerly deleted by the caller.

        A plain SELECT (no locking/mutation) — safe to run just ahead of the
        row-deleting statement in the same transaction. See the note on
        ``pending_chunk_ids`` in :meth:`_release_document`.
        """
        ids = [
            row.id
            for row in session.query(DocumentChunk.id).filter_by(
                source_type="document",
                source_id=doc_id,
                collection_name=f"collection_{collection_id}",
            )
        ]
        if ids:
            pending_chunk_ids.setdefault((doc_id, collection_id), []).extend(
                ids
            )

    @staticmethod
    def _document_exists(session, document_id: Optional[str]) -> bool:
        if not document_id:
            return False
        return (
            session.query(Document.id).filter_by(id=document_id).first()
            is not None
        )