fix: a first watch state and a first Watch later survive two requests at once

The first checkpoint of an item and the final flush beside it both read no
state and both inserted; the loser failed on uq_plex_user_item. Two first saves
each made a Watch later list. Both are created by an ON CONFLICT DO NOTHING
insert and then read; a partial unique index holds one Watch later per user, and
the migration folds an existing second list into the first. Plex keeps one
per-item state map (rollup.item_state_map).
This commit is contained in:
2026-10-20 00:45:22 +02:00
parent b376373af5
commit 3a5212cd8a
11 changed files with 215 additions and 40 deletions
+19 -4
View File
@@ -12,7 +12,7 @@ from datetime import datetime, timezone
from sqlalchemy import select
from app.plex import library, queries, service
from app.plex import library, queries, rollup, service
from app.plex.models import PlexCollection, PlexItem, PlexLibrary, PlexShow, PlexState
from app.plex.query import LibraryFilters
@@ -71,9 +71,9 @@ def test_a_users_watch_state_is_theirs_alone(db, make_user):
_state(db, owner, it, status="watched")
assert queries.state(db, owner, it.id).status == "watched"
assert queries.state(db, stranger, it.id) is None
assert queries.states(db, stranger, [it.id]) == {}
assert set(queries.states(db, owner, [it.id])) == {it.id}
assert queries.states(db, owner, []) == {}
assert rollup.item_state_map(db, stranger, [it.id]) == {}
assert set(rollup.item_state_map(db, owner, [it.id])) == {it.id}
assert rollup.item_state_map(db, owner, []) == {}
def test_the_grid_shows_the_callers_state_and_hides_only_what_they_hid(db, make_user):
@@ -421,3 +421,18 @@ def test_only_the_owners_own_link_pushes_their_watch_state(db, make_user):
db.commit()
assert watch_sync.link_for_push(db, owner.id).id == link.id
assert watch_sync.link_for_push(db, other.id) is None
def test_a_first_write_that_lost_the_race_updates_the_winners_row(db, make_user):
"""The first checkpoint of an item and the `final` flush beside it both read "no state"; the one
that writes second must land on the row the first made, not fail on `uq_plex_user_item`."""
user = make_user()
it = _movie(db, _lib(db), "m-race")
_state(db, user, it, position_seconds=10) # the request that won, committed
st = service.checkpoint(db, user, it.id, None, 42, NOW, dirty=True) # read "none" before it
assert (st.position_seconds, st.synced_to_plex) == (42, False)
st = service.set_status(db, user, it.id, None, "hidden")
assert st.status == "hidden"
db.commit()
rows = db.scalars(select(PlexState).where(PlexState.item_id == it.id)).all()
assert [(r.position_seconds, r.status) for r in rows] == [(42, "hidden")]