← Back to Pull requests

feat: server-side nearHex color-distance sort for polish list, web and mobile color search #407

Closed
unknown closed this pull request without merging on Oct 23, 2026 00:52 UTC
View on GitHub
unknown unknown commented on Oct 23, 2026 00:30 UTC
Author

Follow-up from #399 (mobile By color): catalog color search fetched one page of a color family and ranked it on the device, so in a big family the best match could be missing. It turned out the web was worse. /polishes/search ranked the newest 50 color polishes. Polish detail "related shades" and Looks gap fills also ranked a newest-N page.

API: GET /api/polishes?nearHex=RRGGBB[,…]


  • Ordering: rows come back by OKLAB distance from the display hex (vendor > detected > name) to the nearest target. Nearest is first, ties break on shade id, and shades without a usable hex sort last.

  • Distance: each row carries colorDistance. It equals the shared colorDistance(resolveDisplayHex(p), target), so clients can grade it with the dupe thresholds.

  • Input: hexes may be written with or without #, comma-separated or repeated, up to 24. Anything else is a 400. Several targets rank by the nearest one, which is how web color search ranks a harmony palette in one query.

  • Scope: it only changes ORDER BY and adds the distance column. Visibility (POLISH_VISIBLE_SQL), all other filters, paging and COUNT() OVER() are untouched. It is part of the per-user list cache key, and sortBy/sortOrder are ignored when it is set.

  • polishes.ts diff: limited to query parsing, the select column and ORDER BY. The logic lives in the new lib/near-hex.ts.

  • GET /api/catalog/search: no change. Neither web nor mobile By color uses it; both use GET /api/polishes.
  • Why stored generated columns, not a query-time SQL function


    hex_to_oklab() already exists (migration 20261017024958000). I measured both options with EXPLAIN ANALYZE on a copy of the dev DB with 60k synthetic shades:

    | | ranking 60k rows (distance only) | full list query, pink family (5.2k rows) | full list query, whole catalog |
    |---|---|---|---|
    | default sort (createdAt) | n/a | 36.1 ms | 495 ms |
    | hex_to_oklab() per row at query time | 73 ms | 36.2 ms | 634 ms |
    | stored shade.oklab_l/a/b (this PR) | 9.5 ms | 37.6 ms | 526 ms |

  • Result: stored columns are ~8× cheaper for the ranking itself, and nearHex costs ~1.5 ms over the default sort on a family page (top-N heapsort).

  • Rest of the whole-catalog cost: that ~500 ms is the existing swatch LATERAL plus COUNT() OVER() over every row, and it is the same with or without nearHex. That is a possible follow-up, not part of this PR.

  • Migration: 20261023001520034_shade-display-oklab adds the three STORED GENERATED columns. They use the same trimmed display-hex expression as color_family, so every write path keeps them current. The Down section drops them. Up/Down/Up ran cleanly on 60k rows in ~1.1 s.
  • SQL ↔ TS parity test


    tests/near-hex.unit.test.cjs follows the same pattern as the color-family test:
  • Without a DB: it parses the transfer curve and both matrices out of hex_to_oklab() in docs/schema.sql and in its migration, and evaluates them in JS against the shared hexToOklab on 24 fixed hexes (tolerance 1e-12). Changing one coefficient by 1e-10 makes it fail; I checked.

  • With NEAR_HEX_SQL_TEST_DATABASE_URL: it also compares the live function and the list query's distance expression. I ran this locally against the bench DB and it passed.
  • Clients


  • Web /polishes/search: loads the whole owned color collection (listAllPolishes). Catalog rows come from one debounced nearHex query for the active color, the focused target, palette anchors and the raw (unsnapped) harmony targets (120 rows). Brand and finish filters go to the server. Client-side ranking stays only over that loaded set. The "collection" scope is now complete; before, it only held owned rows that happened to be among the newest 50.

  • Web detail related shades: nearHex=<display hex>&pageSize=6, minus the polish itself.

  • Web Looks: each per-family gap query sends that family's gap target hexes as nearHex, so it gets the nearest shades instead of the newest 60.

  • Mobile By color (catalog): nearHex=<picked>, narrowed only by the selected family chips. This replaces the 250-row "picked color's family" sample. catalogFamiliesFor is replaced by catalogColorQuery, and the tests are updated.
  • Verification


  • npm run typecheck, npm run lint (0 errors; the 11 warnings are all in files this PR doesn't touch), and unit tests for functions, shared, web and mobile.

  • Live check: a functions host against the 60k bench DB.

  • - nearHex=E0457B returned total 60,267 with the nearest at 0.0043, and a bad value got a 400.
    - In the browser, /polishes/search?color=E0457B rendered 20 owned + 120 server-ranked rows, with the top row matching the API's nearest.
  • access-control-reviewer: no findings. Visibility, the ui.user_id = $1 join, parameter binding, the fallback count and the per-user cache key are unchanged, and there is no injection path because hexes are validated and bound as numbers. Following its suggestion, the test now also asserts the caller join and $1.

  • docs-sync-checker: docs in sync.
  • Not verified:

  • /polishes/detail and /polishes/looks in the browser. Both stuck on their Suspense fallback in my local dev setup, and the detail page does the same with this PR's change reverted, so this predates the PR. Their logic is covered by unit tests (Looks) and typecheck only.

  • Mobile on a device or simulator.

  • Production-sized data. The benchmark used synthetic random hexes.
  • Rollout


    ALTER TABLE shade ADD COLUMN … GENERATED … STORED rewrites shade under an ACCESS EXCLUSIVE lock. On 60k rows the migration took ~1.1 s, and the prod catalog is smaller, but run it at a quiet time. Deploy runs npm run migrate before the functions deploy. A web build that ships before the new functions is harmless, because old functions ignore nearHex and return the default sort.

    The /create-migration skill can only be invoked by the user, so I created the migration with the repo's migrate:create script and hand-wrote the Down section and docs/schema.sql.

    🤖 Generated with Claude Code

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->
    <!-- coderabbit-ai-generated:v1 -->

    Summary by CodeRabbit

    New Features
    Color searches now find nearby catalog shades using the active color targets, with optional family, brand, and finish filters.
    Owned shades remain available alongside catalog matches, and inventory changes update search results.
    Related shades and missing colors in recommended looks are matched by color similarity.
    The polish API supports searches by up to 24 target colors and returns each result’s distance from its nearest target.

    Bug Fixes
    * Search results and related shades now reflect server-ranked color matches rather than ranking a limited set of results locally.
    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: mattmck Review duration: 21m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    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.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #407"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% 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: 52% (MEDIUM) · Higher = larger blast radius
    52%
    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: 56.8% · Lower = rushed or shallow review
    56.8%
    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: 22.5% · Safe to merge
    22.5%