← Back to Pull requests

Speed up AddGameToLibrary, cover/avatar removal, and the navbar avatar fetch #5047

Merged
connorshea merged 15 files (157 lines) on Nov 12, 2026 00:31 UTC
View on GitHub
connorshea connorshea commented on Nov 11, 2026 23:54 UTC
Author

<!-- claude-projects-attribution: {"github_login":"connorshea"} -->
_Requested by Connor · project thread_

Fixes the root causes Sentry showed for the three slow requests left after the sfo3 move. Numbers are sampled transactions from the last 3 days.

| Request | p50 | p95 |
| --- | --- | --- |
| AddGameToLibrary | 2.0s | 3.9s |
| RemoveGameCover | 3.7s | 5.6s |
| GetCurrentUserAvatar | 0.7s | 2.4s |

AddGameToLibrary

In trace 6307b543, two SELECT 1 FROM games WHERE pcgamingwiki_id = $1 AND id != $2 queries took 422ms and 249ms. They came from Game's uniqueness validation, run by Game#update_ratings after each library change, and it ran twice because the mutation did GamePurchase.create and then save.

  • Index games.pcgamingwiki_id. It was the only uniquely-validated external ID column without an index, so every game save did a sequential scan. The index is non-unique and built concurrently, so it can't fail on duplicates that may already be in prod.

  • update_ratings writes its columns directly. It now uses update_columns, skipping the per-external-ID uniqueness queries, the blocklist check and the search-document lookup, none of which a rating change can affect. It also skips the write when nothing changed. It still bumps updated_at like before.

  • Save the new library entry once. The mutation now uses GamePurchase.new + save instead of create + save.
  • RemoveGameCover / RemoveUserAvatar

    In trace 6beeba4a, the request waited 562ms + 1103ms on R2 deletes (purge is synchronous) plus the variant purges. Both mutations now use purge_later, which detaches right away and deletes the files in ActiveStorage::PurgeJob.

    GetCurrentUserAvatar

    The server work here is tiny: 6 queries, about 15ms when warm (the fastest samples are 14-50ms). The slow samples are wait time. In trace 8748e732, 850ms passed before the controller started, and there were 100-500ms gaps between queries. That's because the navbar fires the request on every full page load, alongside the page's 5-8 other queries, and they all compete for the same Puma worker. The avatar is already stored with the signed-in user, so this request never blocked rendering.

    The navbar now records when it last fetched the avatar (avatarCheckedAt on the stored user) and skips the request for an hour. Uploading an avatar in Settings forces a refresh. This takes one request out of most page-load bursts. The requests that still happen will still be as slow as whatever they run alongside.

    Tests

  • New specs: a game that fails its own validations still gets its rating updated; AddGameToLibrary recalculates ratings once; both remove mutations enqueue PurgeJob. Each one fails without its fix. Vitest covers the avatar throttle and the force flag.

  • Run locally: full RSpec suite (1534 examples, 0 failures), rubocop on the changed files, oxfmt, oxlint, vue-tsc, Vitest (648 passed).
  • After deploy

    The migration runs automatically. Nothing else to do.

    🤖 Generated with Claude Code

    https://claude.ai/code/session_0151yw9VkWFPsgxpvvGU42gs

    Diff: 157 lines (+143 / -14) across 15 files Reviewer: connorshea Review duration: 36m
    All Vouch review confidence checks passed
    Residual risk 0.18 = Change Risk (0.73) × (1 − Review Confidence (0.75)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.73 · 157 lines diff across 15 files
    0.73
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.83 · 1 substantive comment(s)
    0.83
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    75%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.303
    Self Review self_review
    0.140
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    3 items
    connorshea connorshea commented on Nov 12, 2026 00:02 UTC
    Reviewer

    Reviewed all five commits. No blocking issues found, and CI is green.

    Ratings (Game#update_ratings)

  • All four callers still go through it: GamePurchase after_create / after_update / after_destroy, and GameMergeService#handle_purchases. Game has no save callbacks of its own (Searchable/GlobalSearchable/CachedRowCount add none), and has_paper_trail already ignores avg_rating, ratings_count and updated_at, so update_columns drops nothing the old update did besides validations.

  • The early return compares a Float column with a BigDecimal#round(1) result. I checked every 0.0 to 100.0 step at one decimal place in Ruby and Float == BigDecimal matches for all of them, so it won't miss a write or loop.

  • The skip compares against the in-memory game, the same way the old update dirty check did, so a stale instance behaves the same as before.

  • It also fixes a quiet bug: before, a game that failed its own validations never had its rating updated (the new spec covers this).
  • AddGameToLibrary: new + save is right. The old create + save ran after_update (so update_ratings) a second time even with nothing changed. The error path is unchanged.

    Uniqueness / migration: the uniqueness validation is still there and now uses the index. algorithm: :concurrently + disable_ddl_transaction! is right, and the migrate job doesn't get DB_STATEMENT_TIMEOUT (only Puma sets it), so the build can't be cut short. If a concurrent build ever fails it leaves an INVALID index that blocks a rerun, but at this table size that's very unlikely. Non-unique is the safer choice; a unique index could follow after checking for duplicates.

    purge_later: the attachment row is deleted synchronously, so attached? is false and the response shows no cover/avatar straight away. One trade-off: with the :async adapter the job lives in Puma's memory, so a deploy or restart between the mutation and the job can leave an orphaned blob in R2. That's rare and the orphan cleanup task already handles it.

    Avatar throttle

  • Upload forces a refresh, and removal in Settings sets avatarUrl: null (keeping avatarCheckedAt), so both update the navbar straight away.

  • A moderator's "Remove avatar" on a profile page can't target their own profile (canFollow excludes it), so it can't leave the navbar stale.

  • setAuth replaces the stored user, so avatarCheckedAt doesn't carry over to a different account.

  • An avatar changed on another device can show for up to an hour. If the old file 404s, NavAvatar falls back to the initial. Fine as designed.

  • Nit, optional: sign-in already returns avatarUrl but doesn't set avatarCheckedAt, so the navbar still fetches once right after sign-in. Setting it in useAuth (password and passkey paths) would save that request. It's one request per sign-in, so I didn't push it.
  • Looks good to merge.

    ---
    _Generated by Claude Code_

    connorshea connorshea commented on Nov 12, 2026 00:03 UTC
    Author

    Thanks for the review. I'm leaving the optional nit about setting avatarCheckedAt at sign-in for now. It only saves one request per sign-in, and pushing it would re-run CI on a PR that's already green. If we touch useAuth again, I'll fold it in then.

    ---
    _Generated by Claude Code_

    Reviewers
    Assignees
    connorshea connorshea
    Labels
    risk: low confidence: 75.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 72.8% (HIGH) · Higher = larger blast radius
    72.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 75.4% · Lower = rushed or shallow review
    75.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.9% · Safe to merge
    17.9%