The metrics card had one volume threshold doing two jobs. recMetricsLowVolume = 20 is a DISPLAY floor — below that a skip rate is anecdote — but the card then presented deltas as though it were also a DECISION floor. Those differ by an order of magnitude: detecting the ~13pp differences that matter needs ~133 plays per arm for 80% power at a=0.05. So Discover's taste-matched (59 plays) and random-unheard (70) both rendered as full-confidence rows with a bold delta beside them, and that comparison sits at p ~ 0.06. The card said "signal"; the arithmetic said "maybe". It produced a recommendation the data didn't support, and any reader with the same numbers would have made the same call. Deltas now carry a 95% margin of error and a `distinguishable` flag, computed server-side so both clients read the same arithmetic instead of each re-deriving it. Skip rate is a two-proportion difference; completion is Welch, which needs a variance — hence completion_sqsum in the query. It is the sum of squares rather than stddev_samp on purpose: raw source rows are merged into surface families in Go, and sums of squares combine across groups exactly whereas standard deviations cannot. recMetricsLowVolume is untouched. "Too thin to show" and "too thin to act on" are different questions. Web renders an indistinguishable delta as dimmed and prefixed "≈", with the range on hover and a legend explaining the glyph. Colour is withheld unless the delta clears its margin — colouring noise red is what made the old card misleading. Breakdown rows go through the same path; those are the thinnest samples on screen and where the old card misled most. Also fixes the admin trends view, which had the same problem worse: its "Latest skip"/"Latest completion" columns are one WEEK while the adjacent Plays column is the whole window. I misread exactly that and briefly concluded Deep cuts was the worst surface, from ~17 plays in a single week — over 180 days it is one of the best. Headers now name their period and the skip cell carries that week's play count. #2524: resolveArtist now recognises a duplicate-MBID unique violation as the expected condition it is, matching resolveAlbum. Two rows mapping to one MusicBrainz artist is a merge candidate, not a fault; without the branch it logged a generic warning plus a Postgres ERROR line on every scan, which teaches an operator to ignore database errors.
This commit is contained in:
@@ -39,6 +39,14 @@ type surfaceMetric struct {
|
||||
SkipRate float64 `json:"skip_rate"` // skips / plays, [0,1]
|
||||
AvgCompletion float64 `json:"avg_completion"` // mean completion ratio, [0,1]
|
||||
LowConfidence bool `json:"low_confidence"` // plays < recMetricsLowVolume
|
||||
// SkipDelta / CompletionDelta are this row's difference from the manual
|
||||
// baseline WITH its margin of error (#2495). nil on the baseline row
|
||||
// itself, and whenever the samples are too thin for a margin to mean
|
||||
// anything. Computed server-side so both clients read the same arithmetic
|
||||
// instead of each re-deriving it — and so `low_confidence` is no longer
|
||||
// mistaken for a decision threshold, which it never was.
|
||||
SkipDelta *metricDelta `json:"skip_delta,omitempty"`
|
||||
CompletionDelta *metricDelta `json:"completion_delta,omitempty"`
|
||||
// Breakdown splits the family into the pick-kind populations its
|
||||
// builder stamped (#1249, generalized #1270): For You's taste/fresh,
|
||||
// Discover's buckets, tier1-3 for tiered mixes — plus earlier plays
|
||||
@@ -119,6 +127,10 @@ type familyAccum struct {
|
||||
// completionSum is avg*count re-expanded, so merging N raw rows
|
||||
// reduces to a single weighted division at the end.
|
||||
completionSum float64
|
||||
// completionSqSum is the sum of squared completion ratios, which is what
|
||||
// makes the variance mergeable across raw source rows (#2495). Standard
|
||||
// deviations cannot be combined; sums of squares add exactly.
|
||||
completionSqSum float64
|
||||
}
|
||||
|
||||
func (a *familyAccum) add(row dbq.RecommendationSourceMetricsForUserRow) {
|
||||
@@ -126,6 +138,7 @@ func (a *familyAccum) add(row dbq.RecommendationSourceMetricsForUserRow) {
|
||||
a.skips += row.Skips
|
||||
a.completionN += row.CompletionN
|
||||
a.completionSum += row.AvgCompletion * float64(row.CompletionN)
|
||||
a.completionSqSum += row.CompletionSqsum
|
||||
}
|
||||
|
||||
func (a *familyAccum) metric() surfaceMetric {
|
||||
@@ -145,6 +158,33 @@ func (a *familyAccum) metric() surfaceMetric {
|
||||
return m
|
||||
}
|
||||
|
||||
// completionVariance is the sample variance of this family's completion ratios.
|
||||
func (a *familyAccum) completionVariance() float64 {
|
||||
return sampleVariance(a.completionSum, a.completionSqSum, a.completionN)
|
||||
}
|
||||
|
||||
// applyDeltas attaches baseline-relative deltas + margins to a metric.
|
||||
// Split out so every row — parent surfaces and breakdown rows alike — goes
|
||||
// through the identical arithmetic; a breakdown arm is exactly where the old
|
||||
// card was most misleading, because those are the thinnest samples on screen.
|
||||
func applyDeltas(m *surfaceMetric, acc *familyAccum, baseline *familyAccum) {
|
||||
if baseline == nil || baseline.plays == 0 {
|
||||
return
|
||||
}
|
||||
m.SkipDelta = proportionDelta(
|
||||
m.SkipRate, acc.plays,
|
||||
float64(baseline.skips)/float64(baseline.plays), baseline.plays,
|
||||
)
|
||||
baseMean := 0.0
|
||||
if baseline.completionN > 0 {
|
||||
baseMean = baseline.completionSum / float64(baseline.completionN)
|
||||
}
|
||||
m.CompletionDelta = meanDelta(
|
||||
m.AvgCompletion, acc.completionVariance(), acc.completionN,
|
||||
baseMean, baseline.completionVariance(), baseline.completionN,
|
||||
)
|
||||
}
|
||||
|
||||
// handleGetRecommendationMetrics implements GET /api/me/recommendation-metrics.
|
||||
// Bucketed per-surface-family outcomes for the caller over the last `days`
|
||||
// (default 30, capped at 365), grouped by surface intent and anchored by the
|
||||
@@ -214,7 +254,7 @@ func pickKindFamily(parent recFamily, kind string) recFamily {
|
||||
// Breakdown rows. Attached only when at least one attributed play
|
||||
// exists — an all-unattributed breakdown would just repeat the parent
|
||||
// row, and families that never stamp (radio, direct plays) stay flat.
|
||||
func pickKindBreakdown(picks map[string]*familyAccum) []surfaceMetric {
|
||||
func pickKindBreakdown(picks map[string]*familyAccum, baseline *familyAccum) []surfaceMetric {
|
||||
attributed := int64(0)
|
||||
for kind, acc := range picks {
|
||||
if kind != "" {
|
||||
@@ -227,7 +267,9 @@ func pickKindBreakdown(picks map[string]*familyAccum) []surfaceMetric {
|
||||
out := make([]surfaceMetric, 0, len(picks))
|
||||
for _, kind := range pickKindOrder {
|
||||
if acc, ok := picks[kind]; ok && acc.plays > 0 {
|
||||
out = append(out, acc.metric())
|
||||
m := acc.metric()
|
||||
applyDeltas(&m, acc, baseline)
|
||||
out = append(out, m)
|
||||
}
|
||||
}
|
||||
return out
|
||||
@@ -287,7 +329,8 @@ func bucketMetricsResponse(
|
||||
for _, acc := range families {
|
||||
if acc.fam.intent == g.intent {
|
||||
m := acc.metric()
|
||||
m.Breakdown = pickKindBreakdown(picks[acc.fam.key])
|
||||
applyDeltas(&m, acc, baseline)
|
||||
m.Breakdown = pickKindBreakdown(picks[acc.fam.key], baseline)
|
||||
group.Surfaces = append(group.Surfaces, m)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package api
|
||||
|
||||
import "math"
|
||||
|
||||
// Uncertainty on the deltas the recommendation-metrics card shows (#2495).
|
||||
//
|
||||
// Why this exists: the card had exactly one volume threshold,
|
||||
// recMetricsLowVolume = 20, and it was doing two jobs. Twenty plays is enough to
|
||||
// be worth DISPLAYING — below that a skip rate is anecdote — but it is nowhere
|
||||
// near enough to ACT on. Detecting the ~13pp differences that actually matter
|
||||
// needs roughly 133 plays per arm for 80% power at α=0.05.
|
||||
//
|
||||
// So Discover's taste-matched (59 plays) and random-unheard (70) both rendered as
|
||||
// full-confidence rows with a bold delta beside them, and that comparison sits at
|
||||
// p ≈ 0.06. The card said "signal"; the arithmetic said "maybe". It led directly
|
||||
// to a recommendation the data didn't support, and any reader with the same
|
||||
// numbers would have made the same call.
|
||||
//
|
||||
// The fix is to publish the margin of error next to the delta and flag when the
|
||||
// delta is smaller than it — i.e. not distinguishable from zero. Computed here,
|
||||
// server-side, so both clients agree rather than each re-deriving it.
|
||||
//
|
||||
// recMetricsLowVolume stays exactly as it was. This is a second, independent
|
||||
// signal, not a replacement: "too thin to show" and "too thin to act on" are
|
||||
// different questions and deserve different answers.
|
||||
|
||||
// deltaZ is the two-sided 95% normal critical value. Normal rather than
|
||||
// Student's t: at the sample sizes where a delta is worth acting on (n in the
|
||||
// hundreds) the difference is immaterial, and a household dashboard does not
|
||||
// need a t-table.
|
||||
const deltaZ = 1.96
|
||||
|
||||
// metricDelta is a difference from the baseline, with its uncertainty.
|
||||
//
|
||||
// Both figures are in PERCENTAGE POINTS, matching how the card reads them out —
|
||||
// a skip rate of 0.153 against a baseline of 0.270 is "-11.7", not "-0.117".
|
||||
type metricDelta struct {
|
||||
// DeltaPP is surface minus baseline. Negative skip is better; negative
|
||||
// completion is worse. The client owns that colouring.
|
||||
DeltaPP float64 `json:"delta_pp"`
|
||||
// MarginPP is the 95% margin of error on DeltaPP. Read the delta as
|
||||
// DeltaPP ± MarginPP.
|
||||
MarginPP float64 `json:"margin_pp"`
|
||||
// Distinguishable reports |DeltaPP| >= MarginPP: the interval excludes
|
||||
// zero, so the difference is worth reading as a difference. When false the
|
||||
// number may be pure noise no matter how large it looks.
|
||||
Distinguishable bool `json:"distinguishable"`
|
||||
}
|
||||
|
||||
// proportionDelta compares two rates (skips/plays) as a two-proportion
|
||||
// difference. Returns nil when either sample is empty, or when either rate is
|
||||
// degenerate (0 or 1) — a rate with no observed variation has an SE of 0 on its
|
||||
// side, which would report a spuriously narrow margin rather than an honest one.
|
||||
func proportionDelta(rate1 float64, n1 int64, rate2 float64, n2 int64) *metricDelta {
|
||||
if n1 <= 0 || n2 <= 0 {
|
||||
return nil
|
||||
}
|
||||
v1 := rate1 * (1 - rate1) / float64(n1)
|
||||
v2 := rate2 * (1 - rate2) / float64(n2)
|
||||
se := math.Sqrt(v1 + v2)
|
||||
if se <= 0 {
|
||||
// Both rates are 0 or both are 1. The delta is exactly zero and the
|
||||
// margin is meaningless; reporting nothing is more honest than
|
||||
// reporting certainty.
|
||||
return nil
|
||||
}
|
||||
return newDelta((rate1-rate2)*100, deltaZ*se*100)
|
||||
}
|
||||
|
||||
// meanDelta compares two means (average completion ratio) using Welch's
|
||||
// standard error, which does not assume equal variances between the two groups.
|
||||
//
|
||||
// Note the margins here are wider than intuition suggests, and that is correct:
|
||||
// completion is strongly bimodal — a play is either abandoned early (≈0.05) or
|
||||
// finished (≈1.0), with little in between — so its standard deviation is large
|
||||
// (~0.4) even though the mean looks stable.
|
||||
func meanDelta(mean1 float64, variance1 float64, n1 int64, mean2 float64, variance2 float64, n2 int64) *metricDelta {
|
||||
// Two observations minimum per side: a sample variance needs n-1 > 0.
|
||||
if n1 < 2 || n2 < 2 {
|
||||
return nil
|
||||
}
|
||||
se := math.Sqrt(variance1/float64(n1) + variance2/float64(n2))
|
||||
if se <= 0 || math.IsNaN(se) || math.IsInf(se, 0) {
|
||||
return nil
|
||||
}
|
||||
return newDelta((mean1-mean2)*100, deltaZ*se*100)
|
||||
}
|
||||
|
||||
func newDelta(deltaPP, marginPP float64) *metricDelta {
|
||||
return &metricDelta{
|
||||
DeltaPP: deltaPP,
|
||||
MarginPP: marginPP,
|
||||
// >= rather than >: a delta exactly equal to its margin sits on the
|
||||
// boundary, and calling the boundary "distinguishable" is the
|
||||
// conventional reading of a 95% interval that just excludes zero.
|
||||
Distinguishable: math.Abs(deltaPP) >= marginPP,
|
||||
}
|
||||
}
|
||||
|
||||
// sampleVariance recovers the sample variance from the aggregates the SQL
|
||||
// returns. sum is mean×n rather than a selected column, which keeps the query to
|
||||
// one extra expression.
|
||||
//
|
||||
// The subtraction can go very slightly negative through floating-point
|
||||
// cancellation when every observation is identical, so the result is clamped —
|
||||
// a negative variance would produce NaN downstream.
|
||||
func sampleVariance(sum, sqSum float64, n int64) float64 {
|
||||
if n < 2 {
|
||||
return 0
|
||||
}
|
||||
nf := float64(n)
|
||||
v := (sqSum - (sum * sum / nf)) / (nf - 1)
|
||||
if v < 0 {
|
||||
return 0
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestProportionDelta_ReproducesTheDiscoverCase(t *testing.T) {
|
||||
// The comparison that motivated #2495: Discover taste-matched (59 plays,
|
||||
// 15.3% skip) vs random-unheard (70 plays, 28.6%). A 13.3pp gap that the old
|
||||
// card rendered as a confident coloured number, sitting at p ≈ 0.06.
|
||||
d := proportionDelta(0.153, 59, 0.286, 70)
|
||||
if d == nil {
|
||||
t.Fatal("expected a delta for two real samples")
|
||||
}
|
||||
if math.Abs(d.DeltaPP-(-13.3)) > 0.1 {
|
||||
t.Errorf("DeltaPP = %.2f, want ≈ -13.3", d.DeltaPP)
|
||||
}
|
||||
// This is the assertion the whole task exists for: at these sample sizes the
|
||||
// margin swallows the difference.
|
||||
if d.Distinguishable {
|
||||
t.Errorf("13.3pp on n=59/70 reported as distinguishable (margin %.2f) — "+
|
||||
"this is exactly the false confidence #2495 set out to remove", d.MarginPP)
|
||||
}
|
||||
if d.MarginPP <= 13.3 {
|
||||
t.Errorf("MarginPP = %.2f, expected it to exceed the 13.3pp delta", d.MarginPP)
|
||||
}
|
||||
}
|
||||
|
||||
// Same effect size, ~10x the volume: now it is real. Proves the flag tracks
|
||||
// sample size rather than just the size of the gap.
|
||||
func TestProportionDelta_SameGapBecomesDistinguishableWithVolume(t *testing.T) {
|
||||
d := proportionDelta(0.153, 600, 0.286, 700)
|
||||
if d == nil {
|
||||
t.Fatal("expected a delta")
|
||||
}
|
||||
if !d.Distinguishable {
|
||||
t.Errorf("13.3pp on n=600/700 should be distinguishable (margin %.2f)", d.MarginPP)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProportionDelta_SignAndDirection(t *testing.T) {
|
||||
// Surface skips MORE than baseline -> positive delta (worse for skip rate).
|
||||
worse := proportionDelta(0.40, 500, 0.25, 500)
|
||||
if worse == nil || worse.DeltaPP <= 0 {
|
||||
t.Fatalf("expected a positive delta, got %+v", worse)
|
||||
}
|
||||
better := proportionDelta(0.10, 500, 0.25, 500)
|
||||
if better == nil || better.DeltaPP >= 0 {
|
||||
t.Fatalf("expected a negative delta, got %+v", better)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProportionDelta_EmptySamples(t *testing.T) {
|
||||
if d := proportionDelta(0.2, 0, 0.3, 100); d != nil {
|
||||
t.Errorf("n1=0 produced a delta: %+v", d)
|
||||
}
|
||||
if d := proportionDelta(0.2, 100, 0.3, 0); d != nil {
|
||||
t.Errorf("n2=0 produced a delta: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// Two degenerate rates have zero standard error, which would report a margin of
|
||||
// 0 and therefore "distinguishable" for a delta of exactly 0. Reporting nothing
|
||||
// is the honest answer.
|
||||
func TestProportionDelta_DegenerateRates(t *testing.T) {
|
||||
if d := proportionDelta(0, 50, 0, 50); d != nil {
|
||||
t.Errorf("both rates 0 produced a delta: %+v", d)
|
||||
}
|
||||
if d := proportionDelta(1, 50, 1, 50); d != nil {
|
||||
t.Errorf("both rates 1 produced a delta: %+v", d)
|
||||
}
|
||||
// One degenerate side is still informative — the other side carries variance.
|
||||
if d := proportionDelta(0, 200, 0.3, 200); d == nil {
|
||||
t.Error("one degenerate rate should still yield a delta")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMeanDelta(t *testing.T) {
|
||||
// Completion is bimodal, so ~0.16 variance (sd ≈ 0.4) is realistic.
|
||||
const v = 0.16
|
||||
thin := meanDelta(0.82, v, 59, 0.54, v, 70)
|
||||
if thin == nil {
|
||||
t.Fatal("expected a delta")
|
||||
}
|
||||
if math.Abs(thin.DeltaPP-28.0) > 0.1 {
|
||||
t.Errorf("DeltaPP = %.2f, want ≈ 28.0", thin.DeltaPP)
|
||||
}
|
||||
// 28pp is large enough to survive even a wide margin at this n.
|
||||
if !thin.Distinguishable {
|
||||
t.Errorf("28pp on n=59/70 with sd 0.4 should be distinguishable (margin %.2f)", thin.MarginPP)
|
||||
}
|
||||
// A small completion gap at the same volume should not be.
|
||||
small := meanDelta(0.56, v, 59, 0.54, v, 70)
|
||||
if small == nil {
|
||||
t.Fatal("expected a delta")
|
||||
}
|
||||
if small.Distinguishable {
|
||||
t.Errorf("2pp on n=59/70 reported as distinguishable (margin %.2f)", small.MarginPP)
|
||||
}
|
||||
}
|
||||
|
||||
// A sample variance needs at least two observations per side.
|
||||
func TestMeanDelta_NeedsTwoObservations(t *testing.T) {
|
||||
if d := meanDelta(0.8, 0.1, 1, 0.5, 0.1, 100); d != nil {
|
||||
t.Errorf("n1=1 produced a delta: %+v", d)
|
||||
}
|
||||
if d := meanDelta(0.8, 0.1, 100, 0.5, 0.1, 1); d != nil {
|
||||
t.Errorf("n2=1 produced a delta: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMeanDelta_ZeroVarianceBothSides(t *testing.T) {
|
||||
if d := meanDelta(0.8, 0, 50, 0.5, 0, 50); d != nil {
|
||||
t.Errorf("zero variance on both sides produced a delta: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSampleVariance(t *testing.T) {
|
||||
// Observations 0, 1: mean 0.5, sample variance 0.5.
|
||||
if got := sampleVariance(1.0, 1.0, 2); math.Abs(got-0.5) > 1e-9 {
|
||||
t.Errorf("sampleVariance = %v, want 0.5", got)
|
||||
}
|
||||
// Identical observations -> zero variance, and must not go negative through
|
||||
// floating-point cancellation.
|
||||
if got := sampleVariance(4.0, 4.0, 4); got != 0 {
|
||||
t.Errorf("identical observations gave variance %v, want 0", got)
|
||||
}
|
||||
if got := sampleVariance(0, 0, 1); got != 0 {
|
||||
t.Errorf("n=1 gave variance %v, want 0", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Clamping matters: a negative variance would become NaN in the square root and
|
||||
// propagate into the JSON as a null-ish number.
|
||||
func TestSampleVariance_NeverNegative(t *testing.T) {
|
||||
// sqSum slightly below sum²/n, as cancellation can produce.
|
||||
if got := sampleVariance(10.0, 24.999999999, 4); got < 0 {
|
||||
t.Errorf("variance went negative: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewDelta_BoundaryCountsAsDistinguishable(t *testing.T) {
|
||||
d := newDelta(5.0, 5.0)
|
||||
if !d.Distinguishable {
|
||||
t.Error("a delta exactly equal to its margin should count as distinguishable")
|
||||
}
|
||||
d = newDelta(4.999, 5.0)
|
||||
if d.Distinguishable {
|
||||
t.Error("a delta just inside its margin should not count as distinguishable")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user