diff --git a/README.md b/README.md index df14aea..a19e1e5 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 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: + +| 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. +We consider sustainability through design choices that reduce unnecessary data transfer, processing and resource use, while acknowledging performance tradeoffs. -| 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 | +| 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: @@ -183,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 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: { diff --git a/docs/AI-USAGE.md b/docs/AI-USAGE.md index 6572aa3..c3b744c 100644 --- a/docs/AI-USAGE.md +++ b/docs/AI-USAGE.md @@ -9,62 +9,62 @@ Everyone adds their own rows. Two rows in the middle have no tool in them on purpose: they are where a person overruled what the tool proposed, which is the part that matters most. -| Date | Who | Tool | Used for | -| ---------- | -------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 2026-09-23 | erikhfj | opencode | Stack prototype (PostgreSQL, GraphQL Yoga, Drizzle, React + Apollo) to answer two design risks early: does Postgres FTS give case-insensitive single-term search, and does keyset paging stay correct across every sort mode. Verified live on the VM. **Closed unmerged**, kept as `archive/scaffold-prototype`. | -| 2026-09-23 | erikhfj | opencode | VM bootstrap scripts: PostgreSQL role and database, Node 24 via nvm, `crate-api` systemd unit, Apache `ProxyPass /graphql` | -| 2026-09-23 | erikhfj | opencode | Smoke tests against the running API. These caught three bugs the unit tests had missed: `GenreFacet.genre` shape drift from the SDL, drizzle expanding a JS array into scalar parameters inside a `::int[]` cast, and a missing review aggregate on `album(id:)` | -| 2026-09-24 | erikhfj | opencode | Plan to retire the prototype PR and re-land the work in milestone-sized PRs | -| 2026-09-24 | rachelks | - | **Overruled the plan.** Splitting generated code into smaller PRs would only fix the git cosmetics, so each issue must be implemented from its requirements by its owner. The prototype is a reference, not a source to copy from. Taken. | -| 2026-09-24 | robertky | - | **Overruled the plan.** Dropped the plan-before-code step as process for its own sake; clear issues plus PR descriptions that say what was done and tested are what reviewers read. Also: assign issues one milestone at a time, not all up front. Taken. | -| 2026-09-27 | rachelks | Codex (ChatGPT) | Discussed the UI specification for #29 and how to translate the project requirements into the planned interface. I reviewed and adapted the specification to the group's agreed design. | -| 2026-09-27 | robertky | Codex (ChatGPT) | Assisted with drafting the M1 GraphQL schema and data model for #2. I reviewed the model, kept database/resolvers out of M1, and incorporated peer-review feedback before merge. | -| 2026-09-28 | erikhfj | opencode | Tooling for #1: pnpm workspace, ESLint 9 flat config, Prettier, strict TypeScript, `AGENTS.md` | -| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing #32 and diagnosing a Windows-specific formatting failure. Testing with `core.autocrlf=true` exposed the LF/CRLF issue; I reported it in the review and erikhfj fixed it with `.gitattributes` before merge. | -| 2026-09-28 | erikhfj | opencode | Review fix for #1: `.gitattributes` with `* text=auto eol=lf` after `core.autocrlf` broke `pnpm format:check` on Windows | -| 2026-09-28 | erikhfj | opencode | Workflow guide and this log for #4 | -| 2026-09-28 | evenkkl | Claude | Assisted with formulating a schema for the architecture decision in #3, and served as a sparring partner to help understand why we made the decisions we did. | -| 2026-09-28 | erikhfj | opencode | CI for #27: `quality` and `deploy` jobs, self-hosted runner registered on the VM, client bundle budget | -| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing the CI workflow in #34. Identified that the `project2` runner label was not used by the deploy job. I reported it in the review, erikhfj then pinned the deploy job to the intended runner. | -| 2026-09-29 | erikhfj | opencode | Review fix for #27: `pull_request` no longer filters on `branches: [main]`, which had silently given stacked PRs zero CI runs | -| 2026-09-30 | rachelks | Codex (ChatGPT) | Assisted with reviewing the GraphQL schema in #35. I identified a missing paginated review connection required by the specification and requested changes; robertky corrected the schema before merge. | -| 2026-09-30 | robertky | Codex (ChatGPT) | Helped me interpret Rachel's schema review on #35. | -| 2026-09-30 | evenkkl | Claude | Assisted with formulating reviews of PR #35, and identifying additional areas for improvement. | -| 2026-10-01 | erikhfj | opencode | Answers to the open design questions: UUID as an `X-User-Id` header into the GraphQL context, narrowing facet counts, `id` tie-breakers, nulls last in both directions | -| 2026-10-01 | rachelks | Codex (ChatGPT) | Assisted with diagnosing the CI deploy failure after merge. The investigation traced the API restart issue to the `crate-api.service` check, `sudo` requiring a TTY, and a race while waiting for the API to start; erikhfj then fixed the deploy workflow. | -| 2026-10-01 | erikhfj | opencode | CI deploy fix for #27 after rachelks reported it: `grep -q` SIGPIPE silently skipped a live service, `sudo` had no TTY, and `sleep 2` raced Node binding the port. All three verified against the live unit | -| 2026-10-01 | erikhfj | opencode | Simplified this log to a table at the group's request | -| 2026-10-01 | robertky | Codex (ChatGPT) | Assisted with formulating good reviews of the architecture and UI-specification PRs. The group decided to include decade filtering; Rachel implemented the corresponding schema and documentation update in #38. | -| 2026-10-07 | erikhfj | opencode | Simulated user identity for #10: a `User` type and the `X-User-Id` header contract, read into a per-request GraphQL context so that no field in `schema.graphql` takes a `userId` argument | -| 2026-10-07 | rachelks | ChatGPT | Assisted with frontend styling, UI decisions and troubleshooting for #9 (PR #47). | -| 2026-10-09 | robertky | Codex (ChatGPT) | AI was a good sparring partner when I drafted the initial #5 PostgreSQL migration. It gave me ideas on how to structure and improve the tables, relation tables, constraints, indexes, full-text search triggers and TypeScript migration runner. | -| 2026-10-09 | erikhfj | opencode | VM runbook for #8, and converted `~/T19-Project-2` from a hand-copied prototype into a real git clone of `main` with a deploy SSH key. The gitignored `.env` was checksummed across `git checkout --force` to prove a deploy does not wipe `DATABASE_URL` | -| 2026-10-10 | evenkkl | Claude | Assisted with implementing the GraphQL Yoga server with `searchAlbums` for #6, and formulated an easy to understand PR description. Guided the reset of the prototype tables in the VM database (backup taken first). | -| 2026-10-10 | erikhfj | opencode | Wrote out the facet-count trade-off on #13: OR within a category pairs with per-dimension exclusion, AND with global counts. Posted as an analysis for the group to settle, not as a decision | -| 2026-10-10 | erikhfj | opencode | Forced `source-map-js` to 1.2.2 through `pnpm.overrides` for #43, after the Dependabot alert | -| 2026-10-10 | rachelks | ChatGPT | Assisted with reviewing PR #42, identifying an issue with the backend deployment workflow that led to #44. | -| 2026-10-10 | erikhfj | opencode | Traced the deploy gap rachelks raised on #42 and opened #44: CI built `server/` in the runner workspace while `crate-api.service` runs `dist/index.js` out of `~/T19-Project-2/server`, so a restart kept bringing back a 23 September prototype | -| 2026-10-12 | erikhfj | opencode | **Tool output corrected by a person.** The draft identity contract said `displayName`, derived server-side from the UUID, stops one user writing as another. It does not: the client can still send any UUID. robertky caught it on review and the wording was fixed in #40 | -| 2026-10-13 | evenkkl | Claude | Fixed the review feedback on #6: cursor values validated against the sort, `reviewCount` returns 0 until reviews exist. The group decided genre filters combine with AND; Claude made the filter and the genre counts match that. | -| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing PRs #45 and #46, identifying issues with deployment checks, database migrations and FTS triggers. Erik and Robert addressed the issues before merging. | -| 2026-10-15 | erikhfj | opencode | Rachel's four review points on #45: the smoke query omitted the required `sort` field so it could never have passed, the deploy step skipped instead of failing, and the body check grepped for the word "errors" instead of parsing JSON. Two bugs in my own first attempt: a multi-line `python3 -c` cannot live inside a YAML block scalar, and `\"` in bash single quotes is a literal backslash | -| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing M2 documentation for #48, identifying outdated setup instructions and missing frontend information. | -| 2026-10-15 | erikhfj | opencode | Documentation pass for #48: this log and the README brought up to date with what has actually landed | -| 2026-10-15 | erikhfj | opencode | Folded #46 into the README, and added `db:migrate` to the deploy on #45 after #46 pointed out it never ran: a deploy that lands migration files without applying them leaves the schema behind the code. Also reconciled `DATABASE_URL`, which the systemd unit reads from the checkout root and the server package scripts read from `server/.env` | -| 2026-10-15 | robertky | Codex (ChatGPT) | Assisted me when I designed and implemented #7's batched synthetic catalog generator, its tests and local performance verification. I reviewed the generated data, when AI suggested something before using it. | -| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with updating README and VM setup documentation for #48, clarifying implemented functionality and local development instructions. | -| 2026-10-16 | evenkkl | Claude | Assisted with reviewing PRs #50 and #51, checking the changes against the code and identifying areas for improvement. | -| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with a final documentation review and cleanup for #48. | -| 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-20 | robertky | Codex (ChatGPT) | Assisted me when I implemented #11: the `album(id:)` resolver, batched loading of album relations, paginated reviews, and a code-split album detail route with tracklist and reviews. I reviewed the parts that AI generated and tests before using it. | -| 2026-10-22 | robertky | Codex (ChatGPT) | Assisted me when I implemented #15: per-browser user identity, creating/updating/deleting reviews, and the accessible review UI. I reviewed the parts that AI generated and tests before using it. | - -| 2026-10-20 | erikhfj | opencode | Processed two co-students' reviews of the project. Both found the same real bug: search matches whole words, so `radio` finds nothing for Radiohead. Their diagnosis was right, but the fix proposed, `to_tsquery` with `:*`, throws on quotes and dashes, which is the whole reason the code uses `websearch_to_tsquery`. Filed #55 to build the prefix query in TypeScript instead. Their rating suggestion exposed something worse: #12 asked for `AVG(review.rating)` as the keyset sort key, an aggregate that moves whenever anyone writes a review. Revised #12 to a trigger-maintained `album.average_rating`, warned #15 not to write the same column, and corrected #18 where a bullet still described a debounce #19 had already removed. | -| 2026-10-22 | erikhfj | opencode | Reviewed #57 and #58 by running the full gate suite on the branches rather than reading them as prose. Six findings on each. One of mine was wrong: I wrote that `App.tsx` was the only file in the repo carrying a UTF-8 BOM. It is one of four, and three predate that PR entirely. Posted a correction rather than leaving the error standing. Recorded here because a wrong review is as much a failure of control as a wrong patch. | -| 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. | -| 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. | +| Date | Who | Tool | Used for | +| ---------- | -------- | --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 2026-09-23 | erikhfj | opencode | Stack prototype (PostgreSQL, GraphQL Yoga, Drizzle, React + Apollo) to answer two design risks early: does Postgres FTS give case-insensitive single-term search, and does keyset paging stay correct across every sort mode. Verified live on the VM. **Closed unmerged**, kept as `archive/scaffold-prototype`. | +| 2026-09-23 | erikhfj | opencode | VM bootstrap scripts: PostgreSQL role and database, Node 24 via nvm, `crate-api` systemd unit, Apache `ProxyPass /graphql` | +| 2026-09-23 | erikhfj | opencode | Smoke tests against the running API. These caught three bugs the unit tests had missed: `GenreFacet.genre` shape drift from the SDL, drizzle expanding a JS array into scalar parameters inside a `::int[]` cast, and a missing review aggregate on `album(id:)` | +| 2026-09-24 | erikhfj | opencode | Plan to retire the prototype PR and re-land the work in milestone-sized PRs | +| 2026-09-24 | rachelks | - | **Overruled the plan.** Splitting generated code into smaller PRs would only fix the git cosmetics, so each issue must be implemented from its requirements by its owner. The prototype is a reference, not a source to copy from. Taken. | +| 2026-09-24 | robertky | - | **Overruled the plan.** Dropped the plan-before-code step as process for its own sake; clear issues plus PR descriptions that say what was done and tested are what reviewers read. Also: assign issues one milestone at a time, not all up front. Taken. | +| 2026-09-27 | rachelks | Codex (ChatGPT) | Discussed the UI specification for #29 and how to translate the project requirements into the planned interface. I reviewed and adapted the specification to the group's agreed design. | +| 2026-09-27 | robertky | Codex (ChatGPT) | Assisted with drafting the M1 GraphQL schema and data model for #2. I reviewed the model, kept database/resolvers out of M1, and incorporated peer-review feedback before merge. | +| 2026-09-28 | erikhfj | opencode | Tooling for #1: pnpm workspace, ESLint 9 flat config, Prettier, strict TypeScript, `AGENTS.md` | +| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing #32 and diagnosing a Windows-specific formatting failure. Testing with `core.autocrlf=true` exposed the LF/CRLF issue; I reported it in the review and erikhfj fixed it with `.gitattributes` before merge. | +| 2026-09-28 | erikhfj | opencode | Review fix for #1: `.gitattributes` with `* text=auto eol=lf` after `core.autocrlf` broke `pnpm format:check` on Windows | +| 2026-09-28 | erikhfj | opencode | Workflow guide and this log for #4 | +| 2026-09-28 | evenkkl | Claude | Assisted with formulating a schema for the architecture decision in #3, and served as a sparring partner to help understand why we made the decisions we did. | +| 2026-09-28 | erikhfj | opencode | CI for #27: `quality` and `deploy` jobs, self-hosted runner registered on the VM, client bundle budget | +| 2026-09-28 | rachelks | Codex (ChatGPT) | Assisted with reviewing the CI workflow in #34. Identified that the `project2` runner label was not used by the deploy job. I reported it in the review, erikhfj then pinned the deploy job to the intended runner. | +| 2026-09-29 | erikhfj | opencode | Review fix for #27: `pull_request` no longer filters on `branches: [main]`, which had silently given stacked PRs zero CI runs | +| 2026-09-30 | rachelks | Codex (ChatGPT) | Assisted with reviewing the GraphQL schema in #35. I identified a missing paginated review connection required by the specification and requested changes; robertky corrected the schema before merge. | +| 2026-09-30 | robertky | Codex (ChatGPT) | Helped me interpret Rachel's schema review on #35. | +| 2026-09-30 | evenkkl | Claude | Assisted with formulating reviews of PR #35, and identifying additional areas for improvement. | +| 2026-10-01 | erikhfj | opencode | Answers to the open design questions: UUID as an `X-User-Id` header into the GraphQL context, narrowing facet counts, `id` tie-breakers, nulls last in both directions | +| 2026-10-01 | rachelks | Codex (ChatGPT) | Assisted with diagnosing the CI deploy failure after merge. The investigation traced the API restart issue to the `crate-api.service` check, `sudo` requiring a TTY, and a race while waiting for the API to start; erikhfj then fixed the deploy workflow. | +| 2026-10-01 | erikhfj | opencode | CI deploy fix for #27 after rachelks reported it: `grep -q` SIGPIPE silently skipped a live service, `sudo` had no TTY, and `sleep 2` raced Node binding the port. All three verified against the live unit | +| 2026-10-01 | erikhfj | opencode | Simplified this log to a table at the group's request | +| 2026-10-01 | robertky | Codex (ChatGPT) | Assisted with formulating good reviews of the architecture and UI-specification PRs. The group decided to include decade filtering; Rachel implemented the corresponding schema and documentation update in #38. | +| 2026-10-07 | erikhfj | opencode | Simulated user identity for #10: a `User` type and the `X-User-Id` header contract, read into a per-request GraphQL context so that no field in `schema.graphql` takes a `userId` argument | +| 2026-10-07 | rachelks | ChatGPT | Assisted with frontend styling, UI decisions and troubleshooting for #9 (PR #47). | +| 2026-10-09 | robertky | Codex (ChatGPT) | AI was a good sparring partner when I drafted the initial #5 PostgreSQL migration. It gave me ideas on how to structure and improve the tables, relation tables, constraints, indexes, full-text search triggers and TypeScript migration runner. | +| 2026-10-09 | erikhfj | opencode | VM runbook for #8, and converted `~/T19-Project-2` from a hand-copied prototype into a real git clone of `main` with a deploy SSH key. The gitignored `.env` was checksummed across `git checkout --force` to prove a deploy does not wipe `DATABASE_URL` | +| 2026-10-10 | evenkkl | Claude | Assisted with implementing the GraphQL Yoga server with `searchAlbums` for #6, and formulated an easy to understand PR description. Guided the reset of the prototype tables in the VM database (backup taken first). | +| 2026-10-10 | erikhfj | opencode | Wrote out the facet-count trade-off on #13: OR within a category pairs with per-dimension exclusion, AND with global counts. Posted as an analysis for the group to settle, not as a decision | +| 2026-10-10 | erikhfj | opencode | Forced `source-map-js` to 1.2.2 through `pnpm.overrides` for #43, after the Dependabot alert | +| 2026-10-10 | rachelks | ChatGPT | Assisted with reviewing PR #42, identifying an issue with the backend deployment workflow that led to #44. | +| 2026-10-10 | erikhfj | opencode | Traced the deploy gap rachelks raised on #42 and opened #44: CI built `server/` in the runner workspace while `crate-api.service` runs `dist/index.js` out of `~/T19-Project-2/server`, so a restart kept bringing back a 23 September prototype | +| 2026-10-12 | erikhfj | opencode | **Tool output corrected by a person.** The draft identity contract said `displayName`, derived server-side from the UUID, stops one user writing as another. It does not: the client can still send any UUID. robertky caught it on review and the wording was fixed in #40 | +| 2026-10-13 | evenkkl | Claude | Fixed the review feedback on #6: cursor values validated against the sort, `reviewCount` returns 0 until reviews exist. The group decided genre filters combine with AND; Claude made the filter and the genre counts match that. | +| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing PRs #45 and #46, identifying issues with deployment checks, database migrations and FTS triggers. Erik and Robert addressed the issues before merging. | +| 2026-10-15 | erikhfj | opencode | Rachel's four review points on #45: the smoke query omitted the required `sort` field so it could never have passed, the deploy step skipped instead of failing, and the body check grepped for the word "errors" instead of parsing JSON. Two bugs in my own first attempt: a multi-line `python3 -c` cannot live inside a YAML block scalar, and `\"` in bash single quotes is a literal backslash | +| 2026-10-15 | rachelks | Codex (ChatGPT) | Assisted with reviewing M2 documentation for #48, identifying outdated setup instructions and missing frontend information. | +| 2026-10-15 | erikhfj | opencode | Documentation pass for #48: this log and the README brought up to date with what has actually landed | +| 2026-10-15 | erikhfj | opencode | Folded #46 into the README, and added `db:migrate` to the deploy on #45 after #46 pointed out it never ran: a deploy that lands migration files without applying them leaves the schema behind the code. Also reconciled `DATABASE_URL`, which the systemd unit reads from the checkout root and the server package scripts read from `server/.env` | +| 2026-10-15 | robertky | Codex (ChatGPT) | Assisted me when I designed and implemented #7's batched synthetic catalog generator, its tests and local performance verification. I reviewed the generated data, when AI suggested something before using it. | +| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with updating README and VM setup documentation for #48, clarifying implemented functionality and local development instructions. | +| 2026-10-16 | evenkkl | Claude | Assisted with reviewing PRs #50 and #51, checking the changes against the code and identifying areas for improvement. | +| 2026-10-16 | rachelks | Codex (ChatGPT) | Assisted with a final documentation review and cleanup for #48. | +| 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-20 | robertky | Codex (ChatGPT) | Assisted me when I implemented #11: the `album(id:)` resolver, batched loading of album relations, paginated reviews, and a code-split album detail route with tracklist and reviews. I reviewed the parts that AI generated and tests before using it. | +| 2026-10-20 | erikhfj | opencode | Processed two co-students' reviews of the project. Both found the same real bug: search matches whole words, so `radio` finds nothing for Radiohead. Their diagnosis was right, but the fix proposed, `to_tsquery` with `:*`, throws on quotes and dashes, which is the whole reason the code uses `websearch_to_tsquery`. Filed #55 to build the prefix query in TypeScript instead. Their rating suggestion exposed something worse: #12 asked for `AVG(review.rating)` as the keyset sort key, an aggregate that moves whenever anyone writes a review. Revised #12 to a trigger-maintained `album.average_rating`, warned #15 not to write the same column, and corrected #18 where a bullet still described a debounce #19 had already removed. | +| 2026-10-22 | robertky | Codex (ChatGPT) | Assisted me when I implemented #15: per-browser user identity, creating/updating/deleting reviews, and the accessible review UI. I reviewed the parts that AI generated and tests before using it. | +| 2026-10-22 | erikhfj | opencode | Reviewed #57 and #58 by running the full gate suite on the branches rather than reading them as prose. Six findings on each. One of mine was wrong: I wrote that `App.tsx` was the only file in the repo carrying a UTF-8 BOM. It is one of four, and three predate that PR entirely. Posted a correction rather than leaving the error standing. Recorded here because a wrong review is as much a failure of control as a wrong patch. | +| 2026-10-22 | erikhfj | opencode | #18, dark theme under `prefers-color-scheme`. Lifted the eight hard-coded colours into custom properties first so the light palette stays byte-identical. Did not take the generated palette as-is: `--border-strong` at `#556055` measured 2.5:1 against the surface, under the 3:1 a form-control border needs, so it became `#6b766b` at 3.4:1. Computed every ratio by hand rather than trusting the values that came back. | +| 2026-10-22 | erikhfj | opencode | #17, axe-core over all four states of the search page. A green suite proves nothing on its own, so the harness asserts axe found passing rules before asserting it found no violations, and I checked it against a deliberately broken tree first to confirm it reports failures. `color-contrast` is disabled because jsdom paints nothing; that limitation is written into the PR rather than quietly omitted. | +| 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 {