Thaalam 24x7
A lightweight music app for playback, discovery, personalised Mixes, and listening without interruption.
Recommendation engine#
Thaalam uses a deterministic, heuristic-based recommendation engine. Completed listening, early manual skips, genre preferences, seeded variation, and diversity constraints inform ranking and Mix generation. The browser-side module exports eight functions via window.ThaalamRecommendationEngine.
How recommendations flow#
Integration boundary: The flow describes the intended application pipeline. The supplied engine implements ranking, diversity, seeding, Mix planning, artist selection, and session counters; it does not itself detect playback completion, classify early skips, fetch catalogue tracks, or filter previously heard tracks from Mix discovery candidates.
What the engine learns#
| Listener action | Effect |
|---|---|
| Completes a track | When supplied to history / completedTracks, contributes positive artist and genre evidence. |
| Skips manually before the final 30% | When the application records this in skips, lowers exact-track and artist affinity. The 30% cutoff is an application rule, not an engine rule. |
| Moves to the next track near the end | Does not count as dislike feedback if the application does not record a skip. |
| Completes three tracks from one genre | Makes that genre eligible for a personalised genre Mix, provided the completion records are supplied. |
| Opens a Mix again | nextMixSession increments its session counter; the caller can incorporate that counter into a new seed and candidate ordering. |
Personalisation score#
For a candidate track (s), let (A(s)) be the artist tokens extracted from its artistName, (P(a)) the number of entries in the supplied history associated with artist (a), (K(a)) the number of entries in skips associated with (a), and (T(s)) the number of skipped entries whose normalised title and full artist string match (s).
\operatorname{Affinity}(s)=\sum_{a\in A(s)}\bigl[P(a)-1.5K(a)\bigr]-6T(s)The algorithm sorts candidate songs by descending affinity, breaking ties by their original input index. It subsequently tries to avoid artist repetition within a short rolling window. Scores are unbounded and are not probabilities, percentages, or predictions of whether a listener will like a song.
Worked example
Suppose the candidate is Night Drive — Artist A feat. Artist B, and the supplied event lists yield:
| Signal | Artist A | Artist B |
|---|---|---|
| Completed-history entries | 8 | 3 |
| Skip entries | 2 | 1 |
If this exact title and full artist string appears once in skips, the score is:
(8-1.5\times2)+(3-1.5\times1)-6\times1=0.5Without the exact-track skip, it would be (6.5). The exact-track penalty is deliberately stronger than a single artist-level penalty; no song or artist is permanently blacklisted by personalize.
Daily Mix logic#
Daily Mixes use completed listening only. Opening a track or sampling a few seconds should not change Mix eligibility, provided the application records only true completions in completedTracks.
For each genre (g), the engine calculates a play count and a position-weighted score:
C(g)=\sum_{i=0}^{m-1}\mathbf{1}[\operatorname{genre}(song_i)=g]G(g)=\sum_{i=0}^{m-1}\mathbf{1}[\operatorname{genre}(song_i)=g]\frac{1}{1+0.08i}Only genres with (C(g)\geq3) are eligible. Eligible genres are ranked by (G(g)), and up to five are selected for the next planned daily set. The weighting assumes index 0 is the newest completion; the engine does not sort timestamps itself.
The first eligible day shows a broad Thaalam Mix across genres with at least one completed track. On subsequent days, the saved plan produces a general Mix when more than one genre is planned, followed by numbered genre-specific Mixes. If only one genre qualifies, only its genre Mix is returned. The day and device identifier determine whether a stored plan can be reused.
Mix discovery flow#
Each new Mix session can surface fresh music when the caller combines the session counter with seed, fetches fresh candidates, and removes already completed or skipped tracks. These last two actions are not implemented inside the supplied engine.
Diversity rules#
- Prefer a different album from the previous five selected queue positions.
- Prefer a different full artist string from the previous two selected queue positions in
diversify. - Relax to album-only separation if no candidate meets both constraints.
- If none qualifies, select the first remaining candidate so the queue remains playable.
The separate personalize pass uses split artist tokens and a recent-two-artist-token check; the two passes therefore have different definitions of artist overlap.
Algorithm internals: mathematical and implementation specification#
This section documents the actual supplied JavaScript, including numerical constants, ordering semantics, and fallback behavior.
1. Input normalization and artist-token extraction#
The normalize helper converts nullish/falsy values to an empty string, trims surrounding whitespace, applies toLocaleLowerCase(), and collapses whitespace runs:
const normalize = (value) => String(value || '')
.trim().toLocaleLowerCase().replace(/\s+/g, ' ');
For artist counting, artistNames splits an artist string on commas, slashes, ampersands, and the words feat, featuring, with, or x (case-insensitive), then trims, drops empty tokens, and removes exact-string duplicates. This is heuristic parsing: Artist A & Artist B becomes two artists, but inconsistent punctuation or casing may cause collisions or missed matches. Deduplication occurs before lowercasing; differently cased artist tokens may still contribute twice to one song's score.
2. Deterministic seed: FNV-1a-style 32-bit hashing#
The seed function constructs the string
X=\operatorname{deviceId}\;||\;\texttt{"|"}\;||\;\operatorname{dayKey}\;||\;\texttt{"|"}\;||\;\operatorname{key}and initializes (h_0=2166136261). For each JavaScript UTF-16 code unit (c_i), it applies:
h_{i+1}=\bigl((h_i\oplus c_i)\times16777619\bigr)\bmod2^{32}The implementation uses Math.imul to obtain the low 32 bits of multiplication and >>> 0 to return an unsigned integer. This is an FNV-1a-style hash over UTF-16 code units, not an implementation of FNV-1a over UTF-8 bytes.
Properties: Identical input strings produce identical seeds; changing the device, day, or caller-supplied key generally changes the seed. Collisions are possible. The hash is neither cryptographically secure nor a user identifier protection mechanism.
3. Seeded shuffle: Mulberry32-style PRNG and Fisher–Yates#
shuffle(items, value) copies the input array and uses a small stateful 32-bit pseudorandom generator. On each draw it increments the state by hexadecimal 0x6D2B79F5, mixes the bits with XOR, shifts, and Math.imul, and converts the final unsigned integer into a number in ([0,1)):
u=\frac{\operatorname{uint32}(z)}{2^{32}}It then executes a descending Fisher–Yates shuffle:
j_i=\lfloor u_i(i+1)\rfloor,\quad i=n-1,n-2,\ldots,1and swaps elements (i) and (j_i). The original input array is not mutated. For fixed seed and array order, output order is reproducible. The pseudorandom generator is not suitable for security or cryptography. Fisher–Yates runs in (O(n)) time and (O(n)) copy space.
4. Affinity scoring: weighted implicit feedback#
For every entry in history, the engine adds one artist play for each extracted artist token. For every entry in skips, it adds one artist skip for each token and one exact-track skip for the key:
normalize(trackName) + "|" + normalize(artistName)
Empty title and artist together ("|") are excluded from the exact-track skip map. There is no time decay in the personalize score; recency is determined by whatever retention and ordering the caller applies to its history arrays. There is no separate genre, popularity, rating, or audio-feature term in this function.
The function first invokes the injected dedupe(songs) callback (default identity). It does not internally deduplicate candidates. When both history and skips are empty, it returns the deduped input directly without affinity sorting or artist anti-repeat mixing.
For nonempty feedback, scores are sorted descending, with original candidate index as a stable tie-breaker. During output construction, the engine selects the first remaining candidate with no artist token overlapping the last two entries of its accumulated recentArtists token list. If no candidate qualifies, it chooses the first remaining candidate.
Subtlety: recentArtists is a flattened list of artist tokens, not a list of songs. A collaboration can push several tokens into this window and change the effective artist-repeat horizon.
5. Genre weighting and eligibility#
The decay function is hyperbolic:
w(i)=\frac{1}{1+0.08i}| Completion index | Weight |
|---|---|
| 0 | 1.0000 |
| 1 | 0.9259 |
| 5 | 0.7143 |
| 10 | 0.5556 |
| 25 | 0.3333 |
| 50 | 0.2000 |
Unlike exponential decay, this function declines slowly and never reaches zero. The score counts repeated completions independently. Three completions of the same track can qualify a genre because eligibility counts events, not unique songs.
Worked example: If genre A occurs at positions (0,2,5), then
G(A)=1+\frac1{1.16}+\frac1{1.4}\approx2.5764If genre B occurs at (1,3,8), then
G(B)=\frac1{1.08}+\frac1{1.24}+\frac1{1.64}\approx2.3425Both genres qualify, but A ranks ahead of B. genreForSong is an injected callback, so the engine does not infer genre from audio, titles, or artist names.
6. Daily plan persistence and first-day lifecycle#
dailyMixes starts with a score record for every key in labels. Songs whose resolved genre is not a key in labels are ignored. If no genre has three completed plays, the function immediately returns [] and does not initialize the first-day record.
After eligibility is established, the engine reads storage.getItem(firstDayKey):
- If its JSON contains the same
deviceIdand a truthydayKey, the current day is considered the first Mix day only if the day keys match. - Otherwise, it writes
{ dayKey, deviceId }and treats the current day as the first Mix day. - If storage access or JSON parsing throws, it treats the call as a first-day call and returns the broad Mix.
On later days, it reads storageKey. If the stored dayKey and deviceId match and genres is an array, it keeps only genre values that still exist in labels. If no valid planned genres remain, it writes the current top five eligible genres. If storage fails, it uses the current ranking without persistence.
Important nuance: A previously saved plan is filtered against current label keys but is not rechecked for the three-play threshold. A genre may remain in today's saved plan after the listener's underlying profile changes. Also, the broad first-day Mix uses all genres with at least one completion, not only those with three or more.
7. Discovery artist scoring#
For a given Mix with mix.genres, the engine examines only songs in the supplied taste array whose genreForSong(song) matches a Mix genre. It scores each artist token with a second hyperbolic position weighting:
D(a\mid M)=\sum_{i=0}^{n-1}\mathbf{1}[\operatorname{genre}(song_i)\in M]\,\mathbf{1}[a\in A(song_i)]\frac{1}{1+0.06i}The engine sorts artists by descending discovery score, retains the top 14, applies a deterministic shuffle with the supplied value seed, and returns the first six artist display names. Therefore:
- The output contains up to six names, not song recommendations.
- The top-14 shortlist is affinity-driven; selection of six within it is seeded variation rather than score-weighted sampling.
- No artists are discovered outside the supplied taste history.
- No catalogue lookup, novel-artist similarity model, or candidate-track exclusion is implemented here.
- As with genre weighting, position 0 is assumed to be newest if recency weighting is desired.
8. Session counter and refresh behavior#
nextMixSession({ mixId, dayKey, storage, storageKey }) reads JSON state from storage. If the saved dayKey matches and sessions is an object, it reuses the counters; otherwise it starts with {}. For the selected Mix:
\operatorname{session}_{new}(m)=\max\bigl(0,\operatorname{Number}(\operatorname{session}_{old}(m))\;\text{or}\;0\bigr)+1The new value is persisted as { dayKey, sessions }. If storage throws, the fallback is a random integer from 1 through 1,000,000 inclusive. The fallback is not deterministic and may collide. Session numbers do not affect shuffle order unless the caller passes them into the seed context.
Example integration:
const engine = window.ThaalamRecommendationEngine;
const session = engine.nextMixSession({
mixId: mix.id,
dayKey,
storage: localStorage,
storageKey: 'thaalam:mix:sessions'
});
const value = engine.seed({
deviceId,
dayKey,
key: `mix:${mix.id}:session:${session}`
});
const artists = engine.discoveryArtists({
mix,
taste: completedTracks,
genreForSong,
value
});
// Application responsibility: fetch tracks for these artists,
// exclude completed/skipped track IDs, then build the queue.
9. Diversity selection as constrained greedy scheduling#
diversify processes a mutable copy of the input candidates, constructing an output queue one track at a time. Let (R) be remaining candidates, (L_5) the last five selected normalised album strings, and (L_2) the last two selected normalised full artist strings.
It chooses the earliest remaining candidate satisfying:
(\operatorname{album}(s)=\varnothing\ \lor\ \operatorname{album}(s)\notin L_5)
\ \land\
(\operatorname{artist}(s)=\varnothing\ \lor\ \operatorname{artist}(s)\notin L_2)If none satisfies both constraints, it chooses the earliest candidate meeting only the album constraint. If that also fails, it chooses the first remaining track. This is a greedy soft-constraint algorithm, not a global optimisation solver. It preserves the original candidate preference order as much as possible while introducing local variety.
The album and artist lists store empty strings too, but empty metadata is explicitly exempted from constraints. Different tracks with identical album names are treated as sharing an album even if they belong to different artists.
10. Computational complexity#
Let (n) be candidate tracks, (h) history entries, (k) skip entries, (t) taste entries, and (a) distinct artists. String processing costs depend on metadata lengths and artist-token counts.
| Function | Typical / upper-bound time | Additional space |
|---|---|---|
seed |
(O(L)), input string length | (O(L)) constructed string |
shuffle |
(O(n)) | (O(n)) |
diversify |
(O(n^2)) worst case | (O(n)) |
personalize |
(O(h+k+n\log n+n^2)) worst case, excluding injected dedupe and tokenisation |
(O(h+k+n)) |
dailyMixes |
(O(m+g\log g)), (g) label genres | (O(g)) |
discoveryArtists |
(O(t+a\log a)) | (O(a)) |
nextMixSession |
(O(q)) for JSON parse/serialization of (q) saved session entries | (O(q)) |
The two greedy queue passes can become quadratic because they repeatedly scan remaining/ranked and use splice. For modest browser queues this may be acceptable; very large catalogues should use bounded candidate pools, precomputed keys, or indexed scheduling.
11. Reproducibility, guarantees, and limitations#
| Property | Current behavior |
|---|---|
| Same seed and same ordered input | shuffle returns the same order. |
| Different session | Different order only when the caller incorporates session into the seed. |
| Positive feedback | Artist play counts increase linearly. |
| Negative feedback | Artist skips cost 1.5 each; exact-track skips cost 6 each. |
| Cold start | personalize returns deduped input unchanged; dailyMixes returns no Mix until a genre qualifies. |
| Duplicate songs | Removed only if caller supplies an effective dedupe function. |
| Artist parsing | Delimiter-based heuristics, not canonical artist IDs. |
| Genre inference | Supplied by genreForSong, not learned in this module. |
| Fresh Mix tracks | Must be fetched and filtered by surrounding application. |
| Cross-device profile | Not implemented by this browser module itself. |
| Storage errors | Daily Mixes and sessions have separate fallbacks; persistence is best-effort. |
12. Testing and evaluation#
Recommended unit tests include deterministic shuffle fixtures, hash stability, zero-feedback behavior, exact-track skip penalties, collaborator-artist parsing, empty metadata, three-play eligibility, first-day transition, saved-plan reuse, invalid JSON, blocked storage, session resets at midnight, and constrained queues with repeated albums.
For production measurement, track skip rate, completion rate, distinct artists per 20 tracks, distinct albums per 20 tracks, repeated-track rate, Mix return rate, and recommendation latency. These are proposed evaluation metrics, not metrics computed by the engine. Use replay tests on fixed histories before changing coefficients (1.5, 6, 0.08, 0.06) so changes can be compared against a reproducible baseline.
Storage and performance#
Listening state stays in browser storage by default. Maintenance runs when the browser is idle, so it does not interrupt playback or animation. Favourites, ratings, and account data are not removed by this cleanup.
| Stored data | Limit |
|---|---|
| Playback history | 160 tracks |
| Completed taste profile | 180 tracks |
| Skip profile | 100 tracks |
| Search cache | 24 recent entries |
| Track duration cache | 400 entries |
| Song metadata cache | 350 entries |
| Artist metadata cache | 220 entries |
These are application-level storage policies, as described in the project overview; the recommendation-engine module itself does not enforce these limits or perform idle cleanup. The limits aim to keep the app responsive while retaining useful listening context.
Architecture#
The app is a static HTML, CSS, and JavaScript client hosted through Cloudflare Pages and Worker routes.
| Part | Responsibility |
|---|---|
| Browser app | Home, Search, Library, Now Playing, player controls, and local state. |
| Recommendation engine | Ranking, Mix planning, discovery artist selection, seeded variation, and diversity. |
| Music routes | Same-origin search, song resolution, and autoplay support. |
| Cloudflare D1 | Persistent sessions and cross-browser ratings. |
| Service worker | Versioned app-shell caching and silent update delivery. |
| Optional relay | Catalogue forwarding when direct Worker access to the music source is unavailable. |
Google sign-in and ratings#
Google sign-in uses Google Identity Services. Configure a Web OAuth client with the deployed origin and local development origin as authorised JavaScript origins. Only the public client ID belongs in the client configuration; never add a client secret to this static app.
After sign-in, the app creates a persistent HttpOnly session in Cloudflare D1. Ratings can then sync for the same Google account across browsers. Without the backend configuration, local liked songs and device ratings continue to work in that browser.
Deployment#
Cloudflare Pages serves the static application and API routes for music search, song resolution, autoplay, ratings, and authentication sessions. Persistent sessions and synced ratings require a D1 database bound as DB.
Apply the migrations in the migrations folder in order before enabling account-backed ratings. Git-integrated Pages deployments use the routes in functions, while dashboard Direct Upload deployments use the root Worker file with the static assets.
An optional relay can be configured for catalogue requests when Cloudflare cannot reach the source service directly. Audio still streams from the music CDN.
Local development#
Start the project with its development script. Local middleware exposes the same music routes as production so the player follows the same browser flow.
Local development does not include a D1 binding. Persistent account sessions and synced ratings therefore require a deployed Cloudflare environment, while playback, search, liked songs, and local browser state remain available.
Privacy and security#
The recommendation engine does not transmit listening history on its own. Browser storage can be cleared, blocked, or changed by the user, so the app treats it as best-effort state rather than a secure source of truth.
The daily seed is only for stable variation. It is not a secret, authentication token, or security boundary. Track and artist metadata must always be handled as untrusted display content.
Documentation scope: the recommendation-engine internals are derived from the supplied JavaScript implementation. Product, infrastructure, storage-limit, and deployment details reflect the provided project description and should be verified against the full repository before release.