diff --git a/backend/routers/bookmarks.py b/backend/routers/bookmarks.py index fc2cd0384..0a90943ed 100644 --- a/backend/routers/bookmarks.py +++ b/backend/routers/bookmarks.py @@ -68,6 +68,13 @@ class SavedPapersResponse(BaseModel): "only needs to reconnect" ), ) + bucket_error: str | None = Field( + None, + description=( + "Why the authorized HF Bucket could not be used; saved papers were " + "read from Papers With Code instead" + ), + ) def _bucket_error(error: PaperBucketError) -> HTTPException: @@ -145,6 +152,7 @@ def get_my_bookmarks( areas=areas, bucket_connected=projection.bucket_connected, bucket_migrated=projection.bucket_migrated, + bucket_error=projection.bucket_error, ) diff --git a/backend/services/bookmark_service.py b/backend/services/bookmark_service.py index 93f3dfa4d..5c032719e 100644 --- a/backend/services/bookmark_service.py +++ b/backend/services/bookmark_service.py @@ -28,6 +28,7 @@ class BookmarkRefListing: refs: tuple[SavedPaperRef, ...] bucket_connected: bool + bucket_error: str | None = None @dataclass(frozen=True) @@ -51,6 +52,7 @@ class SavedPapersProjection: areas: tuple[SavedAreaProjection, ...] bucket_connected: bool bucket_migrated: bool + bucket_error: str | None = None @dataclass(frozen=True) @@ -178,11 +180,12 @@ def list_refs( refs = tuple(store.list()) except PaperBucketError as error: logger.warning( - "Falling back to database bookmarks for %s: %s", + "Falling back to database bookmarks for %s: %s (%r)", username, error, + error.__cause__, ) - return BookmarkRefListing(tuple(legacy), False) + return BookmarkRefListing(tuple(legacy), False, str(error)) self.record_bucket_migration(username) return BookmarkRefListing(refs, True) @@ -206,6 +209,7 @@ def list_grouped( areas=(), bucket_connected=listing.bucket_connected, bucket_migrated=bucket_migrated, + bucket_error=listing.bucket_error, ) db_papers = self.db.query(DBPaper).filter(DBPaper.id.in_(paper_ids)).all() @@ -308,6 +312,7 @@ def list_grouped( ), bucket_connected=listing.bucket_connected, bucket_migrated=bucket_migrated, + bucket_error=listing.bucket_error, ) def _require_bucket( @@ -316,12 +321,24 @@ def _require_bucket( encrypted_credential: str | None, hf_user_id: str, username: str, - ) -> SavedPapersBucket: - store = self.initialize_bucket( - encrypted_credential=encrypted_credential, - hf_user_id=hf_user_id, - username=username, - ) + ) -> SavedPapersBucket | None: + """Return the Bucket, or None while an unmigrated account cannot set one up.""" + try: + store = self.initialize_bucket( + encrypted_credential=encrypted_credential, + hf_user_id=hf_user_id, + username=username, + ) + except PaperBucketError as error: + if self.bucket_migrated(username): + raise + logger.warning( + "Saving bookmarks for %s in the database: %s (%r)", + username, + error, + error.__cause__, + ) + return None if store is None: raise PaperBucketError( "Authorize Papers With Code to manage your saved-papers Bucket.", @@ -337,7 +354,11 @@ def add_bookmark( hf_user_id: str, username: str, ) -> None: - """Add a Bucket bookmark, then create its database compatibility mirror.""" + """Add a Bucket bookmark, then create its database compatibility mirror. + + An unmigrated account whose Bucket cannot be set up keeps saving to the + database, which stays its bookmark source until a migration succeeds. + """ paper = self.db.query(DBPaper).filter(DBPaper.id == paper_id).first() if paper is None: raise BookmarkPaperNotFoundError @@ -347,12 +368,13 @@ def add_bookmark( hf_user_id=hf_user_id, username=username, ) - store.add( - paper_id, - title=paper.title, - arxiv_id=paper.arxiv_id, - source_url=paper.source_url, - ) + if store is not None: + store.add( + paper_id, + title=paper.title, + arxiv_id=paper.arxiv_id, + source_url=paper.source_url, + ) existing = ( self.db.query(UserBookmark) @@ -380,7 +402,8 @@ def remove_bookmark( hf_user_id=hf_user_id, username=username, ) - store.remove(paper_id) + if store is not None: + store.remove(paper_id) self.db.query(UserBookmark).filter( UserBookmark.hf_username == username, UserBookmark.paper_id == paper_id, diff --git a/backend/tests/test_bookmarks_router.py b/backend/tests/test_bookmarks_router.py index 8d64fe2af..28a51649a 100644 --- a/backend/tests/test_bookmarks_router.py +++ b/backend/tests/test_bookmarks_router.py @@ -487,6 +487,7 @@ def test_existing_mirror_still_updates_bucket_without_committing(monkeypatch): def test_bucket_mutation_failure_prevents_database_mirror_change(monkeypatch): db = MutationDb() + monkeypatch.setattr(BookmarkService, "bucket_migrated", lambda *_args: True) class FailingStore(FakeBucketStore): def add(self, paper_id, **metadata): @@ -581,3 +582,52 @@ def test_disconnected_listing_reports_account_bucket_migration( assert result.bucket_connected is False assert result.bucket_migrated is expected + + +@pytest.mark.parametrize("migrated", [False, True]) +def test_bucket_setup_failure_saves_to_database_until_migrated(monkeypatch, migrated): + db = MutationDb() + + def failing_setup(*_args, **_kwargs): + raise PaperBucketError("Hugging Face could not write the saved-papers Bucket.") + + monkeypatch.setattr(BookmarkService, "initialize_bucket", failing_setup) + monkeypatch.setattr(BookmarkService, "bucket_migrated", lambda *_args: migrated) + user = {"username": "alice", "hf_user_id": "hf-alice"} + + if migrated: + with pytest.raises(HTTPException) as add_error: + bookmarks.add_bookmark(_request(), 42, user, db) + assert add_error.value.status_code == 400 + assert db.added == [] + assert db.commits == 0 + return + + bookmarks.add_bookmark(_request(), 42, user, db) + assert [item.paper_id for item in db.added] == [42] + assert db.commits == 1 + + bookmarks.remove_bookmark(_request(), 42, user, db) + assert db.bookmark_query.deleted is True + assert db.commits == 2 + + +def test_bucket_setup_failure_is_reported_on_the_listing(monkeypatch): + db = LegacyBookmarkDb([(42, datetime.now(UTC), "Legacy paper", None, None)]) + + def failing_setup(*_args, **_kwargs): + raise PaperBucketError("Hugging Face could not write the saved-papers Bucket.") + + monkeypatch.setattr(BookmarkService, "initialize_bucket", failing_setup) + + listing = BookmarkService(db).list_refs( + encrypted_credential="encrypted", + hf_user_id="hf-alice", + username="alice", + ) + + assert [item.paper_id for item in listing.refs] == [42] + assert listing.bucket_connected is False + assert listing.bucket_error == ( + "Hugging Face could not write the saved-papers Bucket." + ) diff --git a/docs/adr/0018-paper-catalog.md b/docs/adr/0018-paper-catalog.md index f680af385..20df7dd75 100644 --- a/docs/adr/0018-paper-catalog.md +++ b/docs/adr/0018-paper-catalog.md @@ -168,6 +168,12 @@ Saved papers live in the user's Hugging Face Bucket, but the Bucket token is sto Code: `backend/models/database/identity.py` +## Unmigrated accounts save to the database when their Bucket cannot be set up + +Some Hugging Face accounts cannot create or write their private saved-papers Bucket even after approving access (for example a Hub permission or storage refusal). Until an account has migrated, its database bookmarks are already the source that listings read, so save and unsave write the database and succeed instead of failing. The listing returns the Bucket error so /saved explains why the migration did not happen rather than offering the same approval again. Once an account has migrated, Bucket failures still fail the request, so the Bucket and the database mirror cannot diverge. A retried migration copies every database bookmark, including those saved during the fallback. + +Code: `backend/services/bookmark_service.py::BookmarkService._require_bucket` + ## Spam rejection reports counts from the pre-lock snapshot reject_active_as_spam takes its 'before' moderation snapshot without a row lock, before the locked catalog mutation runs, to preserve the historical semantics of the count it returns publicly. Moving the snapshot inside the lock would change that public count. diff --git a/frontend/src/lib/api/account.types.ts b/frontend/src/lib/api/account.types.ts index 1c07b26fd..839b4e0c9 100644 --- a/frontend/src/lib/api/account.types.ts +++ b/frontend/src/lib/api/account.types.ts @@ -30,6 +30,8 @@ export interface SavedPapersResponse { bucket_connected: boolean; /** True once any device has migrated this account to its HF Bucket. */ bucket_migrated: boolean; + /** Why the authorized HF Bucket could not be used, if it failed. */ + bucket_error?: string | null; } /** Payload accepted by `POST /papers/submit`. Either `arxiv_id` or diff --git a/frontend/src/views/SavedPapersView.tsx b/frontend/src/views/SavedPapersView.tsx index 16d70d7ec..140939cb9 100644 --- a/frontend/src/views/SavedPapersView.tsx +++ b/frontend/src/views/SavedPapersView.tsx @@ -125,6 +125,18 @@ const SavedPapersView: React.FC = () => { Reconnect Hugging Face Bucket + ) : showBucketMigration && query.data.bucket_error ? ( +
+ Hugging Face could not set up your private saved-papers Bucket:{" "} + {query.data.bucket_error} Your saved papers stay in Papers With Code, + and saving new papers still works. Check that your Hugging Face + account can create private Buckets, then try again. +
+ +