Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions backend/routers/bookmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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,
)


Expand Down
55 changes: 39 additions & 16 deletions backend/services/bookmark_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
class BookmarkRefListing:
refs: tuple[SavedPaperRef, ...]
bucket_connected: bool
bucket_error: str | None = None


@dataclass(frozen=True)
Expand All @@ -51,6 +52,7 @@ class SavedPapersProjection:
areas: tuple[SavedAreaProjection, ...]
bucket_connected: bool
bucket_migrated: bool
bucket_error: str | None = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -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)

Expand All @@ -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()
Expand Down Expand Up @@ -308,6 +312,7 @@ def list_grouped(
),
bucket_connected=listing.bucket_connected,
bucket_migrated=bucket_migrated,
bucket_error=listing.bucket_error,
)

def _require_bucket(
Expand All @@ -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.",
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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,
Expand Down
50 changes: 50 additions & 0 deletions backend/tests/test_bookmarks_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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."
)
6 changes: 6 additions & 0 deletions docs/adr/0018-paper-catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lib/api/account.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/views/SavedPapersView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,18 @@ const SavedPapersView: React.FC = () => {
Reconnect Hugging Face Bucket
</button>
</div>
) : showBucketMigration && query.data.bucket_error ? (
<div className="saved-bucket-migration">
<p>
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.
</p>
<button type="button" className="hf-signin-btn" onClick={authorizeBucket}>
Try the Bucket migration again
</button>
</div>
) : showBucketMigration ? (
<div className="saved-bucket-migration">
<p>
Expand Down
Loading