fix(subsonic): one listen is one play, and a daily mix played in a Subsonic app is credited to it
release / web (push) Successful in 1m23s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m16s
release / android (push) Successful in 4m50s
release / Build signed APK (push) Successful in 5m29s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Build + push container image (push) Successful in 17s
release / Verify release artifacts (tag releases only) (push) Skipped

A Subsonic app reports "now playing" when a song starts and "played" when
it ends. The played report used to close the now-playing row as a play of
its own and write a second one, so every listen counted twice, and as a
skip when the app sent the song's start time. The report now completes the
app's own row for that song. A late report for an earlier song no longer
cuts short the song playing now.

Subsonic's scrobble doesn't say where a song was played from, so Minstrel
remembers, per user and app, the daily mix the app last opened (for six
hours). A play of a song in that mix is credited to it: the mix's metrics
count it and its rotation moves on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 21:48:17 -05:00
co-authored by Claude Opus 5.5
parent 7f7e946bad
commit 333523b30e
8 changed files with 477 additions and 88 deletions
+140
View File
@@ -0,0 +1,140 @@
package playevents
import (
"context"
"testing"
"time"
"github.com/jackc/pgx/v5/pgtype"
"git.fabledsword.com/bvandeusen/minstrel/internal/db/dbq"
)
// userPlays is every play_events row of the fixture user, oldest first.
func userPlays(t *testing.T, f fixture) []dbq.PlayEvent {
t.Helper()
rows, err := f.pool.Query(context.Background(),
`SELECT id FROM play_events WHERE user_id = $1 ORDER BY started_at`, f.user)
if err != nil {
t.Fatalf("list plays: %v", err)
}
var ids []pgtype.UUID
for rows.Next() {
var id pgtype.UUID
if err := rows.Scan(&id); err != nil {
t.Fatalf("scan: %v", err)
}
ids = append(ids, id)
}
rows.Close()
out := make([]dbq.PlayEvent, 0, len(ids))
for _, id := range ids {
ev, err := f.q.GetPlayEventByID(context.Background(), id)
if err != nil {
t.Fatalf("get play: %v", err)
}
out = append(out, ev)
}
return out
}
// A Subsonic app reports "now playing" when a song starts and "played" when
// it ends. The pair is one listen, a full one, whether the report's time is
// the song's start (as several apps send it) or its end (or left out, so the
// server's clock, which is the end).
func TestSyntheticCompletedPlay_CompletesTheNowPlayingRow(t *testing.T) {
for _, tc := range []struct {
name string
reportAt time.Duration // after the song started
}{
{"report carries the start time", 0},
{"report carries the end time", 200 * time.Second},
} {
t.Run(tc.name, func(t *testing.T) {
f := newFixture(t, 200_000)
ctx := context.Background()
start := time.Now().UTC().Add(-10 * time.Minute).Truncate(time.Millisecond)
if _, err := f.w.RecordPlayStarted(ctx, f.user, f.track, "dsub", start); err != nil {
t.Fatalf("now playing: %v", err)
}
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "", start.Add(tc.reportAt)); err != nil {
t.Fatalf("played: %v", err)
}
plays := userPlays(t, f)
if len(plays) != 1 {
t.Fatalf("got %d play rows for one listen, want 1", len(plays))
}
p := plays[0]
if p.WasSkipped {
t.Error("a song played to the end is recorded as a skip")
}
if p.CompletionRatio == nil || *p.CompletionRatio != 1 {
t.Errorf("completion ratio = %v, want 1", p.CompletionRatio)
}
if !p.StartedAt.Time.Equal(start) {
t.Errorf("started_at = %v, want the now-playing time %v", p.StartedAt.Time, start)
}
if want := start.Add(200 * time.Second); !p.EndedAt.Valid || !p.EndedAt.Time.Equal(want) {
t.Errorf("ended_at = %v, want %v", p.EndedAt.Time, want)
}
})
}
}
// An app that reports a song as played after the next one has started must
// not cut the next one short: it stays open, still playing.
func TestSyntheticCompletedPlay_LeavesALaterSongPlaying(t *testing.T) {
f := newFixture(t, 200_000)
ctx := context.Background()
track, err := f.q.GetTrackByID(ctx, f.track)
if err != nil {
t.Fatalf("track: %v", err)
}
next, err := f.q.UpsertTrack(ctx, dbq.UpsertTrackParams{
Title: "Next", AlbumID: track.AlbumID, ArtistID: track.ArtistID,
FilePath: "/tmp/track-fixture-next.flac", DurationMs: 180_000,
})
if err != nil {
t.Fatalf("next track: %v", err)
}
songStart := time.Now().UTC().Add(-10 * time.Minute)
nextStart := songStart.Add(200 * time.Second)
if _, err := f.w.RecordPlayStarted(ctx, f.user, next.ID, "dsub", nextStart); err != nil {
t.Fatalf("now playing next: %v", err)
}
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "", songStart); err != nil {
t.Fatalf("played: %v", err)
}
open, err := f.q.GetOpenPlayEventForUser(ctx, f.user)
if err != nil {
t.Fatalf("the next song is no longer playing: %v", err)
}
if open.TrackID != next.ID {
t.Errorf("open play is %v, want the next song", open.TrackID)
}
if n := len(userPlays(t, f)); n != 2 {
t.Errorf("got %d play rows, want 2 (the reported song and the one playing)", n)
}
}
// A play reported as coming from a daily mix is credited to it: the row
// carries the mix as its source and the mix's rotation counts the song.
func TestSyntheticCompletedPlay_CreditsTheMix(t *testing.T) {
f := newFixture(t, 200_000)
seedSystemSnapshot(t, f, "for_you", "fresh")
ctx := context.Background()
if err := f.w.RecordSyntheticCompletedPlay(ctx, f.user, f.track, "dsub", "for_you", time.Now().UTC()); err != nil {
t.Fatalf("played: %v", err)
}
plays := userPlays(t, f)
if len(plays) != 1 || plays[0].Source == nil || *plays[0].Source != "for_you" {
t.Fatalf("plays = %+v, want one play from for_you", plays)
}
if plays[0].PickKind == nil || *plays[0].PickKind != "fresh" {
t.Errorf("pick_kind = %v, want fresh", plays[0].PickKind)
}
st, err := f.q.GetRotationState(ctx, dbq.GetRotationStateParams{UserID: f.user, PlaylistKind: "for_you"})
if err != nil || len(st.PlayedTrackIds) != 1 {
t.Errorf("for_you rotation = %v (%v), want the song counted", st.PlayedTrackIds, err)
}
}
+106 -80
View File
@@ -57,8 +57,8 @@ type StartedResult struct {
// RecordPlayStarted: in one transaction, auto-close any prior open row for
// the user, FindOrCreate the play_session, insert the new play_event,
// return its id and session id. Source-agnostic — kept for the Subsonic
// shim (frozen API), which never originates from a system playlist.
// return its id and session id. The play has no source; a caller that knows
// which surface the play came from uses RecordPlayStartedWithSource.
func (w *Writer) RecordPlayStarted(
ctx context.Context,
userID, trackID pgtype.UUID,
@@ -144,60 +144,63 @@ func (w *Writer) RecordPlayStartedWithSource(
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
return err
}
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
if err != nil {
return err
}
var clientIDPtr *string
if clientID != "" {
clientIDPtr = &clientID
}
var sourcePtr *string
if source != "" {
sourcePtr = &source
}
var pickKind *string
if systemPlaylistSources[source] {
pickKind, err = lookupSystemPickKind(ctx, q, userID, trackID, source)
if err != nil {
return err
}
}
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
UserID: userID,
TrackID: trackID,
SessionID: sessionID,
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
ClientID: clientIDPtr,
Source: sourcePtr,
PickKind: pickKind,
DeviceClass: strPtrOrNil(deviceClass),
})
if err != nil {
return err
}
out.PlayEventID = ev.ID
out.SessionID = sessionID
// Capture session vector for the just-inserted row.
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
return err
}
if systemPlaylistSources[source] {
if err := q.AppendRotationPlayed(ctx, dbq.AppendRotationPlayedParams{
UserID: userID,
PlaylistKind: source,
TrackID: trackID,
}); err != nil {
return err
}
}
return nil
var err error
out, err = w.openPlay(ctx, q, userID, trackID, clientID, source, deviceClass, at)
return err
})
return out, err
}
// openPlay inserts a started play_event inside the caller's transaction. It
// finds or creates the listening session, stamps a system-playlist play's
// pick_kind, captures the session vector, and adds the track to that
// playlist's rotation so its shuffle prefers what is still unplayed.
func (w *Writer) openPlay(
ctx context.Context,
q *dbq.Queries,
userID, trackID pgtype.UUID,
clientID, source, deviceClass string,
at time.Time,
) (StartedResult, error) {
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
if err != nil {
return StartedResult{}, err
}
var pickKind *string
if systemPlaylistSources[source] {
pickKind, err = lookupSystemPickKind(ctx, q, userID, trackID, source)
if err != nil {
return StartedResult{}, err
}
}
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
UserID: userID,
TrackID: trackID,
SessionID: sessionID,
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
ClientID: strPtrOrNil(clientID),
Source: strPtrOrNil(source),
PickKind: pickKind,
DeviceClass: strPtrOrNil(deviceClass),
})
if err != nil {
return StartedResult{}, err
}
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
return StartedResult{}, err
}
if systemPlaylistSources[source] {
if err := q.AppendRotationPlayed(ctx, dbq.AppendRotationPlayedParams{
UserID: userID,
PlaylistKind: source,
TrackID: trackID,
}); err != nil {
return StartedResult{}, err
}
}
return StartedResult{PlayEventID: ev.ID, SessionID: sessionID}, nil
}
// RecordPlayEnded closes a play_event with duration + computed completion
// ratio. Applies the skip rule (AND of completion < threshold AND
// duration_played < threshold) — both conditions must hold for the row to
@@ -308,13 +311,39 @@ func (w *Writer) RecordPlaySkipped(
})
}
// RecordSyntheticCompletedPlay writes a start+end pair for a Subsonic
// scrobble?submission=true call. ended_at = at + track.duration_ms,
// duration_played_ms = track.duration_ms, was_skipped = false.
// sameListenWindow is how far apart a Subsonic app's "now playing" and its
// "played" report for the same song may be and still be one listen. The
// report's time is the song's start in some apps and its end (or omitted,
// so the server's clock) in others, and a song can sit paused, so the
// window is wide. A second listen of the same song always opens its own
// row first, since the app reports "now playing" again, so a wide window
// can't merge two listens.
const sameListenWindow = 6 * time.Hour
// within reports whether a and b are no more than d apart, in either order.
func within(a, b time.Time, d time.Duration) bool {
gap := a.Sub(b)
return gap <= d && gap >= -d
}
// RecordSyntheticCompletedPlay records a Subsonic scrobble?submission=true
// call: one completed listen, duration_played_ms = track.duration_ms,
// was_skipped = false.
//
// Subsonic apps report "now playing" (submission=false, which opened a row
// through RecordPlayStarted) when a song starts and "played" when it ends.
// When the user's open row is that same song, that row is the listen and is
// completed in place. Otherwise a completed row is written from at. An open
// row for a different song is closed first only when it started before at:
// one that started after it is the song playing now, which an app reporting
// this one late must not cut short.
//
// source names the system playlist the listen came from, or is "" when
// unknown; it only applies when a new row is written.
func (w *Writer) RecordSyntheticCompletedPlay(
ctx context.Context,
userID, trackID pgtype.UUID,
clientID string,
clientID, source string,
at time.Time,
) error {
var playEventID pgtype.UUID
@@ -324,36 +353,33 @@ func (w *Writer) RecordSyntheticCompletedPlay(
if err != nil {
return err
}
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
open, err := q.GetOpenPlayEventForUser(ctx, userID)
hasOpen := err == nil
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return err
}
sessionID, err := playsessions.FindOrCreate(ctx, q, userID, at, clientID, w.sessionTimeout)
if err != nil {
return err
}
var clientIDPtr *string
if clientID != "" {
clientIDPtr = &clientID
}
ev, err := q.InsertPlayEvent(ctx, dbq.InsertPlayEventParams{
UserID: userID,
TrackID: trackID,
SessionID: sessionID,
StartedAt: pgtype.Timestamptz{Time: at, Valid: true},
ClientID: clientIDPtr,
})
if err != nil {
return err
}
playEventID = ev.ID
if err := w.captureSessionVector(ctx, q, ev.ID, sessionID, at); err != nil {
return err
startedAt := at
switch {
case hasOpen && open.TrackID == trackID && within(open.StartedAt.Time, at, sameListenWindow):
playEventID = open.ID
startedAt = open.StartedAt.Time
default:
if hasOpen && !open.StartedAt.Time.After(at) {
if err := w.autoClosePriorOpen(ctx, q, userID, at); err != nil {
return err
}
}
started, err := w.openPlay(ctx, q, userID, trackID, clientID, source, "", at)
if err != nil {
return err
}
playEventID = started.PlayEventID
}
ratio := 1.0
dur := track.DurationMs
_, err = q.UpdatePlayEventEnded(ctx, dbq.UpdatePlayEventEndedParams{
ID: ev.ID,
EndedAt: pgtype.Timestamptz{Time: at.Add(time.Duration(track.DurationMs) * time.Millisecond), Valid: true},
ID: playEventID,
EndedAt: pgtype.Timestamptz{Time: startedAt.Add(time.Duration(track.DurationMs) * time.Millisecond), Valid: true},
DurationPlayedMs: &dur,
CompletionRatio: &ratio,
WasSkipped: false,
+1 -1
View File
@@ -286,7 +286,7 @@ func TestRecordPlaySkipped_AlwaysSkipFlagAndSkipEventRow(t *testing.T) {
func TestRecordSyntheticCompletedPlay_WritesBothRows(t *testing.T) {
f := newFixture(t, 200_000)
now := time.Now().UTC()
if err := f.w.RecordSyntheticCompletedPlay(context.Background(), f.user, f.track, "feishin", now); err != nil {
if err := f.w.RecordSyntheticCompletedPlay(context.Background(), f.user, f.track, "feishin", "", now); err != nil {
t.Fatalf("synthetic: %v", err)
}
rows, _ := f.pool.Query(context.Background(),