Files
minstrel/internal/recsettings/service_test.go
T
bvandeusenandClaude Opus 5.5 cfdbfa30e3
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m4s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m5s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m35s
release / Build signed APK (push) Canceled after 3m53s
test(backup, scrobble, playevents, recsettings, apierror, auth, providers): merge repeated cases (#8299)
- backup: schema coverage's three tests and the three AWS signing
  examples, one table each.
- scrobble: Qualifies' six boundary tests; the ListenBrainz client's
  refusal mapping, twelve tests of the same rule across three calls, one
  table over call x status; the two similarity lookups' success and URL
  tests, one table.
- playevents: the skip rule's three plays share one fixture. Dropped
  TestRecordPlayEnded_SubThreshold_NoEnqueue: the writer only calls
  scrobble.MaybeEnqueue, whose own test and Qualifies' table hold that
  case; the qualifying-play test still proves the writer calls it.
- recsettings: the three tag-scale tests share one database reset.
- apierror: Error() and From, one test each; auth: RequireAdmin's three.
- providers: GetJSON's not-found and transient answers, one table. Its
  two 401 tests expected the same answer with and without
  TreatAuthAsTransient, which changes only the error's text; the table
  says so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:16:20 -05:00

224 lines
7.6 KiB
Go

package recsettings
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"testing"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
)
func newService(t *testing.T, pool *pgxpool.Pool) *Service {
t.Helper()
s, err := New(context.Background(), pool, slog.New(slog.NewTextHandler(io.Discard, nil)))
if err != nil {
t.Fatalf("recsettings.New: %v", err)
}
return s
}
func auditRows(t *testing.T, pool *pgxpool.Pool) []struct {
Scope, Action string
Changes []fieldChange
} {
t.Helper()
rows, err := pool.Query(context.Background(),
`SELECT scope, action, changes FROM recommendation_tuning_audit ORDER BY id`)
if err != nil {
t.Fatalf("query audit: %v", err)
}
defer rows.Close()
var out []struct {
Scope, Action string
Changes []fieldChange
}
for rows.Next() {
var scope, action string
var raw []byte
if err := rows.Scan(&scope, &action, &raw); err != nil {
t.Fatalf("scan audit: %v", err)
}
var changes []fieldChange
if err := json.Unmarshal(raw, &changes); err != nil {
t.Fatalf("unmarshal audit changes: %v", err)
}
out = append(out, struct {
Scope, Action string
Changes []fieldChange
}{scope, action, changes})
}
return out
}
func TestNew_SeedsShippedDefaults(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
if got := s.Weights(ScopeRadio); got != ShippedRadioWeights() {
t.Errorf("radio weights = %+v, want shipped defaults", got)
}
if got := s.Weights(ScopeDailyMix); got != ShippedDailyMixWeights() {
t.Errorf("daily_mix weights = %+v, want shipped defaults", got)
}
if got := s.Taste(); got != ShippedTasteTuning() {
t.Errorf("taste tuning = %+v, want shipped defaults", got)
}
// Seeding must not write audit rows — nothing changed.
if rows := auditRows(t, pool); len(rows) != 0 {
t.Errorf("boot reconcile wrote %d audit rows, want 0", len(rows))
}
}
func TestUpdateProfile_PersistsAndAudits(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
if err := s.UpdateProfile(context.Background(), ScopeRadio,
map[string]float64{"taste_weight": 2.5, "skip_penalty": 3.0}); err != nil {
t.Fatalf("UpdateProfile: %v", err)
}
got := s.Weights(ScopeRadio)
if got.TasteWeight != 2.5 || got.SkipPenalty != 3.0 {
t.Errorf("weights = %+v, want taste 2.5 / skip 3.0", got)
}
// The other profile is untouched.
if s.Weights(ScopeDailyMix) != ShippedDailyMixWeights() {
t.Error("daily_mix must be unaffected by a radio update")
}
// Values survive a fresh boot (persisted, not just cached), and the
// reconcile's ON CONFLICT DO NOTHING doesn't clobber tuned rows.
s2 := newService(t, pool)
if got := s2.Weights(ScopeRadio); got.TasteWeight != 2.5 {
t.Errorf("rebooted taste_weight = %v, want 2.5", got.TasteWeight)
}
rows := auditRows(t, pool)
if len(rows) != 1 {
t.Fatalf("audit rows = %d, want 1", len(rows))
}
if rows[0].Scope != ScopeRadio || rows[0].Action != "update" || len(rows[0].Changes) != 2 {
t.Errorf("audit row = %+v, want radio/update with 2 changes", rows[0])
}
// Changes are field-sorted: skip_penalty before taste_weight.
if rows[0].Changes[0].Field != "skip_penalty" || rows[0].Changes[0].New != 3.0 {
t.Errorf("changes[0] = %+v, want skip_penalty → 3.0", rows[0].Changes[0])
}
}
func TestUpdateProfile_Validation(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
cases := []struct {
name string
scope string
patch map[string]float64
want error
}{
{"unknown scope", "banana", map[string]float64{"taste_weight": 1}, ErrUnknownScope},
{"unknown field", ScopeRadio, map[string]float64{"vibes": 1}, ErrUnknownField},
{"over bound", ScopeRadio, map[string]float64{"taste_weight": 11}, ErrOutOfRange},
{"negative jitter", ScopeRadio, map[string]float64{"jitter_magnitude": -0.1}, ErrOutOfRange},
}
for _, c := range cases {
if err := s.UpdateProfile(context.Background(), c.scope, c.patch); !errors.Is(err, c.want) {
t.Errorf("%s: err = %v, want %v", c.name, err, c.want)
}
}
if s.Weights(ScopeRadio) != ShippedRadioWeights() {
t.Error("rejected patches must not partially apply")
}
if rows := auditRows(t, pool); len(rows) != 0 {
t.Errorf("rejected patches wrote %d audit rows, want 0", len(rows))
}
}
func TestUpdateTaste_CurveOrderingEnforced(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
// Moving neutral above full must reject on the PATCHED result.
err := s.UpdateTaste(context.Background(), map[string]float64{"engagement_neutral": 0.95})
if !errors.Is(err, ErrOutOfRange) {
t.Fatalf("err = %v, want ErrOutOfRange (curve ordering)", err)
}
// A coherent multi-point move is fine.
if err := s.UpdateTaste(context.Background(), map[string]float64{
"engagement_neutral": 0.40, "engagement_full": 0.95, "half_life_days": 30,
}); err != nil {
t.Fatalf("UpdateTaste: %v", err)
}
cfg := s.TasteConfig()
if cfg.HalfLifeDays != 30 || cfg.Engagement.NeutralCompletion != 0.40 {
t.Errorf("taste config = %+v, want tuned values", cfg)
}
// WindowDays scales with the half-life at the shipped ratio.
if cfg.WindowDays != 30*3.6 {
t.Errorf("WindowDays = %v, want %v", cfg.WindowDays, 30*3.6)
}
}
// The three tag scales take a value in [0, 1]: an in-range one reaches both
// the stored settings and the taste config the profile builder reads, and
// one outside it is refused.
func TestUpdateTaste_TagScales(t *testing.T) {
s := newService(t, dbtest.Pool(t))
for _, tc := range []struct {
key string
stored, built func() float64
}{
{"enriched_tag_scale", func() float64 { return s.Taste().EnrichedTagScale }, func() float64 { return s.TasteConfig().EnrichedTagScale }},
{"era_scale", func() float64 { return s.Taste().EraScale }, func() float64 { return s.TasteConfig().EraScale }},
{"mood_scale", func() float64 { return s.Taste().MoodScale }, func() float64 { return s.TasteConfig().MoodScale }},
} {
if err := s.UpdateTaste(context.Background(), map[string]float64{tc.key: 0.8}); err != nil {
t.Fatalf("%s = 0.8: %v", tc.key, err)
}
if tc.stored() != 0.8 || tc.built() != 0.8 {
t.Errorf("%s: stored %v, taste config %v; want 0.8 in both", tc.key, tc.stored(), tc.built())
}
if err := s.UpdateTaste(context.Background(), map[string]float64{tc.key: 1.5}); !errors.Is(err, ErrOutOfRange) {
t.Errorf("%s = 1.5: err = %v, want ErrOutOfRange", tc.key, err)
}
}
}
func TestReset_RestoresShippedAndAudits(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
// Reset with nothing changed is a no-op (no audit row).
if err := s.Reset(context.Background(), ScopeDailyMix); err != nil {
t.Fatalf("no-op reset: %v", err)
}
if rows := auditRows(t, pool); len(rows) != 0 {
t.Fatalf("no-op reset wrote audit rows")
}
if err := s.UpdateProfile(context.Background(), ScopeDailyMix,
map[string]float64{"similarity_weight": 4}); err != nil {
t.Fatalf("UpdateProfile: %v", err)
}
if err := s.Reset(context.Background(), ScopeDailyMix); err != nil {
t.Fatalf("Reset: %v", err)
}
if s.Weights(ScopeDailyMix) != ShippedDailyMixWeights() {
t.Error("reset must restore shipped defaults")
}
rows := auditRows(t, pool)
if len(rows) != 2 || rows[1].Action != "reset" {
t.Fatalf("audit rows = %+v, want update then reset", rows)
}
}
func TestUpdate_NoOpWritesNoAudit(t *testing.T) {
pool := dbtest.Pool(t)
s := newService(t, pool)
shipped := ShippedRadioWeights()
if err := s.UpdateProfile(context.Background(), ScopeRadio,
map[string]float64{"taste_weight": shipped.TasteWeight}); err != nil {
t.Fatalf("UpdateProfile: %v", err)
}
if rows := auditRows(t, pool); len(rows) != 0 {
t.Errorf("no-op update wrote %d audit rows, want 0", len(rows))
}
}