From 224b67b0bc96eb4d83e75e4cb785a039de4283dd Mon Sep 17 00:00:00 2001 From: Even Date: Sun, 22 Nov 2026 13:18:49 +0100 Subject: [PATCH] perf: #96 skip count and facet queries on Load more searchAlbums now runs only the page query. totalCount, the three facet lists and reviewedCount are AlbumConnection field resolvers, so they run only when an operation selects them. The schema is unchanged. The client sends Load more with a new SearchAlbumsPage query that asks for edges and pageInfo only. The searchAlbums merge keeps the first page's count and facets when a later page leaves them out. Tests: a server test counts the SQL a first page and a Load more request run (6 vs 1); client tests check that the page query omits the aggregates, selects the same album fields, and that the cache keeps page one's count and facets. Pagination mocks now serve Load more with the page query. --- README.md | 3 +- client/src/api/client.test.ts | 57 +++++++++++++- client/src/api/client.ts | 11 ++- client/src/api/searchAlbums.ts | 41 ++++++++++ client/src/generated/gql.ts | 6 ++ client/src/generated/graphql.ts | 10 +++ client/src/hooks/useAlbumSearch.ts | 12 ++- client/src/pagination.test.tsx | 74 +++++++++++------- docs/AI-USAGE.md | 1 + docs/scalability.md | 5 ++ server/src/resolvers.ts | 95 +++++++++++++++-------- server/src/search/aggregates.test.ts | 87 +++++++++++++++++++++ server/src/search/facets.postgres.test.ts | 22 ++++-- 13 files changed, 345 insertions(+), 79 deletions(-) create mode 100644 server/src/search/aggregates.test.ts diff --git a/README.md b/README.md index 6604d01..bbc9c9d 100644 --- a/README.md +++ b/README.md @@ -264,7 +264,8 @@ 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. +facets cover the full matching set. Only the first page pays for them: Load more +leaves counts and facets out, and the server skips those queries (#96). 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 diff --git a/client/src/api/client.test.ts b/client/src/api/client.test.ts index 7866446..563347c 100644 --- a/client/src/api/client.test.ts +++ b/client/src/api/client.test.ts @@ -1,9 +1,9 @@ import schemaSource from '../../../schema.graphql?raw'; -import { buildSchema, validate } from 'graphql'; +import { buildSchema, print, validate, type FieldNode } from 'graphql'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { cache } from './client.js'; -import { SEARCH_ALBUMS } from './searchAlbums.js'; +import { SEARCH_ALBUMS, SEARCH_ALBUMS_PAGE } from './searchAlbums.js'; import { MY_SEARCH_HISTORY } from './searchHistory.js'; import type { AlbumSearchInput, @@ -64,6 +64,30 @@ it('validates the search operation against the repository schema', () => { const schema = buildSchema(schemaSource); expect(validate(schema, SEARCH_ALBUMS)).toEqual([]); + expect(validate(schema, SEARCH_ALBUMS_PAGE)).toEqual([]); +}); + +// The connection fields each search operation selects, keyed by name. +function connectionFields(document: typeof SEARCH_ALBUMS | typeof SEARCH_ALBUMS_PAGE) { + const [operation] = document.definitions; + if (operation?.kind !== 'OperationDefinition') throw new Error('No operation'); + const [searchAlbums] = operation.selectionSet.selections as FieldNode[]; + return new Map( + (searchAlbums?.selectionSet?.selections as FieldNode[]).map((field) => [ + field.name.value, + print(field), + ]), + ); +} + +it('requests Load more pages without the count and facets, but with the same albums', () => { + const first = connectionFields(SEARCH_ALBUMS); + const next = connectionFields(SEARCH_ALBUMS_PAGE); + + expect([...next.keys()]).toEqual(['edges', 'pageInfo']); + // Every album field the first page shows must also arrive with later pages. + expect(next.get('edges')).toBe(first.get('edges')); + expect(next.get('pageInfo')).toBe(first.get('pageInfo')); }); it('replaces complete history snapshots and clears them without affecting album results', () => { @@ -112,6 +136,35 @@ describe('searchAlbums cache policy', () => { expect(read({ first: 20, after: 'cursor-2' })).toEqual(read()); }); + it('keeps the first page count and facets when Load more leaves them out', () => { + const firstPage = result(['1', '2'], 'cursor-2'); + firstPage.searchAlbums.genreFacets = [{ genre: { id: '7', name: 'Rock' }, count: 3 }]; + firstPage.searchAlbums.decadeFacets = [{ decade: 1990, count: 4 }]; + firstPage.searchAlbums.countryFacets = [ + { countryCode: 'NO', countryName: 'Norway', count: 2 }, + ]; + firstPage.searchAlbums.reviewedCount = 1; + write(firstPage); + const { edges, pageInfo } = result(['3', '4'], 'cursor-4', false).searchAlbums; + cache.writeQuery({ + query: SEARCH_ALBUMS_PAGE, + variables: { ...variables, after: 'cursor-2' }, + data: { searchAlbums: { edges, pageInfo } }, + }); + + const connection = read()?.searchAlbums; + + expect(connection?.edges.map((edge) => edge.node.id)).toEqual(['1', '2', '3', '4']); + expect(connection?.pageInfo).toEqual({ endCursor: 'cursor-4', hasNextPage: false }); + expect(connection).toMatchObject({ + totalCount: 4, + genreFacets: [{ genre: { id: '7', name: 'Rock' }, count: 3 }], + decadeFacets: [{ decade: 1990, count: 4 }], + countryFacets: [{ countryCode: 'NO', countryName: 'Norway', count: 2 }], + reviewedCount: 1, + }); + }); + it.each([ { ...input, query: 'different' }, { ...input, genreIds: ['rock'] }, diff --git a/client/src/api/client.ts b/client/src/api/client.ts index 0d22546..12c72ed 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -6,9 +6,11 @@ import type { AlbumConnection } from './searchAlbums.js'; import { getUserId } from './userIdentity.js'; // Album nodes are normalized references inside the cache, not query-result objects. -type CachedConnection = Omit & { - edges: { cursor: string; node: Reference | StoreObject }[]; -}; +// A Load more page (SEARCH_ALBUMS_PAGE) carries only edges and pageInfo. +type CachedConnection = Partial> & + Pick & { + edges: { cursor: string; node: Reference | StoreObject }[]; + }; // The crate is one list per user, so no arguments belong in its cache key; only // the paging argument decides whether this is another page or a refresh. @@ -59,7 +61,8 @@ export const cache = new InMemoryCache({ } } - return { ...incoming, edges }; + // Later pages leave out the count and facets, so the first page's stay. + return { ...existing, ...incoming, edges }; }, }, diff --git a/client/src/api/searchAlbums.ts b/client/src/api/searchAlbums.ts index 2bef720..b8a0299 100644 --- a/client/src/api/searchAlbums.ts +++ b/client/src/api/searchAlbums.ts @@ -2,6 +2,8 @@ import { graphql } from '../generated/gql.js'; import type { AlbumSearchInput, AlbumSort, + SearchAlbumsPageQuery, + SearchAlbumsPageQueryVariables, SearchAlbumsQuery, SearchAlbumsQueryVariables, } from '../generated/graphql.js'; @@ -32,6 +34,8 @@ export type DecadeFacet = AlbumConnection['decadeFacets'][number]; export type CountryFacet = AlbumConnection['countryFacets'][number]; export type SearchAlbumsData = SearchAlbumsQuery; export type SearchAlbumsVariables = SearchAlbumsQueryVariables; +export type SearchAlbumsPageData = SearchAlbumsPageQuery; +export type SearchAlbumsPageVariables = SearchAlbumsPageQueryVariables; // Only the search-page projection is requested; details belong to the album page. export const SEARCH_ALBUMS = graphql(` @@ -82,3 +86,40 @@ export const SEARCH_ALBUMS = graphql(` } } `); + +// Load more asks only for the next albums. The count and facets cover the whole +// result set, so they do not change between pages; the cache keeps the first +// page's values (see `searchAlbums` in client.ts) and the server skips their +// queries when they are not selected (#96). The node selection must match +// SEARCH_ALBUMS, or the merged list would be missing fields; client.test.ts +// checks that. +export const SEARCH_ALBUMS_PAGE = graphql(` + query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) { + searchAlbums(input: $input, first: $first, after: $after) { + edges { + cursor + node { + id + title + releaseYear + musicBrainzReleaseGroupId + artists { + id + name + } + genres { + id + name + } + averageRating + reviewCount + isInCrate + } + } + pageInfo { + hasNextPage + endCursor + } + } + } +`); diff --git a/client/src/generated/gql.ts b/client/src/generated/gql.ts index ded4f8d..e716b5e 100644 --- a/client/src/generated/gql.ts +++ b/client/src/generated/gql.ts @@ -21,6 +21,7 @@ type Documents = { "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": typeof types.UpsertReviewDocument, "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": typeof types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": typeof types.SearchAlbumsDocument, + "\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": typeof types.SearchAlbumsPageDocument, "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": typeof types.MySearchHistoryDocument, "\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n": typeof types.RecordSearchDocument, "\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n": typeof types.ClearSearchHistoryDocument, @@ -33,6 +34,7 @@ const documents: Documents = { "\n mutation UpsertReview($input: UpsertReviewInput!) {\n upsertReview(input: $input) {\n review {\n id\n rating\n comment\n }\n album {\n id\n }\n }\n }\n": types.UpsertReviewDocument, "\n mutation DeleteReview($id: ID!) {\n deleteReview(id: $id) {\n deletedReviewId\n album {\n id\n }\n }\n }\n": types.DeleteReviewDocument, "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": types.SearchAlbumsDocument, + "\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n": types.SearchAlbumsPageDocument, "\n query MySearchHistory {\n mySearchHistory {\n query\n lastSearchedAt\n }\n }\n": types.MySearchHistoryDocument, "\n mutation RecordSearch($query: String!) {\n recordSearch(query: $query) {\n query\n lastSearchedAt\n }\n }\n": types.RecordSearchDocument, "\n mutation ClearSearchHistory {\n clearSearchHistory\n }\n": types.ClearSearchHistoryDocument, @@ -80,6 +82,10 @@ export function graphql(source: "\n mutation DeleteReview($id: ID!) {\n dele * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ export function graphql(source: "\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"): (typeof documents)["\n query SearchAlbums($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n totalCount\n genreFacets {\n genre {\n id\n name\n }\n count\n }\n decadeFacets {\n decade\n count\n }\n countryFacets {\n countryCode\n countryName\n count\n }\n reviewedCount\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"]; +/** + * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. + */ +export function graphql(source: "\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"): (typeof documents)["\n query SearchAlbumsPage($input: AlbumSearchInput!, $first: Int!, $after: String) {\n searchAlbums(input: $input, first: $first, after: $after) {\n edges {\n cursor\n node {\n id\n title\n releaseYear\n musicBrainzReleaseGroupId\n artists {\n id\n name\n }\n genres {\n id\n name\n }\n averageRating\n reviewCount\n isInCrate\n }\n }\n pageInfo {\n hasNextPage\n endCursor\n }\n }\n }\n"]; /** * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients. */ diff --git a/client/src/generated/graphql.ts b/client/src/generated/graphql.ts index 8df5fb5..18bff5d 100644 --- a/client/src/generated/graphql.ts +++ b/client/src/generated/graphql.ts @@ -82,6 +82,15 @@ export type SearchAlbumsQueryVariables = Exact<{ export type SearchAlbumsQuery = { searchAlbums: { totalCount: number, reviewedCount: number, edges: Array<{ cursor: string, node: { id: string, title: string, releaseYear: number | null, musicBrainzReleaseGroupId: string | null, averageRating: number | null, reviewCount: number, isInCrate: boolean, artists: Array<{ id: string, name: string }>, genres: Array<{ id: string, name: string }> } }>, genreFacets: Array<{ count: number, genre: { id: string, name: string } }>, decadeFacets: Array<{ decade: number, count: number }>, countryFacets: Array<{ countryCode: string, countryName: string, count: number }>, pageInfo: { hasNextPage: boolean, endCursor: string | null } } }; +export type SearchAlbumsPageQueryVariables = Exact<{ + input: AlbumSearchInput; + first: number; + after?: string | null | undefined; +}>; + + +export type SearchAlbumsPageQuery = { searchAlbums: { edges: Array<{ cursor: string, node: { id: string, title: string, releaseYear: number | null, musicBrainzReleaseGroupId: string | null, averageRating: number | null, reviewCount: number, isInCrate: boolean, artists: Array<{ id: string, name: string }>, genres: Array<{ id: string, name: string }> } }>, pageInfo: { hasNextPage: boolean, endCursor: string | null } } }; + export type MySearchHistoryQueryVariables = Exact<{ [key: string]: never; }>; @@ -107,6 +116,7 @@ export const MyCrateDocument = {"kind":"Document","definitions":[{"kind":"Operat export const UpsertReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpsertReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpsertReviewInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"upsertReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"review"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"rating"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; export const DeleteReviewDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteReview"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteReview"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deletedReviewId"}},{"kind":"Field","name":{"kind":"Name","value":"album"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]} as unknown as DocumentNode; export const SearchAlbumsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbums"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}},{"kind":"Field","name":{"kind":"Name","value":"genreFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"genre"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"decadeFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"decade"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"countryFacets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"countryCode"}},{"kind":"Field","name":{"kind":"Name","value":"countryName"}},{"kind":"Field","name":{"kind":"Name","value":"count"}}]}},{"kind":"Field","name":{"kind":"Name","value":"reviewedCount"}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; +export const SearchAlbumsPageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"SearchAlbumsPage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"AlbumSearchInput"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"searchAlbums"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}},{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"cursor"}},{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"releaseYear"}},{"kind":"Field","name":{"kind":"Name","value":"musicBrainzReleaseGroupId"}},{"kind":"Field","name":{"kind":"Name","value":"artists"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"genres"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"averageRating"}},{"kind":"Field","name":{"kind":"Name","value":"reviewCount"}},{"kind":"Field","name":{"kind":"Name","value":"isInCrate"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode; export const MySearchHistoryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"mySearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"query"}},{"kind":"Field","name":{"kind":"Name","value":"lastSearchedAt"}}]}}]}}]} as unknown as DocumentNode; export const RecordSearchDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RecordSearch"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"query"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordSearch"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"query"},"value":{"kind":"Variable","name":{"kind":"Name","value":"query"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"query"}},{"kind":"Field","name":{"kind":"Name","value":"lastSearchedAt"}}]}}]}}]} as unknown as DocumentNode; export const ClearSearchHistoryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ClearSearchHistory"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"clearSearchHistory"}}]}}]} as unknown as DocumentNode; \ No newline at end of file diff --git a/client/src/hooks/useAlbumSearch.ts b/client/src/hooks/useAlbumSearch.ts index ae308cc..3052c4d 100644 --- a/client/src/hooks/useAlbumSearch.ts +++ b/client/src/hooks/useAlbumSearch.ts @@ -2,7 +2,11 @@ import { useCallback, useMemo, useRef, useState } from 'react'; import { useQuery } from '@apollo/client/react'; import { NetworkStatus } from '@apollo/client'; -import { SEARCH_ALBUMS, type AlbumSearchInput } from '../api/searchAlbums.js'; +import { + SEARCH_ALBUMS, + SEARCH_ALBUMS_PAGE, + type AlbumSearchInput, +} from '../api/searchAlbums.js'; import { useSearchState } from './useSearchState.js'; const PAGE_SIZE = 20; @@ -111,7 +115,11 @@ export function useAlbumSearch() { const pendingPage = { ...pagination, loadingMore: true, pageError: false }; setPagination(pendingPage); - void fetchMore({ variables: { input, first: PAGE_SIZE, after } }) + // A lighter query: the count and facets from page one stay in the cache. + void fetchMore({ + query: SEARCH_ALBUMS_PAGE, + variables: { input, first: PAGE_SIZE, after }, + }) .then(() => { // Late pages stay cached but must not expand a different search visit. setPagination((current) => diff --git a/client/src/pagination.test.tsx b/client/src/pagination.test.tsx index 727ceb8..3c79eb9 100644 --- a/client/src/pagination.test.tsx +++ b/client/src/pagination.test.tsx @@ -17,8 +17,10 @@ import { cache } from './api/client.js'; import { useAlbumSearch } from './hooks/useAlbumSearch.js'; import { SEARCH_ALBUMS, + SEARCH_ALBUMS_PAGE, type AlbumSearchInput, type SearchAlbumsData, + type SearchAlbumsPageData, type SearchAlbumsVariables, } from './api/searchAlbums.js'; @@ -38,52 +40,68 @@ const searchChanges: [string, AlbumSearchInput][] = [ ['?q=record&decades=1990', { ...input, decades: [1990] }], ]; +type SearchMock = MockLink.MockedResponse< + SearchAlbumsData | SearchAlbumsPageData, + SearchAlbumsVariables +>; + +// The first page uses SEARCH_ALBUMS with the count and facets; Load more uses +// SEARCH_ALBUMS_PAGE without them (#96). MockLink matches the query document, +// so a Load more sent with the full query would find no mock and fail. function page( id: string, after: string | null = null, hasNextPage = false, searchInput = input, ids = [id], + totalCount = 40, ) { + const variables = { input: searchInput, first: 20, after }; + const connection = { + edges: ids.map((albumId) => ({ + cursor: albumId, + node: { + id: albumId, + title: `Album ${albumId}`, + artists: [], + genres: [], + releaseYear: null, + musicBrainzReleaseGroupId: null, + averageRating: null, + reviewCount: 0, + isInCrate: false, + }, + })), + pageInfo: { endCursor: id, hasNextPage }, + }; + + if (after !== null) { + return { + request: { query: SEARCH_ALBUMS_PAGE, variables }, + result: { data: { searchAlbums: connection } }, + delay: 10, + } satisfies SearchMock; + } + return { - request: { - query: SEARCH_ALBUMS, - variables: { input: searchInput, first: 20, after }, - }, + request: { query: SEARCH_ALBUMS, variables }, result: { data: { searchAlbums: { - edges: ids.map((albumId) => ({ - cursor: albumId, - node: { - id: albumId, - title: `Album ${albumId}`, - artists: [], - genres: [], - releaseYear: null, - musicBrainzReleaseGroupId: null, - averageRating: null, - reviewCount: 0, - isInCrate: false, - }, - })), - totalCount: 40, + ...connection, + totalCount, genreFacets: [], decadeFacets: [], countryFacets: [], reviewedCount: 0, - pageInfo: { endCursor: id, hasNextPage }, }, }, }, delay: 10, - } satisfies MockLink.MockedResponse; + } satisfies SearchMock; } -function start( - mocks: MockLink.MockedResponse[], - url = '/?q=record', -) { +function start(mocks: SearchMock[], url = '/?q=record') { window.history.replaceState({}, '', url); // Reuse the production policies, clearing cached results for each test. render( @@ -137,16 +155,14 @@ function observeEnd() { } function fullPage(last: number, searchInput = input) { - const mock = page( + return page( String(last), last === 20 ? null : String(last - 20), true, searchInput, Array.from({ length: 20 }, (_, index) => String(last - 19 + index)), + 100, ); - mock.result.data.searchAlbums.totalCount = 100; - - return mock; } describe('cursor pagination', () => { diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 30a0a84..70d3980 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -105,6 +105,7 @@ the part that matters most. | 2026-11-17 | erikhfj | Antigravity | #91, E2E search helper fix: updated `e2e/tests/search.spec.ts` to match the `Search` and `Filters` buttons with `exact: true` so `Clear recent searches` does not trigger a strict-mode violation, and cleared `E2E_USER_ID`'s recorded search history during cleanup. Verified locally with two consecutive full `pnpm test:e2e` runs against a throwaway seeded PostgreSQL stack. | | 2026-11-20 | erikhfj | Antigravity | #100, review author privacy: removed `User.id` from `schema.graphql` and the `AlbumDetail` query, replaced `Listener ` with deterministic SHA-256 music pseudonyms in `server/src/userIdentity.ts` (including read-time sanitization of legacy labels in `Review.user`), added `User` cache merge policy, and updated schema/unit/client tests and `docs/architecture.md`. Verified with `pnpm codegen`, `pnpm format:check`, `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. | | 2026-11-20 | erikhfj | Antigravity | #103, search history error visibility and focus: moved the search history error message and Retry button inside the open `RecentSearches` dropdown so closed-state errors cannot overlap page content, returned retry success from `useSearchHistory`, restored focus to the search input after a successful retry in `SearchForm`, and added unit/integration tests. Verified with `pnpm format:check && pnpm lint && pnpm typecheck && pnpm test && pnpm build`. | +| 2026-11-22 | evenkkl | Claude | #96, skip count and facet queries on Load more: Claude made the search aggregates lazy `AlbumConnection` field resolvers, added a `SearchAlbumsPage` query for Load more, kept page one's count and facets in the Apollo merge, and added server and client tests. Verified with lint, typecheck, the test suites and the PostgreSQL tests on PGlite. | ## Notes diff --git a/docs/scalability.md b/docs/scalability.md index 23019dd..2c998f4 100644 --- a/docs/scalability.md +++ b/docs/scalability.md @@ -54,6 +54,11 @@ faceting the whole result set - `totalCount`, the genre and decade facets and th reviewed count are all aggregate queries over the full match, not over the 20 returned rows. That is the honest ceiling at one million albums. +Those aggregates only need to run once per search. Since #96 they are +`AlbumConnection` field resolvers that run only when selected, and Load more +uses a lighter query without them, so later pages cost only the cursor page +query. The client cache keeps the first page's count and facets. + ## What the GIN index is worth `server/scripts/index-perf.sql` runs the same selective search with the index and diff --git a/server/src/resolvers.ts b/server/src/resolvers.ts index 8b08acb..5e3a32b 100644 --- a/server/src/resolvers.ts +++ b/server/src/resolvers.ts @@ -215,10 +215,15 @@ async function reviewsForAlbum( } /** - * searchAlbums runs six queries, all filtered and sorted in SQL so they - * cover the whole result set: one page of albums, the total count, three - * facet lists and the reviewed count. Album artists and genres are then fetched by the loaders, one - * query each for the whole page. + * searchAlbums runs one query: a page of albums, filtered and sorted in SQL so + * it covers the whole result set. Album artists and genres are then fetched by + * the loaders, one query each for the whole page. + * + * The total count, the three facet lists and the reviewed count are resolved + * by `AlbumConnection` below, only when the operation selects them. They cover + * the whole result set and do not change between pages, so the client asks for + * them with the first page and leaves them out of Load more (#96). At 1M rows + * they cost far more than an indexed cursor page (docs/scalability.md). */ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { const limit = pageSize(first); @@ -250,28 +255,10 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { ` : 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} - `), - db.execute<{ id: number; name: string; count: number }>(genreFacetQuery(input)), - db.execute<{ decade: number; count: number }>(sql` - SELECT (album.release_year / 10) * 10 AS decade, count(*)::int AS count - FROM album - WHERE ${searchFilter(input, 'decades')} AND album.release_year IS NOT NULL - GROUP BY 1 - ORDER BY 1 - `), - db.execute<{ country_code: string; count: number }>(countryFacetQuery(input)), - db.execute<{ count: number }>(sql` - SELECT count(*)::int AS count FROM album - WHERE ${searchFilter(input, 'hasReviews')} - AND EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id) - `), - ]); + // One extra row tells us whether there is a next page. + const page = await db.execute( + pageQuery, + ); const rows = page.rows.slice(0, limit); const edges = rows.map(({ sortValue, ...node }) => ({ @@ -285,18 +272,57 @@ async function searchAlbums(db: Db, { input, first, after }: SearchArgs) { hasNextPage: page.rows.length > limit, endCursor: edges.at(-1)?.cursor ?? null, }, - totalCount: total.rows[0]?.count ?? 0, - genreFacets: genreFacets.rows.map(({ count, ...g }) => ({ genre: g, count })), - decadeFacets: withSelectedDecades(decadeFacets.rows, input), - countryFacets: countryFacets.rows.map(({ country_code: countryCode, count }) => ({ + // Not a schema field: the AlbumConnection resolvers read it. + input, + }; +} + +type SearchConnection = Awaited>; + +// Whole-result-set aggregates of a search, each run only if its field is selected. +const albumConnectionAggregates = { + totalCount: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { + const total = await ctx.db.execute<{ count: number }>(sql` + SELECT count(*)::int AS count FROM album WHERE ${searchFilter(input)} + `); + return total.rows[0]?.count ?? 0; + }, + genreFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { + const facets = await ctx.db.execute<{ id: number; name: string; count: number }>( + genreFacetQuery(input), + ); + return facets.rows.map(({ count, ...g }) => ({ genre: g, count })); + }, + decadeFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { + const facets = await ctx.db.execute<{ decade: number; count: number }>(sql` + SELECT (album.release_year / 10) * 10 AS decade, count(*)::int AS count + FROM album + WHERE ${searchFilter(input, 'decades')} AND album.release_year IS NOT NULL + GROUP BY 1 + ORDER BY 1 + `); + return withSelectedDecades(facets.rows, input); + }, + countryFacets: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { + const facets = await ctx.db.execute<{ country_code: string; count: number }>( + countryFacetQuery(input), + ); + return facets.rows.map(({ country_code: countryCode, count }) => ({ countryCode, countryName: new Intl.DisplayNames(['en'], { type: 'region' }).of(countryCode) ?? countryCode, count, - })), - reviewedCount: reviewed.rows[0]?.count ?? 0, - }; -} + })); + }, + reviewedCount: async ({ input }: SearchConnection, _: unknown, ctx: Context) => { + const reviewed = await ctx.db.execute<{ count: number }>(sql` + SELECT count(*)::int AS count FROM album + WHERE ${searchFilter(input, 'hasReviews')} + AND EXISTS (SELECT 1 FROM review WHERE review.album_id = album.id) + `); + return reviewed.rows[0]?.count ?? 0; + }, +}; // Fields not listed here (tracks, ratings, reviews, crate) arrive with their // own issues. @@ -317,6 +343,7 @@ export const resolvers = { return found ?? null; }, }, + AlbumConnection: albumConnectionAggregates, Album: { artists: (album: AlbumRow, _: unknown, ctx: Context) => ctx.loaders.artistsByAlbum.load(album.id), diff --git a/server/src/search/aggregates.test.ts b/server/src/search/aggregates.test.ts new file mode 100644 index 0000000..241fc5c --- /dev/null +++ b/server/src/search/aggregates.test.ts @@ -0,0 +1,87 @@ +import { readFileSync } from 'node:fs'; +import type { SQL } from 'drizzle-orm'; +import { PgDialect } from 'drizzle-orm/pg-core'; +import { createSchema, createYoga } from 'graphql-yoga'; +import { describe, expect, it } from 'vitest'; +import type { Db } from '../db/client.js'; +import { createLoaders } from '../loaders/index.js'; +import { resolvers, type Context } from '../resolvers.js'; +import { encodeCursor } from './search.js'; + +// A database stand-in that records the SQL of every query and returns no rows, +// so the test counts which queries a search operation actually runs (#96). +function recordingDb() { + const dialect = new PgDialect(); + const queries: string[] = []; + const db = { + execute: (query: SQL) => { + queries.push(dialect.sqlToQuery(query).sql); + return Promise.resolve({ rows: [] }); + }, + } as unknown as Db; + return { db, queries }; +} + +async function run(query: string, after: string | null) { + const { db, queries } = recordingDb(); + const yoga = createYoga({ + schema: createSchema({ + typeDefs: readFileSync(new URL('../../../schema.graphql', import.meta.url), 'utf8'), + resolvers, + }), + context: () => ({ db, userId: null, loaders: createLoaders(db, null) }), + }); + const response = await yoga.fetch('http://localhost/graphql', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + query, + variables: { input: { query: 'blue', sort: 'TITLE_ASC' }, after }, + }), + }); + const result = (await response.json()) as { data?: unknown; errors?: unknown }; + expect(result.errors).toBeUndefined(); + return { data: result.data, queries }; +} + +const firstPage = ` + query First($input: AlbumSearchInput!, $after: String) { + searchAlbums(input: $input, first: 20, after: $after) { + edges { cursor } + pageInfo { hasNextPage endCursor } + totalCount + genreFacets { count } + decadeFacets { decade count } + countryFacets { countryCode count } + reviewedCount + } + } +`; + +const nextPage = ` + query Next($input: AlbumSearchInput!, $after: String) { + searchAlbums(input: $input, first: 20, after: $after) { + edges { cursor } + pageInfo { hasNextPage endCursor } + } + } +`; + +describe('searchAlbums aggregates', () => { + it('runs the page query plus the count and facet queries when they are selected', async () => { + const { data, queries } = await run(firstPage, null); + expect(queries).toHaveLength(6); + expect(queries.filter((sql) => /\bcount\(/.test(sql))).toHaveLength(5); + expect(data).toMatchObject({ + searchAlbums: { totalCount: 0, genreFacets: [], reviewedCount: 0 }, + }); + }); + + it('runs only the page query for a Load more request without aggregates', async () => { + const cursor = encodeCursor({ sort: 'TITLE_ASC', value: 'blue', id: 7 }); + const { queries } = await run(nextPage, cursor); + expect(queries).toHaveLength(1); + expect(queries[0]).not.toMatch(/\bcount\(/); + expect(queries[0]).toContain('LIMIT'); + }); +}); diff --git a/server/src/search/facets.postgres.test.ts b/server/src/search/facets.postgres.test.ts index 78a4941..6190894 100644 --- a/server/src/search/facets.postgres.test.ts +++ b/server/src/search/facets.postgres.test.ts @@ -103,17 +103,25 @@ describe.skipIf(!process.env.TEST_DATABASE_URL)('PostgreSQL filters and facets', { input, first: 50 }, ctx, ); + // The aggregates are AlbumConnection field resolvers, run only when selected. + const aggregates = resolvers.AlbumConnection; + const [totalCount, genreFacets, decadeFacets, countryFacets, reviewedCount] = + await Promise.all([ + aggregates.totalCount(result, {}, ctx), + aggregates.genreFacets(result, {}, ctx), + aggregates.decadeFacets(result, {}, ctx), + aggregates.countryFacets(result, {}, ctx), + aggregates.reviewedCount(result, {}, ctx), + ]); return { titles: result.edges.map((edge) => edge.node.title.split(' ')[0]), - totalCount: result.totalCount, + totalCount, genres: Object.fromEntries( - result.genreFacets.map((f) => [f.genre.name.split(' ')[0], f.count]), - ), - decades: Object.fromEntries(result.decadeFacets.map((f) => [f.decade, f.count])), - countries: Object.fromEntries( - result.countryFacets.map((f) => [f.countryCode, f.count]), + genreFacets.map((f) => [f.genre.name.split(' ')[0], f.count]), ), - reviewedCount: result.reviewedCount, + decades: Object.fromEntries(decadeFacets.map((f) => [f.decade, f.count])), + countries: Object.fromEntries(countryFacets.map((f) => [f.countryCode, f.count])), + reviewedCount, }; }