diff --git a/README.md b/README.md index 422216a..6604d01 100644 --- a/README.md +++ b/README.md @@ -260,43 +260,34 @@ Remaining limitations: ### Scalability -The brief puts no ceiling on catalog size, so the search path is measured against -synthetic catalogs much larger than the real one (100,000 and 1,000,000 albums), -in separate performance databases that no deployment touches. Headline numbers at -one million albums: - -| Operation | 100,000 | 1,000,000 | -| --------------------------------------------------- | ------: | --------: | -| Selective artist search, relevance order | 2.6 ms | 11.7 ms | -| Broad search that matches every row | 16.3 ms | 83.7 ms | -| Complete broad `searchAlbums` request (with facets) | ~100 ms | ~580 ms | -| Page 500,000 rows in, cursor | - | 254 ms | -| Page 500,000 rows in, `OFFSET` | - | 1184 ms | -| Same page, row comparison plus a matching index | - | 0.08 ms | - -What that says: - -- Sorting, filtering and faceting stay in SQL, so the cost of one page does not - depend on how many pages came before it. -- Cursor paging discards before sorting instead of producing and throwing away - skipped rows, so it does not grow with depth the way `OFFSET` does: 254 ms - against 1184 ms at 500,000 rows in. It is not constant time, though - with no - index on the sort key it still scans and sorts the tail. -- A matching `(lower(title), id)` index - 47 MB at one million albums - only pays - off together with the row comparison `(a, b) > (x, y)` that turns it into an - index condition: 0.08 ms. With the predicate `searchAlbums` runs today, an OR, - the same index gives 322 ms, slower than the 254 ms without it. The index and - the predicate have to change together. -- The GIN index is worth 5-6x on selective search, and is correctly bypassed for - a query that matches most of the catalog. -- Neither the composite indexes nor the row comparison for the album sorts are in - the schema yet - the seven sort modes would need several indexes, each costing - write time and 47 MB. That work is - [#74](https://git.ntnu.no/IT2810-H26/T19-Project-2/issues/74). - -The method, the full tables, the query plans and the reproduction steps are in -[docs/scalability.md](docs/scalability.md). The scripts are read-only and -committed: `server/scripts/benchmark.sh` runs all of them. +The search path is measured against synthetic catalogs of 100,000 and 1,000,000 +albums in separate performance databases. At one million albums, selective artist +search took 11.7 ms, while a broad search matching every row took 83.7 ms. A full +broad `searchAlbums` request with facets took about 580 ms because counts and +facets cover the full matching set. + +Issue #74 adds composite cursor indexes for title, release year and rating sorts. +At a 500,000-row depth, a local benchmark measured indexed cursor pages at +0.09–8.01 ms; the earlier OR predicates took 274 ms–9.70 s, and `OFFSET` took +79–752 ms. The six indexes occupy about 508 MiB on a million-row catalog. Their +individual sizes are measured with `pg_relation_size`: + +| Sort index | Size | +| ---------------------------------- | ------: | +| `album_title_lower_id_idx` | 88 MiB | +| `album_title_lower_desc_id_idx` | 88 MiB | +| `album_release_year_asc_id_idx` | 68 MiB | +| `album_release_year_desc_id_idx` | 68 MiB | +| `album_average_rating_asc_id_idx` | 94 MiB | +| `album_average_rating_desc_id_idx` | 102 MiB | + +A million-row seed took 151 s with the indexes on PostgreSQL 18.6. Importing the +500-album MusicBrainz snapshot into that catalog took 6.43 s (500 new, 0 +matched). The earlier seed-only measurement before the indexes was 88.91 s. +These timings are hardware-dependent; [the method, query plans and reproduction steps](docs/scalability.md) +explain the measurements and tradeoffs. The benchmark runner is +`server/scripts/benchmark.sh`; the cursor-index benchmark modifies ratings only +in a disposable database whose name ends in `_perf`. ### Accessibility diff --git a/docs/scalability.md b/docs/scalability.md index d09bf26..23019dd 100644 --- a/docs/scalability.md +++ b/docs/scalability.md @@ -10,10 +10,11 @@ This document holds the method, the full tables and the plans behind them. ## Method -- PostgreSQL 18.3, Fedora, 15 GB RAM developer laptop, unix socket, warm cache. - Every query was run five times and the median is reported; paging and HTTP - were run three times because they take longer. Timings vary by roughly 10-30 % - between runs on this machine. +- Earlier search/filter measurements used PostgreSQL 18.3 on Fedora (15 GB RAM, + unix socket); the #74 cursor-index measurements used PostgreSQL 18.6 on macOS + through Homebrew. The #74 500,000-row plans are single local runs, so timings + vary with cache and hardware. Use the query plans and relative work as the + primary evidence, not the exact milliseconds. - 100,000 and 1,000,000 deterministic albums. Seeding took **10 s** and **95 s**. The 100,000-album database is 41 MB with a 11 MB GIN index; the 1,000,000-album database is 350 MB with a 75 MB GIN index (489 MB total). @@ -23,12 +24,12 @@ This document holds the method, the full tables and the plans behind them. dataset. The 500,000-row case is a deep page and needs the 1,000,000-album database, so it is passed explicitly with `-v offset=500000`. A depth larger than the table is rejected rather than measured against an unset cursor. -- The scripts are committed and read-only: `server/scripts/benchmark.sh` runs all - of them. It checks the name in the URL _and_ asks the server for - `current_database()`, because a `dbname` parameter or a service file can point - the connection somewhere else; both must end in `_perf`. The check matters - because the index experiments take an exclusive lock on `album`. Seeding is a - separate, destructive step and is deliberately not part of the script. +- `server/scripts/benchmark.sh` checks the name in the URL and asks the server + for `current_database()`, because a `dbname` parameter or service file can + point the connection somewhere else; both must end in `_perf`. Most benchmark + queries only read data, but `paging-index-perf.sql` writes a deterministic + `average_rating` pattern so rating sorts include rated and unrated rows. + Seeding and importing are separate from the benchmark. - These results were measured on a laptop, not on the VM. The VM runs the same PostgreSQL major version, but the numbers are hardware-specific and should be read as orders of magnitude and plan shapes rather than as VM guarantees. @@ -68,12 +69,12 @@ Without the index PostgreSQL falls back to a parallel sequential scan that reads every row and discards all but the matches. The ratio is not larger because the synthetic artist name repeats often; a rarer term gains more. -## Paging depth: cursor vs OFFSET +## Baseline before #74: cursor vs OFFSET `server/scripts/paging-perf.sql` compares the keyset page `searchAlbums` runs with the `OFFSET` alternative, for the same rows and the same order (`TITLE_ASC`). -The keyset predicate is the one `afterCursor` builds in +Before #74, `afterCursor` used the following predicate in `server/src/search/search.ts`: ```sql @@ -108,65 +109,58 @@ and at 500,000 the sort spills 12 MB to disk. The cursor page does not do that, which is why it is slightly _faster_ at 500,000 than at 50,000 - the filter leaves fewer rows to sort. -It is still not constant time, and the reason is worth stating plainly: there is -no index on the sort key, so the keyset query also scans and sorts the remaining -rows. Keyset is faster because it discards before sorting, not because the scan -is avoided. Any claim that cursor paging is depth-independent needs the index as -well, which is what the next section measures. - -## The index that paging wants - and the predicate it needs - -`server/scripts/paging-index-perf.sql` creates the missing index inside a -transaction, measures three queries, and rolls the transaction back, so the -schema is unchanged afterwards: - -```sql -CREATE INDEX album_title_lower_id_perf_idx ON album (lower(title), id); -``` - -At one million albums the index is **47 MB**. Same index, same depth, three -predicates: - -| Dataset | Rows already scrolled | OR (what `searchAlbums` runs) | Row comparison | OFFSET | -| --------- | --------------------: | ----------------------------: | -------------: | -----: | -| 100,000 | 50,000 | 32 ms | 0.09 ms | 15 ms | -| 1,000,000 | 50,000 | 33 ms | 0.08 ms | 16 ms | -| 1,000,000 | 500,000 | 322 ms | 0.08 ms | 154 ms | - -The row comparison becomes an index condition and reads 20 entries at any depth: - -``` - Limit (cost=0.42..4.24 rows=20) (actual time=0.070..0.092 rows=20 loops=1) - -> Index Scan using album_title_lower_id_perf_idx on album - Index Cond: (ROW(lower(title), id) > ROW('synthetic album 549998'::text, 549998)) -``` - -The OR form cannot use the index condition, so it walks the index and filters -every entry it passes - 500,000 of them at this depth, each with a heap lookup: - -``` - -> Index Scan using album_title_lower_id_perf_idx on album (actual time=323.604..323.620 rows=20) - Filter: ((lower(title) > 'synthetic album 549998'::text) OR (...)) - Rows Removed by Filter: 500000 -``` - -At 500,000 rows in, that is **322 ms - slower than the 254 ms without any index**, -because a sequential scan reads the table in order while the filtered index scan -jumps around it. An index on the sort key is only worth its 47 MB together with -the row comparison; on its own it makes this query worse. `OFFSET` does use the -index, but it still walks and discards every skipped entry: - -``` - Limit (actual time=180.073..180.083 rows=20 loops=1) - -> Index Scan using album_title_lower_id_perf_idx on album (actual time=0.027..169.267 rows=500020 loops=1) -``` - -That pairing is the shape the architecture decision describes. The index is not in -the schema yet: the seven sort modes would need several composite indexes, each -one costs write time on seed and import, and the extra 47 MB per index is a -bærekraft tradeoff that deserves its own measurement and review. It is filed as a -follow-up rather than slipped into this milestone, and the numbers above are the -argument for doing it - as one change, not two. +This was still not constant time because there was no index on the sort key. +The index and predicate changes in #74 address that baseline for unfiltered +browse sorts. + +## Composite indexes for cursor sorts (#74) + +The search path now uses composite B-tree indexes that match each supported +browse order and its stable `album.id` tie-breaker. Title uses one +`(lower(title), id)` index, which PostgreSQL can scan in either direction. +Nullable release-year and rating sorts have separate ASC and DESC indexes with +nulls last. The query uses row comparisons for non-null cursor ranges. For a +nullable cursor with a value, it fetches the next non-null rows and a bounded +batch from the null partition separately, then merges those small batches. This +preserves nulls-last ordering without an `OR ... IS NULL` predicate that scans +the deep prefix of an index. + +`server/scripts/paging-index-perf.sql` compares the former OR predicate, the +indexed cursor query, and `OFFSET` for six browse orders at 50,000 rows in (or +500,000 with `-v offset=500000`). In a local 1,000,000-row run at 500,000 rows +in, the indexed cursor queries took **0.09–8.01 ms**; matching plans used +composite indexes and read at most two page-sized ranges. The old OR queries took +**274 ms–9.70 s** in the same run, while `OFFSET` took **79–752 ms**. Timings +are one local run and vary with cache and hardware; the important result is the +plan shape and bounded index range for the cursor query. + +There are six new sort indexes, totaling about **508 MiB** on a freshly seeded +1,000,000-album catalog. Their measured sizes after the seed and MusicBrainz +import were: + +| Index | Size | +| ---------------------------------- | ------: | +| `album_title_lower_id_idx` | 88 MiB | +| `album_title_lower_desc_id_idx` | 88 MiB | +| `album_release_year_asc_id_idx` | 68 MiB | +| `album_release_year_desc_id_idx` | 68 MiB | +| `album_average_rating_asc_id_idx` | 94 MiB | +| `album_average_rating_desc_id_idx` | 102 MiB | + +On this PostgreSQL 18.6 macOS run, seeding one million synthetic albums with +the indexes took **151 s**. Importing the committed 500-album MusicBrainz +snapshot into that catalog then took **6.43 s** (500 new, 0 matched). The +seed-only run before #74 took **88.91 s**; the indexed seed measured earlier +took **133.68 s** on a different run. These are single local measurements, not +VM guarantees, and import time depends on the catalog state. Faster browsing +costs disk space and write time; the indexes trade both for bounded keyset page +reads. + +Index sizes were read from `pg_relation_size` for each named index. The seed and +import timings used the repository's `db:seed:large` and +`db:import:musicbrainz` commands against a disposable `*_perf` database on +PostgreSQL 18.6. Import timing starts after the seed has completed and does not +include fetching the MusicBrainz snapshot. ## Prefix search (#55) @@ -198,8 +192,8 @@ The read-only benchmark is available in ```bash # A separate database. Never the application's `crate` database. -createdb crate_perf -export DATABASE_URL='postgres://t19:password@127.0.0.1:5432/crate_perf' +createdb crate_1000000_perf +export DATABASE_URL='postgres://t19:password@127.0.0.1:5432/crate_1000000_perf' pnpm --filter @t19/server db:migrate ALBUM_COUNT=1000000 pnpm db:seed:large @@ -214,6 +208,12 @@ psql "$DATABASE_URL" -v offset=500000 -f server/scripts/paging-perf.sql psql "$DATABASE_URL" -v offset=500000 -f server/scripts/paging-index-perf.sql ``` +`paging-index-perf.sql` deterministically fills `average_rating` in the +throwaway performance database so rated and unrated cursor paths can be +measured; it is not read-only. It refuses databases without the `_perf` suffix. +`db:seed:large` is destructive to its configured database and should only be +run against the separate performance database. + `psql` does not read `DATABASE_URL` by itself; it is passed explicitly above. The same variable is what the API reads, so the HTTP numbers come from a server built against the performance database: diff --git a/server/drizzle/0007_album_sort_cursor_indexes.sql b/server/drizzle/0007_album_sort_cursor_indexes.sql new file mode 100644 index 0000000..2ed57a8 --- /dev/null +++ b/server/drizzle/0007_album_sort_cursor_indexes.sql @@ -0,0 +1,6 @@ +CREATE INDEX "album_title_lower_id_idx" ON "album" USING btree (lower("title"),"id");--> statement-breakpoint +CREATE INDEX "album_title_lower_desc_id_idx" ON "album" USING btree (lower("title") DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint +CREATE INDEX "album_release_year_asc_id_idx" ON "album" USING btree ("release_year","id");--> statement-breakpoint +CREATE INDEX "album_release_year_desc_id_idx" ON "album" USING btree ("release_year" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint +CREATE INDEX "album_average_rating_asc_id_idx" ON "album" USING btree ("average_rating","id");--> statement-breakpoint +CREATE INDEX "album_average_rating_desc_id_idx" ON "album" USING btree ("average_rating" DESC NULLS LAST,"id" DESC NULLS LAST); \ No newline at end of file diff --git a/server/drizzle/meta/0007_snapshot.json b/server/drizzle/meta/0007_snapshot.json new file mode 100644 index 0000000..b1b2bb4 --- /dev/null +++ b/server/drizzle/meta/0007_snapshot.json @@ -0,0 +1,847 @@ +{ + "id": "be61a1b0-26ab-4b78-be38-6ad2a8655ae9", + "prevId": "622a95de-bc54-4e41-97a8-37e9d52b3a3c", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album": { + "name": "album", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "release_year": { + "name": "release_year", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "musicbrainz_release_group_id": { + "name": "musicbrainz_release_group_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "search_vector": { + "name": "search_vector", + "type": "tsvector", + "primaryKey": false, + "notNull": false + }, + "average_rating": { + "name": "average_rating", + "type": "double precision", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_search_vector_idx": { + "name": "album_search_vector_idx", + "columns": [ + { + "expression": "search_vector", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "gin", + "with": {} + }, + "album_title_lower_id_idx": { + "name": "album_title_lower_id_idx", + "columns": [ + { + "expression": "lower(\"title\")", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_title_lower_desc_id_idx": { + "name": "album_title_lower_desc_id_idx", + "columns": [ + { + "expression": "lower(\"title\") DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "\"id\" DESC NULLS LAST", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_release_year_asc_id_idx": { + "name": "album_release_year_asc_id_idx", + "columns": [ + { + "expression": "release_year", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_release_year_desc_id_idx": { + "name": "album_release_year_desc_id_idx", + "columns": [ + { + "expression": "release_year", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_average_rating_asc_id_idx": { + "name": "album_average_rating_asc_id_idx", + "columns": [ + { + "expression": "average_rating", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_average_rating_desc_id_idx": { + "name": "album_average_rating_desc_id_idx", + "columns": [ + { + "expression": "average_rating", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "album_musicbrainz_release_group_id_unique": { + "name": "album_musicbrainz_release_group_id_unique", + "nullsNotDistinct": false, + "columns": ["musicbrainz_release_group_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_artist": { + "name": "album_artist", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "artist_id": { + "name": "artist_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "album_artist_album_id_album_id_fk": { + "name": "album_artist_album_id_album_id_fk", + "tableFrom": "album_artist", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_artist_artist_id_artist_id_fk": { + "name": "album_artist_artist_id_artist_id_fk", + "tableFrom": "album_artist", + "tableTo": "artist", + "columnsFrom": ["artist_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_artist_album_id_artist_id_pk": { + "name": "album_artist_album_id_artist_id_pk", + "columns": ["album_id", "artist_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.album_genre": { + "name": "album_genre", + "schema": "", + "columns": { + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "genre_id": { + "name": "genre_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "album_genre_album_id_album_id_fk": { + "name": "album_genre_album_id_album_id_fk", + "tableFrom": "album_genre", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "album_genre_genre_id_genre_id_fk": { + "name": "album_genre_genre_id_genre_id_fk", + "tableFrom": "album_genre", + "tableTo": "genre", + "columnsFrom": ["genre_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "album_genre_album_id_genre_id_pk": { + "name": "album_genre_album_id_genre_id_pk", + "columns": ["album_id", "genre_id"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.app_user": { + "name": "app_user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.artist": { + "name": "artist", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "musicbrainz_artist_id": { + "name": "musicbrainz_artist_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "country": { + "name": "country", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "artist_musicbrainz_artist_id_unique": { + "name": "artist_musicbrainz_artist_id_unique", + "columns": [ + { + "expression": "musicbrainz_artist_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "artist_country_idx": { + "name": "artist_country_idx", + "columns": [ + { + "expression": "country", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.crate_item": { + "name": "crate_item", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "crate_item_user_album_unique": { + "name": "crate_item_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "crate_item_user_added_at_idx": { + "name": "crate_item_user_added_at_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "added_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "crate_item_user_id_app_user_id_fk": { + "name": "crate_item_user_id_app_user_id_fk", + "tableFrom": "crate_item", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "crate_item_album_id_album_id_fk": { + "name": "crate_item_album_id_album_id_fk", + "tableFrom": "crate_item", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.genre": { + "name": "genre", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "genre_name_unique": { + "name": "genre_name_unique", + "nullsNotDistinct": false, + "columns": ["name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.review": { + "name": "review", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "rating": { + "name": "rating", + "type": "smallint", + "primaryKey": false, + "notNull": true + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "review_user_album_unique": { + "name": "review_user_album_unique", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "review_album_idx": { + "name": "review_album_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "review_user_id_app_user_id_fk": { + "name": "review_user_id_app_user_id_fk", + "tableFrom": "review", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "review_album_id_album_id_fk": { + "name": "review_album_id_album_id_fk", + "tableFrom": "review", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "review_rating_range": { + "name": "review_rating_range", + "value": "\"review\".\"rating\" BETWEEN 1 AND 5" + } + }, + "isRLSEnabled": false + }, + "public.search_history": { + "name": "search_history", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "query": { + "name": "query", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_searched_at": { + "name": "last_searched_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "search_history_user_recent_idx": { + "name": "search_history_user_recent_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_searched_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "search_history_user_id_app_user_id_fk": { + "name": "search_history_user_id_app_user_id_fk", + "tableFrom": "search_history", + "tableTo": "app_user", + "columnsFrom": ["user_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "search_history_user_id_query_pk": { + "name": "search_history_user_id_query_pk", + "columns": ["user_id", "query"] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "search_history_query_nonempty": { + "name": "search_history_query_nonempty", + "value": "length(btrim(\"search_history\".\"query\")) > 0" + } + }, + "isRLSEnabled": false + }, + "public.track": { + "name": "track", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "album_id": { + "name": "album_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "track_number": { + "name": "track_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "duration_seconds": { + "name": "duration_seconds", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "track_album_track_number_unique": { + "name": "track_album_track_number_unique", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "track_album_track_number_idx": { + "name": "track_album_track_number_idx", + "columns": [ + { + "expression": "album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "track_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "track_album_id_album_id_fk": { + "name": "track_album_id_album_id_fk", + "tableFrom": "track", + "tableTo": "album", + "columnsFrom": ["album_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index 29822c2..8e2eeaf 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1794569205825, "tag": "0006_search-history", "breakpoints": true + }, + { + "idx": 7, + "version": "7", + "when": 1794671787291, + "tag": "0007_album_sort_cursor_indexes", + "breakpoints": true } ] } diff --git a/server/scripts/paging-index-perf.sql b/server/scripts/paging-index-perf.sql index 7680f63..419ba73 100644 --- a/server/scripts/paging-index-perf.sql +++ b/server/scripts/paging-index-perf.sql @@ -1,26 +1,24 @@ --- What a composite (lower(title), id) index is worth for keyset paging, with --- and without the predicate change that makes it usable. --- --- Read-only with respect to data. The index is created inside a transaction --- that is rolled back at the end, so it never survives the run and the schema --- is unchanged even if the script fails part-way through. Do not run it against --- the application database: CREATE INDEX takes an ACCESS EXCLUSIVE lock on --- album for the duration. +-- Compare deep keyset pages with the old OR predicate and OFFSET on each +-- indexed browse sort. Run only on a disposable *_perf database. Ratings are +-- generated deterministically here because db:seed:large creates no reviews; +-- this gives the rating sorts both rated and unrated albums to page through. -- -- psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f server/scripts/paging-index-perf.sql -- psql "$DATABASE_URL" -v offset=500000 -f server/scripts/paging-index-perf.sql -- --- The default depth works on the 100,000-album database as well as on one --- million; 500,000 is the deep case and needs the larger catalog. --- --- Three plans, same index, same depth: --- 1. the predicate searchAlbums runs today, an OR --- 2. the equivalent row comparison, which is what crateForUser uses and what --- #74 proposes for the album sorts --- 3. OFFSET, for the depth comparison +-- The benchmark changes average_rating in the performance database. The +-- benchmark.sh wrapper checks both the URL database name and current_database() +-- before running this file. \set ON_ERROR_STOP on +SELECT right(current_database(), 5) = '_perf' AS is_perf \gset +\if :is_perf +\else + \echo 'Refusing to run outside a *_perf database.' + DO $$ BEGIN RAISE EXCEPTION 'benchmark requires a *_perf database'; END $$; +\endif + \if :{?offset} \else \set offset 50000 @@ -34,56 +32,160 @@ SELECT (:offset >= 1) AS has_cursor \gset \endif SELECT count(*) AS albums FROM album; - --- The anchor is the last row already scrolled past, so the table must hold at --- least :offset rows. Otherwise OFFSET :offset - 1 returns nothing and the --- keyset queries would page from an unset cursor. SELECT count(*) >= :offset AS deep_enough FROM album \gset \if :deep_enough \else - \echo 'offset is deeper than the table: nothing to page after. Use a smaller -v offset.' + \echo 'offset is deeper than the table; use a smaller -v offset.' DO $$ BEGIN RAISE EXCEPTION 'offset is deeper than the table'; END $$; \endif -BEGIN; +-- Five ratings and 5% unrated rows give the sort representative tie groups. +UPDATE album +SET average_rating = CASE WHEN id % 19 = 0 THEN NULL ELSE (1 + id % 5)::double precision END +WHERE average_rating IS DISTINCT FROM + CASE WHEN id % 19 = 0 THEN NULL ELSE (1 + id % 5)::double precision END; +ANALYZE album; --- The index paging wants: the exact sort key of TITLE_ASC, with id as the --- tie-break, so a row comparison is an index condition rather than a filter. -CREATE INDEX album_title_lower_id_perf_idx ON album (lower(title), id); +SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS size +FROM pg_stat_user_indexes +WHERE relname = 'album' + AND indexrelname IN ( + 'album_title_lower_id_idx', + 'album_title_lower_desc_id_idx', + 'album_release_year_asc_id_idx', + 'album_release_year_desc_id_idx', + 'album_average_rating_asc_id_idx', + 'album_average_rating_desc_id_idx' + ) +ORDER BY indexrelname; --- Without fresh statistics the planner may not trust a brand-new index. -ANALYZE album; +SELECT lower(title) AS v, id AS i FROM album +ORDER BY lower(title), id OFFSET :offset - 1 LIMIT 1 \gset ta_ +SELECT lower(title) AS v, id AS i FROM album +ORDER BY lower(title) DESC, id DESC OFFSET :offset - 1 LIMIT 1 \gset td_ +SELECT release_year AS v, id AS i FROM album WHERE release_year IS NOT NULL +ORDER BY release_year, id OFFSET :offset - 1 LIMIT 1 \gset ya_ +SELECT release_year AS v, id AS i FROM album WHERE release_year IS NOT NULL +ORDER BY release_year DESC, id DESC OFFSET :offset - 1 LIMIT 1 \gset yd_ +SELECT average_rating AS v, id AS i FROM album WHERE average_rating IS NOT NULL +ORDER BY average_rating, id OFFSET :offset - 1 LIMIT 1 \gset ra_ +SELECT average_rating AS v, id AS i FROM album WHERE average_rating IS NOT NULL +ORDER BY average_rating DESC, id DESC OFFSET :offset - 1 LIMIT 1 \gset rd_ -SELECT lower(title) AS title_key, id AS id_key -FROM album -ORDER BY lower(title), id -OFFSET :offset - 1 -LIMIT 1 \gset +\echo 'TITLE_ASC — old OR predicate' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE lower(title) > :'ta_v' OR (lower(title) = :'ta_v' AND id > :ta_i) +ORDER BY lower(title) ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'TITLE_ASC — row comparison' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE (lower(title), id) > (:'ta_v', :ta_i) +ORDER BY lower(title) ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'TITLE_ASC — OFFSET' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album ORDER BY lower(title) ASC NULLS LAST, id ASC NULLS LAST +OFFSET :offset LIMIT 21; -SELECT pg_size_pretty(pg_relation_size('album_title_lower_id_perf_idx')) AS index_size; +\echo 'TITLE_DESC — old OR predicate' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE lower(title) < :'td_v' OR (lower(title) = :'td_v' AND id < :td_i) +ORDER BY lower(title) DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'TITLE_DESC — row comparison' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE (lower(title), id) < (:'td_v', :td_i) +ORDER BY lower(title) DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'TITLE_DESC — OFFSET' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album ORDER BY lower(title) DESC NULLS LAST, id DESC NULLS LAST +OFFSET :offset LIMIT 21; -\echo '1. OR predicate (what searchAlbums runs), with the index:' +\echo 'RELEASE_YEAR_ASC — old OR predicate' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE release_year > :ya_v OR (release_year = :ya_v AND id > :ya_i) OR release_year IS NULL +ORDER BY release_year ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'RELEASE_YEAR_ASC — split indexed branches' EXPLAIN (ANALYZE, BUFFERS) -SELECT id -FROM album -WHERE (lower(title) > :'title_key' OR (lower(title) = :'title_key' AND id > :id_key)) -ORDER BY lower(title), id -LIMIT 20; +SELECT * FROM ( + (SELECT id, release_year AS sort_value FROM album + WHERE (release_year, id) > (:ya_v, :ya_i) AND release_year IS NOT NULL + ORDER BY release_year ASC NULLS LAST, id ASC NULLS LAST LIMIT 21) + UNION ALL + (SELECT id, release_year AS sort_value FROM album + WHERE release_year IS NULL + ORDER BY release_year ASC NULLS LAST, id ASC NULLS LAST LIMIT 21) +) AS page_rows +ORDER BY sort_value ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'RELEASE_YEAR_ASC — OFFSET' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album ORDER BY release_year ASC NULLS LAST, id ASC NULLS LAST +OFFSET :offset LIMIT 21; -\echo '2. Row comparison (what crateForUser runs), with the index:' +\echo 'RELEASE_YEAR_DESC — old OR predicate' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE release_year < :yd_v OR (release_year = :yd_v AND id < :yd_i) OR release_year IS NULL +ORDER BY release_year DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'RELEASE_YEAR_DESC — split indexed branches' +EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM ( + (SELECT id, release_year AS sort_value FROM album + WHERE (release_year, id) < (:yd_v, :yd_i) AND release_year IS NOT NULL + ORDER BY release_year DESC NULLS LAST, id DESC NULLS LAST LIMIT 21) + UNION ALL + (SELECT id, release_year AS sort_value FROM album + WHERE release_year IS NULL + ORDER BY release_year DESC NULLS LAST, id DESC NULLS LAST LIMIT 21) +) AS page_rows +ORDER BY sort_value DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'RELEASE_YEAR_DESC — OFFSET' EXPLAIN (ANALYZE, BUFFERS) -SELECT id -FROM album -WHERE (lower(title), id) > (:'title_key', :id_key) -ORDER BY lower(title), id -LIMIT 20; +SELECT id FROM album ORDER BY release_year DESC NULLS LAST, id DESC NULLS LAST +OFFSET :offset LIMIT 21; -\echo '3. OFFSET' :offset 'page, with the index:' +\echo 'AVERAGE_RATING_ASC — old OR predicate' EXPLAIN (ANALYZE, BUFFERS) -SELECT id -FROM album -ORDER BY lower(title), id -OFFSET :offset -LIMIT 20; +SELECT id FROM album +WHERE average_rating > :ra_v OR (average_rating = :ra_v AND id > :ra_i) OR average_rating IS NULL +ORDER BY average_rating ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'AVERAGE_RATING_ASC — split indexed branches' +EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM ( + (SELECT id, average_rating AS sort_value FROM album + WHERE (average_rating, id) > (:ra_v, :ra_i) AND average_rating IS NOT NULL + ORDER BY average_rating ASC NULLS LAST, id ASC NULLS LAST LIMIT 21) + UNION ALL + (SELECT id, average_rating AS sort_value FROM album + WHERE average_rating IS NULL + ORDER BY average_rating ASC NULLS LAST, id ASC NULLS LAST LIMIT 21) +) AS page_rows +ORDER BY sort_value ASC NULLS LAST, id ASC NULLS LAST LIMIT 21; +\echo 'AVERAGE_RATING_ASC — OFFSET' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album ORDER BY average_rating ASC NULLS LAST, id ASC NULLS LAST +OFFSET :offset LIMIT 21; -ROLLBACK; +\echo 'AVERAGE_RATING_DESC — old OR predicate' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album +WHERE average_rating < :rd_v OR (average_rating = :rd_v AND id < :rd_i) OR average_rating IS NULL +ORDER BY average_rating DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'AVERAGE_RATING_DESC — split indexed branches' +EXPLAIN (ANALYZE, BUFFERS) +SELECT * FROM ( + (SELECT id, average_rating AS sort_value FROM album + WHERE (average_rating, id) < (:rd_v, :rd_i) AND average_rating IS NOT NULL + ORDER BY average_rating DESC NULLS LAST, id DESC NULLS LAST LIMIT 21) + UNION ALL + (SELECT id, average_rating AS sort_value FROM album + WHERE average_rating IS NULL + ORDER BY average_rating DESC NULLS LAST, id DESC NULLS LAST LIMIT 21) +) AS page_rows +ORDER BY sort_value DESC NULLS LAST, id DESC NULLS LAST LIMIT 21; +\echo 'AVERAGE_RATING_DESC — OFFSET' +EXPLAIN (ANALYZE, BUFFERS) +SELECT id FROM album ORDER BY average_rating DESC NULLS LAST, id DESC NULLS LAST +OFFSET :offset LIMIT 21; diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 2361134..73a648d 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -33,8 +33,32 @@ export const album = pgTable( // review keeps it current, so the rating sorts page on a stored column. averageRating: doublePrecision('average_rating'), }, - // GIN is the index type for tsvector, so a word lookup does not scan the table. - (t) => [index('album_search_vector_idx').using('gin', t.searchVector)], + // GIN serves word search; composite B-tree indexes serve keyset ordering. + (t) => [ + index('album_search_vector_idx').using('gin', t.searchVector), + index('album_title_lower_id_idx').on(sql`lower(${t.title})`, t.id), + index('album_title_lower_desc_id_idx').using( + 'btree', + sql`lower(${t.title}) DESC NULLS LAST`, + sql`${t.id} DESC NULLS LAST`, + ), + index('album_release_year_asc_id_idx').on( + t.releaseYear.asc().nullsLast(), + t.id.asc(), + ), + index('album_release_year_desc_id_idx').on( + t.releaseYear.desc().nullsLast(), + t.id.desc(), + ), + index('album_average_rating_asc_id_idx').on( + t.averageRating.asc().nullsLast(), + t.id.asc(), + ), + index('album_average_rating_desc_id_idx').on( + t.averageRating.desc().nullsLast(), + t.id.desc(), + ), + ], ); export const artist = pgTable( diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index c17de7d..aaf8948 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -1,9 +1,10 @@ -import { and, count, desc, eq, lt, or, sql } from 'drizzle-orm'; +import { and, count, desc, eq, lt, or, sql, type SQL } from 'drizzle-orm'; import { GraphQLError } from 'graphql'; import type { Db } from './db/client.js'; import { album, crateItem, review } from './db/schema.js'; import type { Loaders } from './loaders/index.js'; import { + afterNullValues, afterCursor, decodeCursor, encodeCursor, @@ -222,20 +223,36 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { const limit = pageSize(first); const filter = searchFilter(input); const key = sortKey(input); - const afterSql = after ? afterCursor(key, decodeCursor(after, input.sort)) : sql`TRUE`; - - const [page, total, genreFacets, decadeFacets, countryFacets, reviewed] = - await Promise.all([ - // One extra row tells us whether there is a next page. - db.execute(sql` + const cursor = after ? decodeCursor(after, input.sort) : null; + const afterSql = cursor ? afterCursor(key, cursor) : sql`TRUE`; + const pageSizeWithLookahead = limit + 1; + const pageSelect = (predicate: SQL) => sql` SELECT album.id, album.title, album.release_year AS "releaseYear", album.musicbrainz_release_group_id AS "musicBrainzReleaseGroupId", ${key.expr} AS "sortValue" FROM album - WHERE ${filter} AND ${afterSql} + WHERE ${filter} AND ${predicate} ORDER BY ${orderBy(key)} - LIMIT ${limit + 1} - `), + LIMIT ${pageSizeWithLookahead} + `; + const pageQuery = + key.nullable && cursor && cursor.value !== null + ? sql` + SELECT * FROM ( + (${pageSelect(sql`(${afterSql} AND ${key.expr} IS NOT NULL)`)}) + UNION ALL + (${pageSelect(afterNullValues(key, cursor))}) + ) AS page_rows + ORDER BY "sortValue" ${sql.raw(key.direction)} NULLS LAST, + id ${sql.raw(key.direction)} NULLS LAST + LIMIT ${pageSizeWithLookahead} + ` + : pageSelect(afterSql); + + const [page, total, genreFacets, decadeFacets, countryFacets, reviewed] = + await Promise.all([ + // One extra row tells us whether there is a next page. + db.execute(pageQuery), db.execute<{ count: number }>(sql` SELECT count(*)::int AS count FROM album WHERE ${filter} `), diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index b89a2dd..57b0572 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -2,6 +2,7 @@ import type { SQL } from 'drizzle-orm'; import { PgDialect } from 'drizzle-orm/pg-core'; import { describe, expect, it } from 'vitest'; import { + afterNullValues, afterCursor, countryFacetQuery, decodeCursor, @@ -48,19 +49,26 @@ describe('afterCursor', () => { const { sql, params } = render( afterCursor(key, { sort: 'TITLE_ASC', value: 'blue', id: 5 }), ); - expect(sql).toBe( - '(lower(album.title) > $1 OR (lower(album.title) = $2 AND album.id > $3))', - ); - expect(params).toEqual(['blue', 'blue', 5]); + expect(sql).toBe('((lower(album.title), album.id) > ($1, $2))'); + expect(params).toEqual(['blue', 5]); }); - it('includes the NULL years that sort after a non-NULL cursor', () => { + it('keeps non-NULL keyset comparisons indexable', () => { const key = sortKey(input({ sort: 'RELEASE_YEAR_DESC' })); - const { sql } = render( + const { sql, params } = render( afterCursor(key, { sort: 'RELEASE_YEAR_DESC', value: 1990, id: 3 }), ); - expect(sql).toContain('album.release_year < $1'); - expect(sql).toContain('album.release_year IS NULL'); + expect(sql).toBe('((album.release_year, album.id) < ($1, $2))'); + expect(params).toEqual([1990, 3]); + }); + + it('selects the NULL partition separately after a non-NULL cursor', () => { + const key = sortKey(input({ sort: 'RELEASE_YEAR_DESC' })); + const { sql, params } = render( + afterNullValues(key, { sort: 'RELEASE_YEAR_DESC', value: 1990, id: 3 }), + ); + expect(sql).toBe('(album.release_year IS NULL)'); + expect(params).toEqual([]); }); it('only pages through NULL years once the cursor is on one', () => { @@ -68,7 +76,7 @@ describe('afterCursor', () => { const { sql, params } = render( afterCursor(key, { sort: 'RELEASE_YEAR_DESC', value: null, id: 3 }), ); - expect(sql).toBe('(album.release_year IS NULL AND album.id > $1)'); + expect(sql).toBe('(album.release_year IS NULL AND album.id < $1)'); expect(params).toEqual([3]); }); }); @@ -86,9 +94,10 @@ describe('sortKey for every sort', () => { expect(render(key.expr).sql).toBe(expr); expect(key.direction).toBe(direction); expect(key.nullable).toBe(nullable); - // NULLs last in both directions, then the id tiebreak. + // NULLs last in both directions; matching the id direction makes a row + // comparison usable as an index condition for the composite key. expect(render(orderBy(key)).sql).toBe( - `${expr} ${direction} NULLS LAST, album.id ASC`, + `${expr} ${direction} NULLS LAST, album.id ${direction} NULLS LAST`, ); }); @@ -104,10 +113,8 @@ describe('afterCursor for the descending and rating sorts', () => { const { sql, params } = render( afterCursor(key, { sort: 'TITLE_DESC', value: 'blue', id: 5 }), ); - expect(sql).toBe( - '(lower(album.title) < $1 OR (lower(album.title) = $2 AND album.id > $3))', - ); - expect(params).toEqual(['blue', 'blue', 5]); + expect(sql).toBe('((lower(album.title), album.id) < ($1, $2))'); + expect(params).toEqual(['blue', 5]); }); it('keeps unknown years last when sorting oldest first', () => { @@ -115,8 +122,7 @@ describe('afterCursor for the descending and rating sorts', () => { const { sql } = render( afterCursor(key, { sort: 'RELEASE_YEAR_ASC', value: 1990, id: 3 }), ); - expect(sql).toContain('album.release_year > $1'); - expect(sql).toContain('album.release_year IS NULL'); + expect(sql).toBe('((album.release_year, album.id) > ($1, $2))'); }); // Ratings repeat far more than titles do, so on a tie the id decides which @@ -128,10 +134,11 @@ describe('afterCursor for the descending and rating sorts', () => { const key = sortKey(input({ sort })); const beyond = sort === 'AVERAGE_RATING_ASC' ? '>' : '<'; const { sql, params } = render(afterCursor(key, { sort, value: 4.5, id: 12 })); - expect(sql).toBe( - `(album.average_rating ${beyond} $1 OR (album.average_rating = $2 AND album.id > $3) OR album.average_rating IS NULL)`, - ); - expect(params).toEqual([4.5, 4.5, 12]); + expect(sql).toBe(`((album.average_rating, album.id) ${beyond} ($1, $2))`); + expect(params).toEqual([4.5, 12]); + const nulls = render(afterNullValues(key, { sort, value: 4.5, id: 12 })); + expect(nulls.sql).toBe('(album.average_rating IS NULL)'); + expect(nulls.params).toEqual([]); }, ); @@ -140,7 +147,7 @@ describe('afterCursor for the descending and rating sorts', () => { const { sql, params } = render( afterCursor(key, { sort: 'AVERAGE_RATING_DESC', value: null, id: 9 }), ); - expect(sql).toBe('(album.average_rating IS NULL AND album.id > $1)'); + expect(sql).toBe('(album.average_rating IS NULL AND album.id < $1)'); expect(params).toEqual([9]); }); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 6a76d92..1b4a626 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -248,7 +248,7 @@ export function sortKey(input: AlbumSearchInput): SortKey { } export function orderBy(key: SortKey): SQL { - return sql`${key.expr} ${sql.raw(key.direction)} NULLS LAST, album.id ASC`; + return sql`${key.expr} ${sql.raw(key.direction)} NULLS LAST, album.id ${sql.raw(key.direction)} NULLS LAST`; } /** @@ -289,16 +289,19 @@ export function afterCursor(key: SortKey, cursor: Cursor): SQL { // sort never has NULLs) would otherwise fail in Postgres or page wrongly. const valid = value === null ? key.nullable : typeof value === key.valueType; if (!valid) throw new GraphQLError('Invalid cursor'); + const beyond = key.direction === 'ASC' ? sql`>` : sql`<`; + const idBeyond = key.direction === 'ASC' ? sql`>` : sql`<`; // The cursor row had no value, so only the NULL rows after it by id remain. if (value === null) { - return sql`(${key.expr} IS NULL AND album.id > ${id})`; + return sql`(${key.expr} IS NULL AND album.id ${idBeyond} ${id})`; } - const beyond = key.direction === 'ASC' ? sql`>` : sql`<`; - const parts = [ - sql`${key.expr} ${beyond} ${value}`, - sql`(${key.expr} = ${value} AND album.id > ${id})`, - ]; - // NULLs are sorted last, so they all come after any non-NULL cursor. - if (key.nullable) parts.push(sql`${key.expr} IS NULL`); - return sql`(${sql.join(parts, sql` OR `)})`; + return sql`((${key.expr}, album.id) ${beyond} (${value}, ${id}))`; +} + +/** The NULL partition follows every non-NULL cursor when NULLs sort last. */ +export function afterNullValues(key: SortKey, cursor: Cursor): SQL { + if (!key.nullable || cursor.value === null) { + throw new GraphQLError('Invalid cursor'); + } + return sql`(${key.expr} IS NULL)`; } diff --git a/server/src/search/sort.postgres.test.ts b/server/src/search/sort.postgres.test.ts index 4b9919b..c69ff23 100644 --- a/server/src/search/sort.postgres.test.ts +++ b/server/src/search/sort.postgres.test.ts @@ -4,6 +4,7 @@ import { sql } from 'drizzle-orm'; import { Pool } from 'pg'; import { afterAll, describe, expect, it } from 'vitest'; import { + afterNullValues, afterCursor, decodeCursor, encodeCursor, @@ -34,14 +35,29 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL sorting', () => { async function page(sort: AlbumSort, after: string | null) { const key = sortKey({ query: '', sort }); - const where = after ? afterCursor(key, decodeCursor(after, sort)) : sql`TRUE`; - const query = dialect.sqlToQuery(sql` + const cursor = after ? decodeCursor(after, sort) : null; + const where = cursor ? afterCursor(key, cursor) : sql`TRUE`; + const pageSelect = (predicate: typeof where) => sql` SELECT album.id, ${key.expr} AS "sortValue" FROM ${fixture} - WHERE ${where} + WHERE ${predicate} ORDER BY ${orderBy(key)} LIMIT 2 - `); + `; + const pageQuery = + key.nullable && cursor && cursor.value !== null + ? sql` + SELECT * FROM ( + (${pageSelect(sql`(${where} AND ${key.expr} IS NOT NULL)`)}) + UNION ALL + (${pageSelect(afterNullValues(key, cursor))}) + ) AS page_rows + ORDER BY "sortValue" ${sql.raw(key.direction)} NULLS LAST, + id ${sql.raw(key.direction)} + LIMIT 2 + ` + : pageSelect(where); + const query = dialect.sqlToQuery(pageQuery); const result = await pool.query<{ id: number; sortValue: string | number | null }>( query.sql, query.params, @@ -79,13 +95,13 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL sorting', () => { expect(new Set(paged).size).toBe(7); }); - it('orders ratings with ties on id and unrated albums last', async () => { + it('orders ratings with direction-matched id ties and unrated albums last', async () => { const key = sortKey({ query: '', sort: 'AVERAGE_RATING_DESC' }); const query = dialect.sqlToQuery( sql`SELECT album.id FROM ${fixture} ORDER BY ${orderBy(key)}`, ); const rows = (await pool.query<{ id: number }>(query.sql, query.params)).rows; - expect(rows.map((row) => row.id)).toEqual([1, 2, 3, 7, 5, 4, 6]); + expect(rows.map((row) => row.id)).toEqual([7, 3, 2, 1, 5, 6, 4]); }); it('keeps album.average_rating in step with reviews', async () => {