Skip to content

fix(mentions): read the Mentions table's window from its index alone - #1360

Merged
gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/mentions-list-speed
Oct 22, 2026
Merged

gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/mentions-list-speed

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The Mentions table (Mentions & Sentiment › Mentions) reads its window from an index alone, and only touches competitor_mentions when the table asks for competitors. The output is the same for every filter, sort and group.

Measured on prod on 2026-10-22, Ansvisor brand, read-only in the user's browser:

  • mentions_list took 8.4 s cold at 30 days, right at the 8 s statement timeout.
  • It took 4.9 s at 90 days, right after.

The user's target is every Mentions & Sentiment tab at 7/30/90 days in 3–4 s cold on the biggest brand.

Why it was slow. mentions_list (00158) read every mention in the window from the table, each with its competitor_mentions jsonb, to count the competitors named beside the brand. That count is only used by two of the table's choices: the "co-mentioned" sort and the Co-mentioned filter. The total, the prompt count and the page's order need none of it.

Migration 00239 (00239_mentions_list_index_only.sql):

  1. Covering index. idx_prompt_results_brand_mentions_cover: (brand_id, created_at desc) include (id, prompt_id, platform, region, sentiment) where mention_count > 0.
    • It replaces 00158's idx_prompt_results_brand_mentions, which had the same key and predicate. So every read that used that index can use this one: mentions_overview, Perception, and the content and citation reads.
    • The window CTE now selects only indexed columns, so on dev it is an Index Only Scan.
  2. competitor_mentions only when asked. It is read through a lateral join gated by v_competitors (p_sort = 'co_mentions' or p_competitor_id is not null).
    • Under force_custom_plan the planner folds that gate into a One-Time Filter: false, so otherwise no answer row is visited. This was checked with a prepared statement and a custom plan, as plpgsql runs it.
    • The page's 100 rows still read it, for the names shown beside each answer.
    • With the competitor sort or filter, the read costs what it does today.
  3. health_probe gains mentions_list and mentions_perception. Each is timed over the last p_days days. The server's morning report now times both at 30 and 90 days, last in its list (server/src/lib/health/report.js PROBES), so they read as cold as a first visit.

Apply on prod. Build the index by hand first, which doesn't hold back tracking's writes. The migration then finds it in place:

create index concurrently if not exists idx_prompt_results_brand_mentions_cover
  on public.prompt_results (brand_id, created_at desc)
  include (id, prompt_id, platform, region, sentiment)
  where mention_count > 0;
drop index concurrently if exists public.idx_prompt_results_brand_mentions;

Then apply 00239, then deploy the server (the new probes). Until 00239 is applied, the report's new probes fail with "unknown health probe".

@gkhngyk could you time mentions_list on prod after the index is built, cold, at 30 and 90 days on the biggest brand? For example, select public.health_probe('<member>', '<brand>', 'mentions_list', 30);.

Related issue

Page speed queue (user, 2026-10-22). Perception's part is #1325's 00237, which still needs to be applied on prod. No issue.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

Same output. On the dev DB, in one transaction that was then rolled back, I fingerprinted mentions_list (md5 of its jsonb) for 3,456 combinations, before and after 00239:

  • windows of 1, 30, 90 and 400 days;
  • every sort (newest, oldest, co_mentions, negative);
  • every group (none, prompt, platform);
  • sentiment none, positive and neutral;
  • competitor none, 'none' and a competitor;
  • platform and search on and off;
  • offsets 0 and 20.

All 3,456 are identical. 1,320 of them had rows, and 56,112 rows were compared in total.

Plan. On dev with seq and bitmap scans off, the window is an Index Only Scan using idx_prompt_results_brand_mentions_cover, and the competitor branch is One-Time Filter: false.

Probes. health_probe(…, 'mentions_list' | 'mentions_perception', 30 | 90) runs as the probe member and reads real rows. As that member, the 90-day list returns 142 mentions.

In the app. With 00239 on the dev DB, Mentions › Mentions at 30 and 90 days shows the same counts as before (87 / 142 responses, 5 / 7 prompts), with co-mentioned names on each row.

Tests: report.test.js (+1) checks that the Mentions & Sentiment probes run last, at 30 and 90 days.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/) — no web change
  • yarn typecheck passes (run from web/) — no web change
  • yarn format:check passes (run from web/) — no web change
  • Changes are focused — one concern per PR

Also run: server npm run format, npm run lint and npm test (2,030 tests); bash supabase/build-schema.sh (schema.sql included).

🤖 Generated with Claude Code

mentions_list read every mention in the window from prompt_results, each
with its competitor_mentions jsonb: 8.4 s cold at 30 days on the largest
brand. 00239 gives the brand-mentions partial index the window's columns
(id, prompt_id, platform, region, sentiment), replacing 00158's index with
the same key and predicate, and reads competitor_mentions only for the
co-mentioned sort or the competitor filter. The output is unchanged for
every filter, sort and group. health_probe and the morning report time
mentions_list and mentions_perception at 30 and 90 days.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk this is the Mentions tab's part of the user's 3–4 s target (Perception's part is 00237 on #1325). 00239 is checked on dev (3,456 filter/sort/group combinations identical, index-only window) and applied there. On prod: build the index concurrently first (SQL in the description), then 00239, then the server. Could you time mentions_list cold at 30 and 90 days on the biggest brand afterwards?

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 22, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good. I checked it on prod against the live function and found nothing blocking. Two notes on the apply steps and one on the description:

  1. Check the new index is valid before dropping the old one (PR body, "Apply on prod"; 00239_mentions_list_index_only.sql:21-27).

    • A create index concurrently that is cancelled (by a statement timeout, a deadlock or a cancel) leaves an INVALID index under the same name.
    • 00239's create index if not exists then skips it. If the old index was already dropped, the Mentions reads fall back to the non-partial (brand_id, created_at) indexes.
    • Add a step between the build and the drop: select indisvalid from pg_index where indexrelid = 'public.idx_prompt_results_brand_mentions_cover'::regclass; must be true. If it isn't, run drop index concurrently on it and build again.
    • Also say to run the build in a session with no statement timeout. It scans the whole 858 MB heap twice.
  2. The migration's own index statements may lock briefly. If 00239 is applied without the manual steps, the plain drop index takes an ACCESS EXCLUSIVE lock on prompt_results. Even after the manual steps, create index if not exists may take a brief SHARE lock before it finds the index. Neither is a problem outside the nightly tracking window. Saying so in the header would help whoever applies it.

  3. The description undersells the competitor filter.

    • It says that with the competitor sort or filter, "the read costs what it does today". On prod, today's mentions_list with p_competitor_id => 'none' at 90 days on the largest brand runs past 2 minutes, so users hit the 8 s timeout.
    • The cause: the planner estimates prompts_in at 42 rows (it has 733) and loops the competitor_mentions jsonb filter once per prompt.
    • This PR's version answers the same call in 0.44 s, and a named competitor in 0.48 s, because the jsonb filter now sits on the per-row primary-key lookup. Worth stating, since it's a real fix.

What I verified on prod, as an authenticated member of the largest brand, with a pg_temp copy of the new function in rolled-back transactions:

  • Same output. I compared the jsonb from both functions on 112 calls:
    • 46 each at 7 and 30 days: every sort × group × competitor (none, 'none', a competitor), plus sentiment, platform, search and offset 100;
    • 20 at 90 days, the same set without the competitor filter, because the live function times out on it.
    • All identical, 10,728 rows compared.
  • Timing. Live, warm: 0.08 s at 7 days, 0.18 s at 30 and 0.33 s at 90. The first touch at 90 days took 3.1 s.
    • The window read takes about one heap page per mention: about 7,000 buffers at 30 days and 14,000 at 90. That is the cold cost the covering index removes.
    • I couldn't time after the index, since I didn't build it on prod.
  • Index. The new index is about 4–5 MB for 45k mention rows, against 1.8 MB today. It duplicates nothing: the other (brand_id, created_at desc) indexes aren't partial.
  • Rest of the PR.
    • 00239 is free, and no other open PR uses it.
    • health_probe on prod matches 00236, so the new version keeps every existing probe.
    • Probe errors are kept per probe in report.js, so deploying the server before the migration only marks the four new rows red.

On production: idx_prompt_results_brand_mentions_cover was built concurrently (valid, 4.7 MB), the old partial index was dropped concurrently, and 00239 applied; its function bodies match the file. Three mentions_list reads compared identical before and after. Largest brand as a member: 7/30/90 days 0.04–0.05 s, and the none competitor filter at 90 days 0.41 s (it ran past the timeout before). Tested on top of main: web and server tests, tsc, lint and Prettier pass. The new health probes need the next server deploy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants