Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { addBreadcrumb } from '@lucky/shared/utils/monitoring'
import { blendAutoplayTracks } from '../../../../../utils/music/queueManipulation'
import { applyStoredAutoplayPreference } from './autoplayPreference'
import { clearAutoplayPause } from '../../../../../utils/music/autoplay/skipCircuitBreaker'
import { clearSessionMoodCache } from '../../../../../utils/music/autoplay/replenisher'

export interface PostPlayBackgroundOpsInput {
queue: GuildQueue | null | undefined
Expand Down Expand Up @@ -75,6 +76,10 @@ export async function runPostPlayBackgroundOps(
clearAutoplayPause(guildId),
)

await runIsolated('clearSessionMoodCache', guildId, () =>
clearSessionMoodCache(guildId),
)

if (!hadQueueBeforePlay && queue) {
await runIsolated('applyStoredAutoplayPreference', guildId, () =>
withSingleRetry(() =>
Expand Down
1 change: 1 addition & 0 deletions packages/bot/src/utils/music/autoplay/autoplayContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ export interface AutoplayContext {
}
replayFrequentTrackIds?: Set<string>
replayFrequentArtists?: Set<string>
recentArtistIndices?: Map<string, number>
}
29 changes: 29 additions & 0 deletions packages/bot/src/utils/music/autoplay/candidateScorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ const SPOTIFY_PREFERRED_UNKNOWN_MULTIPLIER = 0.5
// artist replayed >2 times in the last 30 days. Bounded so it cannot flip
// genre vetoes (-Infinity) or dominate provenance-aware rankings.
const SCORE_REPLAY_COUNT_BOOST = 0.15
// Recency-decay penalty: applied to candidates whose artist appeared in the
// recent queue, scaled by how recently they appeared. Decays linearly to zero
// over a window of RECENCY_WINDOW_TRACKS. Bounded so it cannot flip genre
// vetoes (-Infinity) or override provenance-aware ordering.
const SCORE_RECENCY_DECAY_MAX = -0.15
const RECENCY_WINDOW_TRACKS = 10
Comment thread
LucasSantana-Dev marked this conversation as resolved.
Resolved
// Genre families dense/cohesive enough that a cross-family jump reads as drift.
// Used both for the cross-family penalty and the untagged-candidate fail-closed
// guard. Kept deliberately narrow (pop/soul are too broad to fail closed on).
Expand Down Expand Up @@ -200,6 +206,12 @@ export interface ScoringContext {
*/
replayFrequentTrackIds?: Set<string>
replayFrequentArtists?: Set<string>
/**
* Map of artist names (lowercased) to their queue position (0 = most recent)
* in the recent history. Used to calculate recency-decay penalty: artists
* that appeared recently get a penalty that decays to zero over RECENCY_WINDOW_TRACKS.
*/
recentArtistIndices?: Map<string, number>
}

export function calculateRecommendationScore(ctx: ScoringContext): {
Expand All @@ -224,6 +236,7 @@ export function calculateRecommendationScore(ctx: ScoringContext): {
genreContext = {},
replayFrequentTrackIds = new Set(),
replayFrequentArtists = new Set(),
recentArtistIndices = new Map(),
} = ctx
const candidateTags = genreContext.candidateTags ?? []
const currentTrackTags = genreContext.currentTrackTags ?? []
Expand Down Expand Up @@ -516,6 +529,22 @@ export function calculateRecommendationScore(ctx: ScoringContext): {
signals.push('replay frequent')
}

// Recency-decay penalty: candidates whose artist appeared in the recent
// queue receive a penalty that decays linearly to zero over a window of
// RECENCY_WINDOW_TRACKS. More recent = larger penalty, older = smaller
// penalty. Bounded and applied additively so it cannot flip hard vetoes
// or override provenance-aware ordering.
const recentIndex = recentArtistIndices.get(candidateArtist)
if (recentIndex !== undefined && recentIndex >= 0) {
// Linear decay: penalty = max * (1 - index/window), clamped to [0, max]
const decayFactor = Math.max(0, 1 - recentIndex / RECENCY_WINDOW_TRACKS)
const penalty = SCORE_RECENCY_DECAY_MAX * decayFactor
if (penalty !== 0) {
score += penalty
signals.push('recency decay')
}
}

// Soft genre-family penalty (formerly inside enrichWithAudioFeatures via
// Spotify's getArtistGenres). When both sides have Last.fm tags, score
// family overlap: same family → 0, no families known → −0.1, no overlap
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export type RecommendationSignal =
| 'discovery boost'
| 'energy match'
| 'replay frequent'
| 'recency decay'

export interface RecommendationBasis {
source: RecommendationSource
Expand Down
27 changes: 27 additions & 0 deletions packages/bot/src/utils/music/autoplay/replenisher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ async function _replenishQueue(
},
})
const recentArtists = buildRecentArtists(currentTrack, historyTracks)
const recentArtistIndices = buildRecentArtistIndices(currentTrack, historyTracks)
const artistFrequency = buildArtistFrequency(persistentHistory)

// Fetch the token FIRST (it may refresh), then audio features —
Expand Down Expand Up @@ -361,6 +362,7 @@ async function _replenishQueue(
genreContext: candidateGenreContext,
replayFrequentTrackIds: replayFrequency?.trackIds ?? new Set(),
replayFrequentArtists: replayFrequency?.artists ?? new Set(),
recentArtistIndices,
}
const candidates = await collectRecommendationCandidates(
autoplayContext,
Expand Down Expand Up @@ -613,6 +615,31 @@ function buildRecentArtists(
)
}

/**
* Build a map of artist names (lowercased) to their queue position (0 = most recent)
* for recency-decay scoring. Maps only the most recent N unique artists in the
* session history to keep memory usage bounded.
*/
function buildRecentArtistIndices(
currentTrack: Track,
historyTracks: Track[],
): Map<string, number> {
const indices = new Map<string, number>()
const allTracks = [currentTrack, ...historyTracks]
const seenArtists = new Set<string>()

// Iterate from most recent to oldest, assigning indices only to unique artists
for (let i = 0; i < allTracks.length; i++) {
const artist = allTracks[i].author?.toLowerCase()
if (artist && !seenArtists.has(artist)) {
indices.set(artist, i)
seenArtists.add(artist)
}
}

return indices
}

/**
* Look up Last.fm tags for the most recent unique artists in history and
* derive the dominant genre families. Returns a non-empty set only when at
Expand Down
Loading