From 528ea9df0c82c0ae3258f67b7bd117a646d5b91c Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 26 Nov 2026 23:59:09 -0500 Subject: [PATCH] fix(likes): unliking any copy of a song retires the listening context captured on another (#8078) A like is on the song: LikeTrack and UnlikeTrack change every copy sharing its song_key. The contextual like (the session captured while it played) is written on the copy that was playing, but an unlike soft-deleted only the copy it named. Unliking from the Liked list, which shows one copy per song, or from another album holding the song, left the context active, and the engine kept boosting candidates matching it. The soft-delete now covers every copy of the song, and the engine's reader counts only contexts whose song is still liked, as a backstop. Co-Authored-By: Claude Opus 5.5 --- internal/api/radio_test.go | 6 +++ internal/db/dbq/contextual_likes.sql.go | 27 +++++++---- internal/db/queries/contextual_likes.sql | 27 +++++++---- internal/playevents/contextual_likes_test.go | 47 ++++++++++++++++++++ internal/recommendation/candidates_test.go | 13 ++++-- 5 files changed, 101 insertions(+), 19 deletions(-) diff --git a/internal/api/radio_test.go b/internal/api/radio_test.go index 90720559..ddd7a944 100644 --- a/internal/api/radio_test.go +++ b/internal/api/radio_test.go @@ -273,6 +273,12 @@ func TestHandleRadio_ContextualMatch_BoostsRankingOverControl(t *testing.T) { // Insert a contextual_like on the target track whose stored vector matches // the rock vibe. Direct DB insert — we want full control over the vector // for this test. + // Both are liked (only a liked song's captured context counts), so the + // like itself favours neither and the contextual match is what differs. + if _, err := pool.Exec(context.Background(), + `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2), ($1, $3)`, user.ID, target.ID, control.ID); err != nil { + t.Fatalf("like target and control: %v", err) + } if _, err := pool.Exec(context.Background(), `INSERT INTO contextual_likes (user_id, track_id, session_vector) VALUES ($1, $2, $3)`, user.ID, target.ID, rockVecJSON); err != nil { diff --git a/internal/db/dbq/contextual_likes.sql.go b/internal/db/dbq/contextual_likes.sql.go index 32bdb7a6..93ac12bc 100644 --- a/internal/db/dbq/contextual_likes.sql.go +++ b/internal/db/dbq/contextual_likes.sql.go @@ -34,11 +34,12 @@ func (q *Queries) InsertContextualLike(ctx context.Context, arg InsertContextual } const listActiveContextualLikesForUser = `-- name: ListActiveContextualLikesForUser :many -SELECT track_id, session_vector -FROM contextual_likes -WHERE user_id = $1 - AND deleted_at IS NULL - AND session_vector IS NOT NULL +SELECT cl.track_id, cl.session_vector +FROM contextual_likes cl +WHERE cl.user_id = $1 + AND cl.deleted_at IS NULL + AND cl.session_vector IS NOT NULL + AND EXISTS (SELECT 1 FROM general_likes g WHERE g.user_id = cl.user_id AND g.track_id = cl.track_id) ` type ListActiveContextualLikesForUserRow struct { @@ -50,6 +51,9 @@ type ListActiveContextualLikesForUserRow struct { // non-null vectors. Cardinality is bounded by the user's actual like-while- // playing history — typically tens to low hundreds. Used by the engine to // compute contextual_match_score for the candidate pool. +// +// Only rows whose song is still liked count, so a context left active by +// an unlike that missed it can't keep boosting a song the user let go of. func (q *Queries) ListActiveContextualLikesForUser(ctx context.Context, userID pgtype.UUID) ([]ListActiveContextualLikesForUserRow, error) { rows, err := q.db.Query(ctx, listActiveContextualLikesForUser, userID) if err != nil { @@ -73,7 +77,11 @@ func (q *Queries) ListActiveContextualLikesForUser(ctx context.Context, userID p const softDeleteContextualLikesForUserTrack = `-- name: SoftDeleteContextualLikesForUserTrack :exec UPDATE contextual_likes SET deleted_at = now() -WHERE user_id = $1 AND track_id = $2 AND deleted_at IS NULL +WHERE user_id = $1::uuid + AND deleted_at IS NULL + AND (track_id = $2::uuid + OR track_id IN (SELECT t.id FROM tracks t + WHERE t.song_key = (SELECT s.song_key FROM tracks s WHERE s.id = $2::uuid))) ` type SoftDeleteContextualLikesForUserTrackParams struct { @@ -81,8 +89,11 @@ type SoftDeleteContextualLikesForUserTrackParams struct { TrackID pgtype.UUID } -// Marks all currently-active rows for (user, track) as deleted. Idempotent — -// already-deleted rows aren't re-touched. +// Marks the user's active rows for the song as deleted: every copy sharing +// the track's song_key, as UnlikeTrack removes the like from every copy. +// The context was captured on whichever copy was playing, which needn't be +// the one the unlike names. Idempotent — already-deleted rows aren't +// re-touched. func (q *Queries) SoftDeleteContextualLikesForUserTrack(ctx context.Context, arg SoftDeleteContextualLikesForUserTrackParams) error { _, err := q.db.Exec(ctx, softDeleteContextualLikesForUserTrack, arg.UserID, arg.TrackID) return err diff --git a/internal/db/queries/contextual_likes.sql b/internal/db/queries/contextual_likes.sql index c84fdb5f..917b9a68 100644 --- a/internal/db/queries/contextual_likes.sql +++ b/internal/db/queries/contextual_likes.sql @@ -3,19 +3,30 @@ INSERT INTO contextual_likes (user_id, track_id, session_vector, session_id) VALUES ($1, $2, $3, $4); -- name: SoftDeleteContextualLikesForUserTrack :exec --- Marks all currently-active rows for (user, track) as deleted. Idempotent — --- already-deleted rows aren't re-touched. +-- Marks the user's active rows for the song as deleted: every copy sharing +-- the track's song_key, as UnlikeTrack removes the like from every copy. +-- The context was captured on whichever copy was playing, which needn't be +-- the one the unlike names. Idempotent — already-deleted rows aren't +-- re-touched. UPDATE contextual_likes SET deleted_at = now() -WHERE user_id = $1 AND track_id = $2 AND deleted_at IS NULL; +WHERE user_id = sqlc.arg(user_id)::uuid + AND deleted_at IS NULL + AND (track_id = sqlc.arg(track_id)::uuid + OR track_id IN (SELECT t.id FROM tracks t + WHERE t.song_key = (SELECT s.song_key FROM tracks s WHERE s.id = sqlc.arg(track_id)::uuid))); -- name: ListActiveContextualLikesForUser :many -- Returns all the user's active (non-soft-deleted) contextual_likes with -- non-null vectors. Cardinality is bounded by the user's actual like-while- -- playing history — typically tens to low hundreds. Used by the engine to -- compute contextual_match_score for the candidate pool. -SELECT track_id, session_vector -FROM contextual_likes -WHERE user_id = $1 - AND deleted_at IS NULL - AND session_vector IS NOT NULL; +-- +-- Only rows whose song is still liked count, so a context left active by +-- an unlike that missed it can't keep boosting a song the user let go of. +SELECT cl.track_id, cl.session_vector +FROM contextual_likes cl +WHERE cl.user_id = $1 + AND cl.deleted_at IS NULL + AND cl.session_vector IS NOT NULL + AND EXISTS (SELECT 1 FROM general_likes g WHERE g.user_id = cl.user_id AND g.track_id = cl.track_id); diff --git a/internal/playevents/contextual_likes_test.go b/internal/playevents/contextual_likes_test.go index 83c53a23..d3a32074 100644 --- a/internal/playevents/contextual_likes_test.go +++ b/internal/playevents/contextual_likes_test.go @@ -75,3 +75,50 @@ func TestSoftDeleteContextualLikes_MarksActiveRowsDeleted(t *testing.T) { t.Errorf("deleted_at not set after SoftDelete") } } + +// An unlike reaches the context captured on any copy of the song: the like +// is on the song, and the heart can be tapped on a different copy than the +// one that was playing. +func TestSoftDeleteContextualLikes_ReachesEveryCopyOfTheSong(t *testing.T) { + f := newFixture(t, 200_000) + ctx := context.Background() + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + played := f.track + var album, artist pgtype.UUID + if err := f.pool.QueryRow(ctx, "SELECT album_id, artist_id FROM tracks WHERE id = $1", played).Scan(&album, &artist); err != nil { + t.Fatalf("read track: %v", err) + } + other, err := f.q.UpsertTrack(ctx, dbq.UpsertTrackParams{ + Title: "Track", AlbumID: album, ArtistID: artist, FilePath: "/tmp/track-fixture-copy.flac", DurationMs: 200_000, + }) + if err != nil { + t.Fatalf("copy: %v", err) + } + if _, err := f.pool.Exec(ctx, "UPDATE tracks SET song_id = $1 WHERE id = $2", played, other.ID); err != nil { + t.Fatalf("link copies: %v", err) + } + + _, _ = f.w.RecordPlayStarted(ctx, f.user, played, "c", time.Now().UTC()) + if _, err := f.q.LikeTrack(ctx, dbq.LikeTrackParams{UserID: f.user, TrackID: played}); err != nil { + t.Fatalf("like: %v", err) + } + if err := CaptureContextualLikeIfPlaying(ctx, f.q, f.user, played, logger); err != nil { + t.Fatalf("capture: %v", err) + } + + // Unliked through the other copy, as from another album holding the song. + if _, err := f.q.UnlikeTrack(ctx, dbq.UnlikeTrackParams{UserID: f.user, TrackID: other.ID}); err != nil { + t.Fatalf("unlike: %v", err) + } + if err := SoftDeleteContextualLikes(ctx, f.q, f.user, other.ID); err != nil { + t.Fatalf("SoftDelete: %v", err) + } + var active int + if err := f.pool.QueryRow(ctx, + "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND deleted_at IS NULL", f.user).Scan(&active); err != nil { + t.Fatalf("count: %v", err) + } + if active != 0 { + t.Fatalf("%d contextual likes still active after unliking the song", active) + } +} diff --git a/internal/recommendation/candidates_test.go b/internal/recommendation/candidates_test.go index b7c6d753..ccff0347 100644 --- a/internal/recommendation/candidates_test.go +++ b/internal/recommendation/candidates_test.go @@ -196,15 +196,22 @@ func trackTitles(cs []Candidate) []string { return out } -// helperInsertContextualLike inserts a contextual_like row with the given -// session_vector marshaled to JSON. Bypasses playevents.CaptureContextualLikeIfPlaying -// because we want full control over the stored vector for these unit tests. +// helperInsertContextualLike likes the track and inserts a contextual_like +// row with the given session_vector marshaled to JSON, as a like while +// playing does. Bypasses playevents.CaptureContextualLikeIfPlaying because we +// want full control over the stored vector for these unit tests. (Only a +// still-liked song's context counts, so the like has to be there too.) func helperInsertContextualLike(t *testing.T, f fixture, trackID pgtype.UUID, vec SessionVector) { t.Helper() raw, err := json.Marshal(vec) if err != nil { t.Fatalf("marshal: %v", err) } + if _, err := f.pool.Exec(context.Background(), + `INSERT INTO general_likes (user_id, track_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, + f.user, trackID); err != nil { + t.Fatalf("like: %v", err) + } if _, err := f.pool.Exec(context.Background(), `INSERT INTO contextual_likes (user_id, track_id, session_vector) VALUES ($1, $2, $3)`, f.user, trackID, raw); err != nil {