From 787f35ff02a68da65b58d8bcd8b6b2ea9fe22bc1 Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Fri, 23 Oct 2026 21:37:11 +0200 Subject: [PATCH 1/3] feat: #55 add prefix matching to album search --- README.md | 41 ++++++++---- docs/AI-USAGE.md | 1 + server/scripts/prefix-search-perf.sql | 71 ++++++++++++++++++++ server/src/search/search.postgres.test.ts | 79 +++++++++++++++++++++++ server/src/search/search.test.ts | 21 +++++- server/src/search/search.ts | 16 ++++- 6 files changed, 213 insertions(+), 16 deletions(-) create mode 100644 server/scripts/prefix-search-perf.sql create mode 100644 server/src/search/search.postgres.test.ts diff --git a/README.md b/README.md index 40843fd..c1ea135 100644 --- a/README.md +++ b/README.md @@ -127,19 +127,38 @@ In local testing on 16 October 2026, using PostgreSQL 16 and 100,000 generated a The first three timings are SQL queries; the last is a GraphQL HTTP response. These results were measured locally, not on the VM, and may differ on other hardware. +#### Prefix search (#55) + +Prefix search allows partial words to match album titles and artists, e.g. `radio` matches Radiohead. It uses the existing PostgreSQL GIN index and requires all search terms to match. + +Performance was tested locally with 100,000 synthetic albums using PostgreSQL 18.6: + +| Search | Matches | Query time | +| ----------------------- | ------: | ---------: | +| `synth` | 100,000 | ~35 ms | +| `synthetic art` | 100,000 | ~53 ms | +| `synthetic album 99999` | 1 | ~1.3 ms | + +Broad prefixes can match many albums, increasing the work needed for ranking, counts and facets. All tested prefix queries used the existing GIN index. + +Measurements are based on two local runs with cached synthetic data and cover only page queries, not the full GraphQL response or energy consumption. + +The read-only benchmark is available in `server/scripts/prefix-search-perf.sql`. PostgreSQL tests can be run by setting `TEST_DATABASE_URL` before running the server tests. + ### Sustainability measures -Bærekraft here means design choices we can point at rather than claims, so each one is listed with a number. - -| Measure | Why it saves work | Effect | -| ------------------------------- | -------------------------------------------------------- | --------------------------------------------------- | -| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | -| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | -| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | -| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | -| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | -| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | -| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | +We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs. + +| Measure | Resource consideration | Effect | +| ------------------------------- | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| Plain CSS, no UI framework | No component-library runtime to download or parse | 0 UI dependencies in the bundle | +| `prefers-color-scheme` | OLED screens draw less power on a dark pixel | Dark theme when the OS asks for it | +| `prefers-reduced-motion` | Animations cost frames and battery | Collapsed to near-zero when the OS asks for it | +| Nothing until Search is pressed | Typing would otherwise cost one request per change | `skipToken` holds the query back, so typing is free | +| `cache-first` fetch policy | A repeated search is already in the cache | 0 requests when the answer is cached | +| Code-split album route | The detail page is not needed to browse search results | Separate 3.73 kB chunk, kept out of the main bundle | +| Bundle budget in CI | CI fails before a dependency quietly doubles the payload | 512 000 bytes per JS chunk | +| Indexed prefix search | Uses the existing GIN index, but broad prefixes require more database processing | Better search flexibility, but potentially higher query costs for broad prefixes | **Bundle size**, production build measured 21 October 2026: diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index d5cbdd8..170e09d 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -58,6 +58,7 @@ the part that matters most. | 2026-10-19 | erikhfj | opencode | Distributed the M3 issues #11 to #19 across the four of us, then corrected six of them where the text contradicted `schema.graphql` or the M2 identity contract: `toggleCrate` and `inCrate(userId:)` do not exist, `AlbumSort` uses `RELEASE_YEAR` and `AVERAGE_RATING` rather than `YEAR` and `RATING`, `countries` duplicates #25, and the genre facet counts do not exclude their own dimension the way the decade counts do. | | 2026-10-19 | erikhfj | opencode | Reviewed #53 against the code rather than as prose. Found the README contradicting its own Implemented section and a smoke test that dropped an expectation while keeping the field in the query. Verified Rachel's other claims, including that `AVERAGE_RATING_DESC` throws, which corrected my own "four sort modes" in the README. | | 2026-10-19 | erikhfj | opencode | Search state in the URL for #19, with `useSearchState` owning `q`, `sort`, `genres` and `decades`. My first version committed on a 300 ms debounce, which rewrote the URL mid-word and reset the input back through the `query !== previousQuery` branch; it read as the page reloading on every keystroke. Changed so the query reaches the URL only on Search. | +| 2026-10-23 | rachelks | Codex (ChatGPT) | Assisted with implementing and testing prefix search (#55), performance testing with 100,000 albums, and updating documentation. | ## Notes diff --git a/server/scripts/prefix-search-perf.sql b/server/scripts/prefix-search-perf.sql new file mode 100644 index 0000000..9ac8f05 --- /dev/null +++ b/server/scripts/prefix-search-perf.sql @@ -0,0 +1,71 @@ +-- Read-only comparison on the existing catalog; no seed/reset required. +-- psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f server/scripts/prefix-search-perf.sql +SELECT version(), (SELECT count(*) FROM album) AS albums; + +PREPARE exact_search(text) AS +SELECT album.id +FROM album +WHERE album.search_vector @@ websearch_to_tsquery('simple', $1) +ORDER BY + ts_rank(album.search_vector, websearch_to_tsquery('simple', $1)) DESC, + album.id ASC +LIMIT 21; + +PREPARE prefix_search(text) AS +SELECT + album.id, + ts_rank(album.search_vector, ( + SELECT coalesce( + string_agg(array_to_tsvector(ARRAY[lexeme])::text || ':*', ' & '), + '' + )::tsquery + FROM unnest(tsvector_to_array(to_tsvector('simple', $1))) AS tokens(lexeme) + )) AS rank +FROM album +WHERE album.search_vector @@ ( + SELECT coalesce( + string_agg(array_to_tsvector(ARRAY[lexeme])::text || ':*', ' & '), + '' + )::tsquery + FROM unnest(tsvector_to_array(to_tsvector('simple', $1))) AS tokens(lexeme) +) +ORDER BY rank DESC, album.id ASC +LIMIT 21; + +-- Compare broad prefixes, complete words, a specific album and a missing word. +EXPLAIN (ANALYZE, BUFFERS) EXECUTE exact_search('synth'); +EXPLAIN (ANALYZE, BUFFERS) EXECUTE prefix_search('synth'); + +EXPLAIN (ANALYZE, BUFFERS) EXECUTE exact_search('synthetic art'); +EXPLAIN (ANALYZE, BUFFERS) EXECUTE prefix_search('synthetic art'); + +EXPLAIN (ANALYZE, BUFFERS) EXECUTE exact_search('synthetic'); +EXPLAIN (ANALYZE, BUFFERS) EXECUTE prefix_search('synthetic'); + +EXPLAIN (ANALYZE, BUFFERS) EXECUTE exact_search('synthetic album 99999'); +EXPLAIN (ANALYZE, BUFFERS) EXECUTE prefix_search('synthetic album 99999'); + +EXPLAIN (ANALYZE, BUFFERS) EXECUTE exact_search('zzznomatch'); +EXPLAIN (ANALYZE, BUFFERS) EXECUTE prefix_search('zzznomatch'); + +-- Count matches without printing every album. +PREPARE prefix_results(text) AS +SELECT count(*) AS matches +FROM album +WHERE album.search_vector @@ ( + SELECT coalesce( + string_agg(array_to_tsvector(ARRAY[lexeme])::text || ':*', ' & '), + '' + )::tsquery + FROM unnest(tsvector_to_array(to_tsvector('simple', $1))) AS tokens(lexeme) +); + +EXECUTE prefix_results('synth'); +EXECUTE prefix_results('synthetic art'); +EXECUTE prefix_results('synthetic'); +EXECUTE prefix_results('synthetic album 99999'); +EXECUTE prefix_results('zzznomatch'); + +DEALLOCATE exact_search; +DEALLOCATE prefix_search; +DEALLOCATE prefix_results; diff --git a/server/src/search/search.postgres.test.ts b/server/src/search/search.postgres.test.ts new file mode 100644 index 0000000..29edbf0 --- /dev/null +++ b/server/src/search/search.postgres.test.ts @@ -0,0 +1,79 @@ +import { PgDialect } from 'drizzle-orm/pg-core'; +import { Pool } from 'pg'; +import { afterAll, describe, expect, it } from 'vitest'; +import { searchFilter, sortKey } from './search.js'; + +// Set TEST_DATABASE_URL to run these tests. VALUES supplies temporary test rows; +// the queries do not read or change stored albums. +describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL prefix search', () => { + const pool = new Pool({ connectionString: process.env.TEST_DATABASE_URL }); + const dialect = new PgDialect(); + + afterAll(() => pool.end()); + + it.each([ + ['radio', ['Radiohead']], + ['radiohead', ['Radiohead']], + ['RADIO', ['Radiohead']], + ['dark sid', ['Dark Side of the Moon']], + ['sid dark', ['Dark Side of the Moon']], + ['"dark" & sid:*', ['Dark Side of the Moon']], + ['!!! & | :* <->', []], + [String.raw`"' \\ ); DROP TABLE album; --`, []], + ['radio OR dark', []], + ['björ', ['Björk']], + ])('matches safely for %j', async (query, expected) => { + const input = { query, sort: 'RELEVANCE' as const }; + const filter = dialect.sqlToQuery(searchFilter(input)); + const rank = dialect.sqlToQuery(sortKey(input).expr); + const fixture = `FROM ( + SELECT title, to_tsvector('simple', title) AS search_vector + FROM (VALUES + ('Radiohead'), + ('Dark Side of the Moon'), + ('Dark'), + ('Björk') + ) AS titles(title) + ) AS album`; + + const result = await pool.query<{ title: string }>( + `SELECT title + ${fixture} + WHERE ${filter.sql} + ORDER BY title`, + filter.params, + ); + + expect(result.rows.map((row) => row.title)).toEqual(expected); + + const ranked = await pool.query<{ title: string; rank: number }>( + `SELECT title, ${rank.sql} AS rank + ${fixture} + WHERE ${filter.sql} + ORDER BY title`, + rank.params, + ); + + expect(ranked.rows.map((row) => row.title)).toEqual(expected); + + for (const row of ranked.rows) { + expect(row.rank).toBeGreaterThan(0); + } + }); + + it('keeps weighted title matches ahead of artist matches', async () => { + const key = dialect.sqlToQuery(sortKey({ query: 'radio', sort: 'RELEVANCE' }).expr); + + const result = await pool.query<{ id: number; rank: number }>( + `SELECT id, ${key.sql} AS rank + FROM (VALUES + (1, setweight(to_tsvector('simple', 'Radiohead'), 'B')), + (2, setweight(to_tsvector('simple', 'Radiohead'), 'A')) + ) AS album(id, search_vector) + ORDER BY rank DESC, id ASC`, + key.params, + ); + + expect(result.rows.map((row) => row.id)).toEqual([2, 1]); + }); +}); diff --git a/server/src/search/search.test.ts b/server/src/search/search.test.ts index 1d7d2ca..c295052 100644 --- a/server/src/search/search.test.ts +++ b/server/src/search/search.test.ts @@ -87,12 +87,29 @@ describe('cursor value validation', () => { }); describe('searchFilter', () => { - it('matches the term with websearch_to_tsquery and passes it as a parameter', () => { + it('normalizes and quotes prefix lexemes while keeping input parameterised', () => { const { sql, params } = render(searchFilter(input({ query: ' Blue ' }))); - expect(sql).toBe(`album.search_vector @@ websearch_to_tsquery('simple', $1)`); + + expect(sql).toContain("to_tsvector('simple', $1)"); + expect(sql).toContain("array_to_tsvector(ARRAY[lexeme])::text || ':*'"); expect(params).toEqual(['Blue']); }); + it.each(['radio', 'dark sid', 'RADIO', '!!!', String.raw`"' \\ & | ! :* <-> OR`])( + 'uses the same parameterised query for filtering, facets and ranking: %s', + (query) => { + const filters = input({ query, sort: 'RELEVANCE' }); + const where = render(searchFilter(filters)); + const facets = render(searchFilter(filters, 'decades')); + const rank = render(sortKey(filters).expr); + + expect(where.params).toEqual([query]); + expect(facets).toEqual(where); + expect(rank.params).toEqual(where.params); + expect(rank.sql).toContain(where.sql.replace('album.search_vector @@ ', '')); + }, + ); + it('has no condition for an empty search', () => { expect(render(searchFilter(input())).sql).toBe('TRUE'); }); diff --git a/server/src/search/search.ts b/server/src/search/search.ts index 6f05924..1ae09c9 100644 --- a/server/src/search/search.ts +++ b/server/src/search/search.ts @@ -23,10 +23,20 @@ export function pageSize(first: number): number { return Math.min(Math.max(first, 1), MAX_PAGE_SIZE); } -// websearch_to_tsquery never throws on odd user input (quotes, dashes, "or"), -// and 'simple' lowercases words the same way the stored search_vector does. +/** + * Splits words the same way as the stored search vector. Input stays a SQL + * parameter; PostgreSQL safely quotes each word before we add prefix syntax. + * Every word must match. Quotes, OR and dashes are not search operators. + * Input with no searchable words produces a query that matches nothing. + */ function tsQuery(query: string): SQL { - return sql`websearch_to_tsquery('simple', ${query})`; + return sql`( + SELECT coalesce( + string_agg(array_to_tsvector(ARRAY[lexeme])::text || ':*', ' & '), + '' + )::tsquery + FROM unnest(tsvector_to_array(to_tsvector('simple', ${query}))) AS tokens(lexeme) + )`; } function parseGenreId(id: string): number { From 0370569a417d9f38ecf73296ec6856b70e20c09a Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Sat, 24 Oct 2026 14:49:02 +0200 Subject: [PATCH 2/3] docs: #55 document prefix matching --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 876be7f..e81cd19 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ The frontend supports searching by album title or artist, committed on Search or ### Backend search behavior -The API uses PostgreSQL full-text search for album titles and artist names. It supports genre and decade filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. +The API uses PostgreSQL full-text search for album titles and artist names, with prefix matching to support partial words (e.g. `radi` matches `Radiohead`). It supports genre and decade filters, relevance/title/release-year sorting, facet counts and cursor-based pagination. These capabilities are available through GraphQL but are not all exposed in the frontend yet. ## Try the application From db577fc262779115e046c8313974d0e8d8e420df Mon Sep 17 00:00:00 2001 From: Rachel Knutsen Stiansen Date: Mon, 26 Oct 2026 11:54:46 +0100 Subject: [PATCH 3/3] test: #55 update Apollo mock types --- README.md | 2 +- client/src/App.test.tsx | 6 +++--- client/src/a11y.test.tsx | 8 ++++---- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e81cd19..a19e1e5 100644 --- a/README.md +++ b/README.md @@ -129,7 +129,7 @@ The first three timings are SQL queries; the last is a GraphQL HTTP response. Th #### Prefix search (#55) -Prefix search allows partial words to match album titles and artists, e.g. `radio` matches Radiohead. It uses the existing PostgreSQL GIN index and requires all search terms to match. +Prefix search allows partial words to match album titles and artists, e.g. `radio` matches Radiohead. It uses the existing PostgreSQL GIN index and treats each search term as a prefix, requiring all terms to match. Performance was tested locally with 100,000 synthetic albums using PostgreSQL 18.6: diff --git a/client/src/App.test.tsx b/client/src/App.test.tsx index ef8fbad..ec47df6 100644 --- a/client/src/App.test.tsx +++ b/client/src/App.test.tsx @@ -1,7 +1,7 @@ import { describe, it, expect, vi } from 'vitest'; import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MockedProvider } from '@apollo/client/testing/react'; -import type { MockedResponse } from '@apollo/client/testing'; +import type { MockLink } from '@apollo/client/testing'; import { GraphQLError } from 'graphql'; import App from './App.js'; import { SEARCH_ALBUMS } from './api/searchAlbums.js'; @@ -24,7 +24,7 @@ const album: AlbumSummary = { function mockSearch( query: string, albums: AlbumSummary[] = [album], -): MockedResponse { +): MockLink.MockedResponse { return { request: { query: SEARCH_ALBUMS, @@ -44,7 +44,7 @@ function mockSearch( } function renderApp( - mocks: MockedResponse[] = [], + mocks: MockLink.MockedResponse[] = [], ) { return render( diff --git a/client/src/a11y.test.tsx b/client/src/a11y.test.tsx index ff1211f..57bddd1 100644 --- a/client/src/a11y.test.tsx +++ b/client/src/a11y.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect } from 'vitest'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MockedProvider } from '@apollo/client/testing/react'; -import type { MockedResponse } from '@apollo/client/testing'; +import type { MockLink } from '@apollo/client/testing'; import { GraphQLError } from 'graphql'; import axe from 'axe-core'; @@ -27,7 +27,7 @@ const album: AlbumSummary = { function mockSearch( query: string, albums: AlbumSummary[] = [album], -): MockedResponse { +): MockLink.MockedResponse { return { request: { query: SEARCH_ALBUMS, @@ -47,7 +47,7 @@ function mockSearch( } function renderApp( - mocks: MockedResponse[] = [], + mocks: MockLink.MockedResponse[] = [], ) { return render( @@ -115,7 +115,7 @@ describe('axe-core on the search page', () => { }); it('is clean when the search fails', async () => { - const failing: MockedResponse = { + const failing: MockLink.MockedResponse = { request: { query: SEARCH_ALBUMS, variables: {