-
Notifications
You must be signed in to change notification settings - Fork 0
feat(search): indexed word search over recipes, ingredients and tags; indexed sorting #98
Conversation
- Search: full-text search on a generated tsvector of title and
description with a GIN index (config 'simple', no extension needed).
Every word must match as a word prefix, so "chicken rice" finds
"Rice with chicken". The query is built from letters and digits only,
so user input cannot break the tsquery syntax. Behaviour change: words
no longer match mid-word ("cake" does not find "pancakes").
- Highest rated: rating_avg/rating_count cached on recipes and kept in
step by a trigger on ratings (covers API, seed and manual SQL); the
touch trigger now ignores these columns so rating does not change a
recipe's updated time. Summaries read the cached values.
- Partial indexes for category, total time and rating whose order matches
each ORDER BY; the row query is skipped when the count is 0.
- npm run db:seed:large -- <n> | --remove loads or removes a generated
catalogue (never run by CI or deploy).
Measured locally on 100 000 recipes (EXPLAIN ANALYZE, median of 3):
highest rated 439 -> 0.1 ms, quickest 42 -> 0.1 ms, search count
94 -> 10 ms; whole GraphQL list requests 2-29 ms. Numbers and method in
docs/performance-and-images.md.
Closes #69
Closes #80
Following team review: the search document now covers title, description, ingredient names and tags. search_vector is a plain column kept current by a row trigger on recipes and statement-level triggers on recipe_ingredients/recipe_tags, so one search still hits one row per recipe (no duplicates, exact counts, same visibility rules). seed-large now runs VACUUM ANALYZE after loading (the triggers leave dead rows that made counts several times slower). Docs updated with new measurements and a warning to use a separate test database, never production. Refs #69, #80
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Requesting changes due to a couple of correctness issues that could cause regressions:
- Concurrent rating deadlocks:
rate()usesFOR SHARE, but the new trigger updates the same recipe row. Simultaneous ratings can deadlock and fail. Consider using a stronger lock before writing. - Stale cached data: Concurrent rating or ingredient/tag updates can overwrite cached values calculated from outdated snapshots. Serialize updates before recomputing aggregates and search vectors.
- Incomplete trigger handling: Moving ratings, ingredients, or tags between recipes does not properly refresh both affected recipes, potentially leaving incorrect ratings or search results.
- Search terms silently ignored:
toSearchQuery()limits searches to 8 words without informing users, potentially returning results that don't match the full query.
I'd recommend fixing the concurrency issues before merging and adding regression tests for simultaneous writes.
…arch word - rate() takes FOR NO KEY UPDATE instead of FOR SHARE: the ratings trigger updates the same recipe row, so two shared locks deadlocked. removeRating() takes the same lock first, in a transaction. - The rating and search-vector triggers lock the recipe row(s) (in id order) before recomputing, so a concurrent write is counted instead of being overwritten from a stale snapshot. - Moving a rating, ingredient or tag to another recipe refreshes both recipes (rating trigger also fires on recipe_id; update triggers use both transition tables). - toSearchQuery() no longer drops words after the eighth; repeated words are searched once, and the 200-character input limit bounds the query. - test:api: concurrent rate/remove through the API, interleaved raw-SQL writes on ratings, ingredients and tags, moved rows, and a 9-word search.
|
Thanks — all four were real. Fixed in the latest commit:
New
Note: I edited migration |
The previous issues appear fixed, but a potential deadlock remains: API and direct SQL writes can acquire locks in opposite orders. Please add a regression test and address this through consistent lock ordering or deadlock retries before merging. |
…lity # Conflicts: # README.md
The API locks a recipe before its ratings, ingredients or tags; a write outside the API (seed, manual SQL) locks the child row first and the recipe in its trigger, so the two can deadlock. Lock order cannot be forced on such writers, so transaction() now rolls back and retries a transaction that fails with 40P01 (deadlock) or 40001 (serialization), up to three attempts with a short jittered pause. test:api: a manual session locks a rating, the API rate() then waits for it while holding the recipe, and the manual update's trigger waits for the recipe. Before this change the API returned "deadlock detected"; now it retries, succeeds, and the cached rating counts both writes. Refs #69
|
Thanks, confirmed. I reproduced it as a test first, then fixed it in 3a239f0. The deadlock: the API locks the recipe and then a rating, ingredient or tag. A write outside the API (seed, manual SQL) locks the child row first, and its trigger then locks the recipe. Two such transactions can each wait for the other. Fix: deadlock retries. Regression test (
On the previous commit the API returns One remaining case: PostgreSQL aborts whichever side's deadlock check runs first. Usually that's the side that started waiting first. If that is the outside session, it gets the deadlock error. The seed and manual SQL should retry, or run when the API is idle. I don't think the API should depend on that. I also merged the latest
|
Changes
Search (also closes #80)
recipes.search_vector(GIN index, configsimple) covering title, description, ingredient names and tags. A row trigger onrecipesand statement-level triggers onrecipe_ingredients/recipe_tagskeep it current.soup &or(can never break the tsquery syntax (unit tests incl.Palačinke,bringebær,sunny-side-up).pg_trgmbecause it needs no database extension or extra privileges on CI/VM, and TASK.md asks for word search.Sorting and indexes
rating_avg/rating_countcached onrecipes, kept in step by a trigger onratings(covers API, seed and manual SQL); backfilled in the migration. Theupdated_attrigger now ignores these columns, so rating a recipe does not change its "last updated" time.ORDER BY. The row query is skipped when the count is 0.Scalability evidence
npm run db:seed:large -- <n>/-- --removeloads or removes a generated catalogue. Use a separate test database, never production (stated in the script and docs); never run by CI or deploy. RunsVACUUM ANALYZEafterwards.EXPLAIN ANALYZE, median of 3; "before" = old queries with the new indexes dropped, same data):Whole GraphQL list requests: 4–25 ms for typical searches/filters/sorts; very common words matching half the catalogue ("butter", 49 000 hits) 70–100 ms because exact counts visit every hit. Details in
docs/performance-and-images.md.On the team review comments: precomputing rating averages was kept because the benchmark shows the per-request aggregation was the slowest query (719 ms → 0.2 ms at 100k). Indexes were added only where
EXPLAINshowed sequential scans on the listing queries, not for every query.Validation
npm run checkpasses (217 unit tests);db:checkclean.test:db(12) andtest:api(17) against PostgreSQL 16; the new API test covers multi-word, prefix, Unicode, hostile input, ingredient and tag matches, no duplicates, private recipes, ingredient edits updating search, and the rating trigger (incl. unchangedupdatedAt).Remaining work
feature/search-multi-wordbranch is no longer needed and can be deleted.AI usage
Written with Claude Code (Anthropic) during the final-delivery review and extended after a teammate's review. Please review the diff as you would any other contribution.
Closes #69
Closes #80