Repository navigation
feat: serve partial listings, page instead of scroll, and fan out a listing's tracks - #10
Merged
Merged
Conversation
Three changes to one subsystem, specced together because they interlock: partials are the degraded mode that pagination still needs, and fan-out only makes sense once a listing is complete enough to be worth caching. The finding that shaped it: the browser is not the data source. normalize already parses pathfinder bodies; scrolling is only how the page is provoked into fetching more of them. So both the 8-15s and the "25 of 50" are the same scroll heuristic, and replacing it with offset pagination issued from inside the page fixes both without taking on Spotify token handling. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Nine tasks in three phases, each ending in an independently testable deliverable. Task 6 carries a live check against the playlist that fails today, because Phase 1 would otherwise mask a pagination that did not work. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Self-review caught two defects. `declaredTotalFrom` was called in Task 6 and defined nowhere, which the plan rules call a plan failure outright. And several test snippets invented helpers -- `recordedFromFixture`, `extractFromCapture` -- where the suite already has `fixture`, `albumEntityResponse`, `albumTrackItem`, `playlistItem` and `playlistPageResponse`. An implementer following the invented names would have built a second harness beside the real one. Also corrects the album fixture id to 6ymZBbRSmzAvoSGmwAFoxm. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Wire ?partial=allow through the route: handleEntity now takes a
partialAllowed flag, read from the query string in route registration.
For listing kinds (album, playlist) when the caller has not opted in,
withCache is given an acceptsCached predicate that refuses a cached
entry with complete: false, so a strict request re-produces rather than
being handed someone else's cached partial. Tracks are exempt -- they
carry no `complete` field, so the predicate is never applied to them.
After the cache lookup, a short listing (complete: false) increments
sleevenote_partial_listings_total{type,served} and, absent the opt-in,
502s with extraction_incomplete -- unchanged from today's default
behavior, since a truncated listing must not silently look like a
complete one. The value is cached either way, so an opt-in caller
arriving later gets it without paying for the scrape again.
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
recordResponses now also listens for the first pathfinder POST that carries an offset variable and keeps it verbatim as a QueryTemplate (url, headers, full body) on the returned Capture. Everything that authenticates the call -- bearer token, client token, persisted-query hash -- is already in the page's own request, so it is harvested rather than constructed. withOffset(template, offset, limit) returns a copy of that template with only variables.offset/limit changed, leaving the original and everything else (auth headers, operationName, persisted-query extensions) untouched. Task 6 will use it to page past the scroll heuristic's shortfall. The request listener is attached and detached in the same places as the existing response listener, since a listener left on a pooled page is a per-lease leak. Capture gained a required `template` field, so two logging.test.ts literals needed `template: null` to keep typechecking -- evidenceFrom itself only reads navStatus/responses and is unaffected at runtime. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
…etwork Extract the "is this the windowed query worth repeating" decision out of onRequest into isWindowedQuery(url, body), a pure function, and have onRequest call it instead of inlining the condition. A silent false-negative here would make Task 6's pagination loop fall back to the scroll heuristic -- today's broken behaviour -- with nothing to show it happened, now that Phase 1 serves a short listing as a legitimate partial result. That deserves direct unit coverage, not only a live network check. isWindowedQuery is false for a non-pathfinder URL, a pathfinder URL with no variables at all, and a pathfinder URL whose variables has no offset (the entity-header query); true only when variables.offset is present. The postDataJSON()-throws-on-non-JSON case stays in onRequest, as before, with a comment explaining why it isn't part of the predicate -- not restructuring the listener just to test it. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Repeat the page's own windowed pathfinder query at each remaining offset
rather than scrolling a virtualized list and hoping it fetches more. The
scroll heuristic was both symptoms at once: it picked its container by
walking `querySelectorAll('*')` for the largest scrollable element, and it
cost 200 iterations x 350ms plus a 3s settle to come up short anyway.
Today's Top Hits returned 25 of 50 declared tracks.
Two things had to hold for the responses to be usable. The fetches are
issued from inside the page, so the session, cookies and tokens are the
page's own -- we repeat its request, we never construct one. And they
arrive through the same `page.on('response')` listener as the ones the page
fetched for itself, so nothing downstream can tell pagination from
scrolling; `normalize` and the whole fixture corpus are untouched.
The body reads now have to be waited on rather than guessed at. The entity
race resolves on the response *event*, which fires before the body has been
pulled across, and scrolling only ever got away with reading `totalCount`
afterwards because its 3s settle covered the gap. Pagination has no settle
and needs the total immediately, so `recordResponses` keeps the read
promises and awaits the ones it provoked -- once before computing the total,
once after the loop so the last window is not dropped.
The scroll loop stays as the fallback, entered when no windowed query was
harvested. It is not dead code: it is the path that comes up short, which
is why partial listings shipped before this.
MAX_PAGES bounds the loop. The total it walks toward is a number Spotify
supplies, and an unbounded loop against that is a denial of service handed
to us. A window that fails to fetch breaks the loop rather than failing the
extraction -- a short listing is a `complete: false` result, not a 502.
Measured against live Spotify, cold cache: Today's Top Hits 50/50 complete
in ~3.2s over three runs (was `extraction_incomplete`, 25 of 50); album
5s5svl5DzlSmEvkjuL8Upw 60/60; a 200-track playlist recovered in full across
seven pages in 4.5s.
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
A page fetch that failed mid-loop broke out and left a short listing with nothing in the logs. `complete: false` alone cannot tell an operator "Spotify declared 50 and every window came back fine" apart from "window 2 of 4 threw" -- and since partial listings shipped, the second is handed to an opt-in caller looking exactly like the first. A truncated listing that reads as a whole one is the failure this service exists to prevent, so it should not be reintroduced one rung down. Warn with the window's position, its offset, the limit and the declared total, then break as before. The break is still right: a partial listing is the correct outcome, it just should not be a silent one. `console.warn` and not a request logger because extraction has no logger handle -- failures carry `ExtractionEvidence` to the HTTP layer instead, and that route is closed here precisely because this path returns rather than throws. store.ts reports a connection error the same way, for the same reason. `id` is the correlation key. Only the first line of the error: Playwright folds a page-side stack into `message`, and those frames point into Spotify's bundle rather than ours. Verified by routing every pathfinder request with offset > 0 to abort against a live 200-track playlist: [extract] playlist 37i9dQZF1DWXRqgorJj26U: window 1 of 7 failed at offset 25 (limit 25, declared total 200) -- listing will be short: page.evaluate: TypeError: Failed to fetch (api-partner.spotify.com) RESULT items=25/200 tracks=25 complete=false Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
An album lists its tracks with `album: null` -- repeating the parent across 60 entries would be noise. Caching them verbatim under `v1:track:<id>` would answer a later `/v1/track/:id` lookup with a record that has lost its album, which is worse than not caching it at all. `tracksToCache` enriches album tracks with their parent so every writer produces an equivalent record, meaning fan-out (Task 8) can overwrite freely with no read-before-write. Playlist tracks already carry their album and pass through unchanged. Podcast episodes, which a playlist can also hold, are dropped: their url is /episode/<id> rather than /track/<id>, so they are not a valid /v1/track/:id response. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
An album or playlist response already contains every track in it, fully resolved, but those tracks were thrown away as far as the cache is concerned -- a later /v1/track/:id for one of them paid for a whole browser scrape it didn't need. handleEntity now fans each listing's tracks (via Task 7's tracksToCache) out to their own v1:track:<id> entries after a produce, using the track TTL rather than the listing's. Best effort: fan-out is fired without being awaited into the response path, and each write is individually caught and logged at debug rather than propagated, so one failed write can't abandon the rest and none of them can turn a successful listing response into a failure. Partial listings (complete: false) fan out too -- the tracks that did arrive are real -- so this is not gated on completeness, only on the response having actually reached the caller (a strict caller's 502 for a short listing returns before the fan-out call, same as before). Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Fan-out was placed after the completeness check, so it never ran when a strict caller got a 502 for a short listing -- only when the response actually reached the caller as a 200. That was wrong: whether the caller opted into a partial listing governs what the caller receives, not what we learned from the scrape. A short listing is cached even on the 502 path, precisely so a later opt-in caller doesn't re-pay for the scrape; fan-out is that identical argument applied to the tracks the listing already contains, and having the two disagree would mean a strict request caches the listing but discards its tracks, for no reason anyone could state. It also costs nothing to be consistent here -- fan-out is fire-and-forget, so an error response gains no latency from it. Move the fan-out call above the completeness block so it runs for every listing response, partial or not, strict caller or not. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Explains, in design-notes.md's existing voice, that the completeness check itself did not change -- a shortfall is now reported as complete: false instead of thrown, and the caller (via ?partial=allow) decides what that means. Documents why partials are opt-in (a truncated listing looks exactly like a complete one), why a cached partial is refused rather than 502'd for a strict caller (it keeps the retry path the never-cache rule protected), and why the scroll loop stays as a fallback rather than being deleted (pagination narrows how often a listing comes back short; it doesn't close the possibility). Adds a short pointer in captured-shapes.md distinguishing the fixture probe (tools/capture.ts, still scroll-based) from production's harvested-template pagination, since that section previously read as describing the only way pagination happens. README documents ?partial=allow, declaredItems and complete. docs/examples/album.json and docs/examples/playlist.json were re-recorded live against a locally running instance (Redis via Docker, Playwright's Chromium installed for this session) -- not hand-edited. Verified against the "Done means" bar in the task brief along the way: GET /v1/playlist/37i9dQZF1DXcBWIGoYBM5M -> 200, 50/50 tracks, complete: true, ~3.7s. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
docs/examples/README.md listed every field its committed fixtures carry except the two new ones -- a field table missing the fields that carry a shortfall is worse than no table, and the out-of-repo Rust client that will next model this contract reads exactly this table. Adds declaredItems and complete with the same meaning-and-nullability register the rest of the table uses. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
design-notes.md's "scroll loop's new status" section welded two distinct degraded paths into one causal claim: it said a mid-loop navigation or token failure falls back to scrolling. It does not. src/extract.ts only takes the scroll branch when no pathfinder template was harvested at all -- decided up front, before pagination runs. A mid-loop window failure instead breaks out of the pagination loop and lets the short recorded list flow through as complete: false, per the code comment beside it and the design doc's own "decision 1's partial handling remains live after this lands". Splits the section into the two paths it actually describes: no template to page with (why the scroll loop survives) and a window failing mid-loop (why the partial-listing policy stays load-bearing after pagination lands). Same conclusion -- pagination doesn't remove the need for partials -- now resting on the path that actually produces it. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
The waiter loop exits on an accepted entry or a published failure, and on nothing else. A holder that produces a *partial* succeeds: it writes a fresh entry and publishes no failure. A strict waiter -- one passing acceptsCached -- therefore had neither exit available, and polled every 50ms for the entire produceBudgetMs (150s by default: ~6000 iterations, ~12k Redis reads) before falling through and producing anyway. Impossible before partial listings: a waiter took whatever was written. The design doc's "single-flight still holds ... a strict and an opt-in caller racing the same cold key produce once" does not hold for this case, and the same document's "a cached partial reads as a miss to it, so it re-produces" is the behaviour this restores -- a refused entry ends the wait rather than extending it. Covering test: 'stops waiting and produces once the holder writes a partial it refuses'. It fails on the old code with 'expected 2013 to be less than 1000' -- the full budget, spent waiting for something that had already happened. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
Two defects in the same call, both introduced with fan-out. `tracksToCache(entity)` sat in the `for...of` head, outside the try. The call is `void`ed, so anything it throws is an unhandled rejection, and index.ts installs no `unhandledRejection` handler -- Node's default terminates the process. The value it reads is only cast, never validated (readEntry tolerates corrupt JSON, not wrong-shaped JSON), so a listing with no `tracks` array is reachable and fatal. It now runs inside its own try and logs a warn, which is a louder register than the per-write debug below it because a listing that malformed is a shape change, not a write that missed. Fan-out also ran unconditionally after withCache, so a cache HIT on a 50-track playlist re-issued 50 sequential Redis SETs writing back what it had just read, on every request for the whole 4-hour TTL. The design doc says "after a successful album or playlist produce", and `hit === 'miss'` is exactly that: produceAndCache returns 'miss' only after produce() resolved, and returns 'fresh'/'stale' with a staleError on the fallback path. The call stays where it is, above the completeness block, so the strict-caller 502 path still fans out -- that path produced, so it is a miss. Covering tests: 'does not crash the process on a listing with no track list' (vitest reports the unhandled rejection and fails the run on the old code) and 'fans out on a produce, not again on every cache hit'. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
…g loop
Three causes produce a short listing and only one of them left a trace. A
window failing mid-loop already warns; the other two said nothing at all:
- no template was harvested, so the scroll fallback ran. This is the risk the
fallback exists to absorb ("Spotify changes how the web player issues
pathfinder queries"), and silently degrading to the old behaviour is how a
fallback stops being a fallback and becomes the only path.
- nothing declared a total, so `pageOffsets` asked for nothing and no windows
were fetched. The quietest of the three: with no declared total the verdict
is `complete: true` by definition ("we cannot tell, so do not claim a
shortfall"), so nothing in the response marks it either.
Both are `console.warn` in the same register and format as the existing
mid-loop line, for the same reason: this path deliberately does not throw, so
the ExtractionEvidence route to the HTTP layer is closed.
Also adds the integration coverage the design doc asked for and that never
landed. `isWindowedQuery`'s unit tests judge request bodies the test itself
wrote -- they prove the predicate is self-consistent, never that a request
shaped like the web player's own satisfies it, which is the actual risk. The
new test drives a real browser page that issues one genuine-shaped pathfinder
POST (method, JSON body, operationName, variables.offset/limit,
persisted-query hash, bearer and client-token headers), and asserts the whole
path: offsets [0, 2, 4] walked to a declared total of 6, every repeat
carrying the harvested bearer, and a complete six-track listing out the far
end. The page has no scrollable container, so a failed harvest cannot be
rescued -- sabotaging isWindowedQuery to return false fails it with
'expected [ 0 ] to deeply equal [ 0, 2, 4 ]'.
Fixture-driven rather than live: tests/live.smoke.test.ts is opt-in behind
SLEEVENOTE_LIVE and its album case already passes whether pagination or the
scroll fallback did the work, so a live test would neither run in CI nor
assert the harvest. The genuine request shape is what carries the risk here,
and that is reproduced exactly.
Co-Authored-By: Claude & Lothrop (cycle.five@proton.me)
Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
… held §4 said "Single-flight still holds: the lock is keyed on the entity, not the caller's strictness, so a strict and an opt-in caller racing the same cold key produce once." That was already false when `acceptsCached` landed: a strict waiter behind a holder that produced a partial always refused it and produced a second time. fe1faad changed how long that took (50ms instead of the whole 150s produceBudgetMs), not whether it happened. The bullet directly above it -- "a strict request behind a cached partial re-produces" -- says the same thing and contradicts it. Rewritten to claim what the design actually delivers: the lock still stops two callers producing the same answer concurrently, but a strict caller and an opt-in caller are not asking the same question, so the second produce is the intended behaviour rather than a lost invariant. docs/design-notes.md already states it this way. This is a spec, not a note: it is what the crack-sleevenote and cracktunes follow-ups will read. An invariant asserted in a document and not held by the code is the same failure this service exists to prevent, one level up. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
A feature: Spotify listings that came back short are now serveable to a caller that asks for them, the scroll heuristic that made them come back short is replaced by offset pagination, and a listing's tracks are cached under their own ids. `src/version.ts` reads this at startup, so the bump is the whole change. Co-Authored-By: Claude & Lothrop (cycle.five@proton.me) Claude-Session: https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Implements
docs/superpowers/specs/2026-09-08-partial-listings-and-in-page-pagination-design.md. Bumps to 0.4.0.The bug this starts from
Measured against the deployed
0.3.1on 2026-09-07:/v1/playlist/37i9dQZF1DXcBWIGoYBM5M(Today's Top Hits)extraction_incomplete, 25 of 50, 8–15scomplete: true, 50 of 50, ~3.2s/v1/album/5s5svl5DzlSmEvkjuL8UpwLarge editorial playlists were effectively unplayable, and the cause was not the parsing.
normalize.tsalready reads Spotify's internal pathfinder GraphQL responses — the browser was never the data source. It established a session and provoked those queries by scrolling a virtualised list up to 200 times at 350ms a step plus a 3s settle, choosing its scroll container by walkingquerySelectorAll('*')for the largest scrollable element. That heuristic was both symptoms: the 8–15s cold resolve, and the shortfall when it stopped early.Three changes, one subsystem
1. Partial listings are opt-in. A shortfall is reported on the listing as
complete: falsealongsidedeclaredItems, rather than thrown.?partial=allowserves it as a 200; without the flag a short listing still 502s exactly as before.withCachegained anacceptsCachedpredicate, so a strict caller treats a cached partial as a miss and re-produces instead of being handed something it did not ask for.Opt-in rather than always-200 because
design-notes.mdis right that a truncated playlist looks exactly like a complete one — serving partials by default would re-create the failure the completeness check exists to catch, for every consumer that does not know to look. Policy belongs to the caller; the service reports facts.2. Pagination replaces scrolling. The page's own pathfinder request is harvested as a template and repeated with increasing offsets from inside the page, so the responses arrive through the existing
page.on('response')listener into the sameRecorded[].normalize.ts, the counting rules and the whole recorded-fixture corpus are untouched. The scroll loop is retained as the fallback when no template can be harvested — it is not dead code.3. Fan-out caching. A listing's tracks are written to
v1:track:<id>. Album tracks are enriched with their parent album first — they list withalbum: nullby design, so caching them verbatim would put album-less records where a later track lookup reads them. Podcast episodes are skipped: their url is/episode/<id>and they are not valid track responses.Why the phases shipped in this order
Pagination makes partials rare, not impossible — a navigation failure or a token expiring mid-loop still truncates. So partials are the degraded mode pagination still needs, which is why they landed first.
That ordering also creates the hazard this branch had to contain: once a short listing is a legitimate response, any failure of pagination looks like the feature working. It caught the plan itself — the original snippet fired
sawEntityData()beforeawait response.json(), sorecordedwas still empty when the race resolved, which would have meant a null declared total, zero fetches, and the same 25-track listing served as a perfectly valid partial. Caught in implementation, fixed by reading bodies through a promise array awaited both before the total is computed and after the loop.Containment now: strict callers still get a 502,
partialListings{served}moves either way, and threeconsole.warnlines distinguish "a window failed" from "no template was harvested" from "the declared total was never found".Verification
tsc --noEmitclean.FLUSHALLbetween, all 50/50.recordResponsesdirectly, rather than inferring it from a green result.offset > 0pathfinder request toabort('failed'), so the page loads and exactly the pagination windows die.Every task was reviewed independently, then the whole branch was reviewed as one change. That final pass found the two seams no single task owned — a strict waiter could stall for the full 150s produce budget, and fan-out fired on cache hits rather than on produce — plus a crash path where a wrong-shaped Redis value would throw synchronously inside a
void-invoked async function with nounhandledRejectionhandler. All fixed and re-reviewed.Known follow-ups, not in this PR
isWindowedQueryaccepts any pathfinder POST carryingvariables.offset; if a carousel query won that race we would page the wrong operation. Live runs passed, but the ordering is not guaranteed.v1:cache keys predate the required fields. A TypeScript required field is not a wire guarantee — values from Redis reach the route through a cast, so entries written before this branch serve withoutdeclaredItems/completeuntil they expire. The Rust client will model them as required.ExtractionIncompleteErroris now unthrowable but keeps its routing arms, soscrape_failures{reason="extraction_incomplete"}reports zero forever.?partial=trueand?partial=1silently mean strict.Downstream
crack-sleevenoteneeds to modeldeclaredItems/completeand add the request flag; cracktunes then opts in and can say "queued 25 of 50" instead of refusing the link. Neither is in scope here.🤖 Generated with Claude Code
https://claude.ai/code/session_01F8PrF3gizKqXCStjCuWL3d