Skip to content

perf(mentions): read the window before only for the brand's terms shown, and keep the terms' counts in their index, for the Perception tab's filtered views (00290) - #1542

Merged
gkhngyk merged 3 commits into
ansvisor:mainfrom
cihan-gyk:fix/perception-live-read
Oct 26, 2026

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The Perception tab's live read (every filtered view) reads less, with the same output. Migration 00290 only; no server or web change. A first step: see "If 90 days is still over 3 s" below.

What's slow

The default view (7/30/90 days, every platform and country, no topic or search) is served from #1385's snapshot. Every filtered view (a platform, a country, a topic or a search) still reads mentions_perception_live, and so does the default view when there's no fresh snapshot.

Measured on production on 2026-10-26, Ansvisor brand, read-only, in the browser:

View Time
Default, 30 days 1.2 s (snapshot)
Default, 90 days 1.1 s (snapshot)
ChatGPT only, 30 days 6.3 s
ChatGPT only, 90 days 8.7 s ×2 → "Couldn't load"
Search "tool", 30 days 8.5 s ×2 → "Couldn't load"

This morning's health report timed mentions_perception_live at 10.9 s (30 days) and 8.9 s (90 days). The user's target is 3 s for every view.

What changes

  1. The window before is read only for what the tab shows of it.
    • 00237 summed every shown entity's every term over both windows. Half of that read was the window before, and only 15 numbers from it are shown: the prev_answers of the brand's top terms.
    • Now term_counts_all counts the current window only. A new brand_prev reads the window before for the brand's 15 terms shown.
    • Each entity's mentions and co-mentions still come from mentions_entities_daily, which is small.
    • On the rollups (whole days, no topic or search): the window's terms for the 5 shown entities, plus only the brand's for the window before. That is about 6 entity-windows of rows instead of 10.
    • On the answers (topic, search, under two days): both windows are still read, because the mentions and co-mentions need them. Only the brand's answers from the window before are unnested, so this branch saves CPU, not I/O.
    • A platform or country filter is checked inside the key, after the day. So a filtered view still reads as many index entries as the default one.
  2. mentions_terms_daily's key carries the count (include (answers)), so the terms' sums can come from the index alone.
    • mentions_terms_daily_key_cover replaces 00231's mentions_terms_daily_key: same key, still unique, nulls not distinct.
    • refresh_mention_terms_daily's deletes use the same leading columns, so they still use it.
  3. Autovacuum runs on both rollups about daily, with 00236's settings for the Insights rollups.
    • Every refresh deletes and rewrites a range of days.
    • An index-only scan still goes to the table for pages that aren't all-visible yet.
    • mentions_entities_daily has no covering index; for it the gain is cleared dead rows and current statistics.
  4. Safe to apply after a hand-built index.
    • If mentions_terms_daily_key_cover exists but is invalid (a concurrent build that stopped part way), the migration refuses to drop the old key.
    • The drop gives up after 3 s (lock_timeout) rather than holding the Perception reads behind it.

Same output

On the dev DB I kept the old function as mentions_perception_live_old and compared it with the new one, then dropped it. 1,296 parameter combinations returned identical jsonb:

  • 2 end dates × 1/2/7/14/30/90 days;
  • platform: none / ChatGPT / Claude / AI Overviews;
  • country: none / US / TR;
  • topic: none / two topics;
  • search: none / two words.

682 of them have terms, and 289 have a prev_answers above 0, so the narrowed part was exercised. 00290 is applied on dev.

Deploy note (for gkhngyk)

On production, build the index by hand first. Unlike the migration's plain create index, it doesn't hold back the refreshes, and the migration then finds it in place:

set statement_timeout = 0;
create unique index concurrently if not exists mentions_terms_daily_key_cover
  on public.mentions_terms_daily (brand_id, entity, day, platform, region, term)
  include (answers) nulls not distinct;
-- must be true before the old key goes:
select indisvalid from pg_index where indexrelid = 'public.mentions_terms_daily_key_cover'::regclass;
drop index concurrently if exists public.mentions_terms_daily_key;

Please time it on production after it's applied, cold if you can:

explain (analyze, buffers)
select public.mentions_perception_live('<Ansvisor brand id>', now() - interval '90 days', now(), 'chatgpt-web');

Please run it at 30 and 90 days, with the platform filter and with p_search => 'tool'. The health probes mentions_perception_live 30/90 will show it in tomorrow's report too.

If 90 days is still over 3 s, the next step (a separate PR) is one of these. Your numbers will tell which one is needed.

Related issue

No GitHub issue. Follows #1385 / #1392 (Perception snapshots); the user's 3 s target for Mentions & Sentiment.

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

  1. Apply 00290 to a dev DB.
  2. Open Mentions › Perception and pick a platform, a country, a topic or a search. The figures are the same as before the migration.
  3. To compare directly, keep the old function under another name before applying 00290 (as above), and compare their jsonb for the same parameters.

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 changes
  • yarn typecheck passes (run from web/): no web changes
  • yarn format:check passes (run from web/): no web changes
  • Changes are focused — one concern per PR

Other checks:

  • bash supabase/build-schema.sh: schema.sql gains only 00290.
  • 00290 is re-applied on dev after the review fixes: it runs again cleanly, and the cover index is valid.
  • npm run version:check (root) reports the docker-compose images at 0.2.0 against 0.3.0. This was already the case on main and isn't touched here.

Pre-push review

A review agent read the migration before the push. It confirmed:

  • the output is the same: types, terms with no current answers, an empty brand_terms, union-all pruning;
  • the refresh's deletes still have an index;
  • schema.sql matches byte for byte.

Fixed from it:

  • an invalid hand-built index could have left the table with no unique key;
  • the drop now gives up after 3 s;
  • the vacuum settings now follow 00236;
  • the header and this description now say what each branch saves, instead of "half".

🤖 Generated with Claude Code

cihan-gyk and others added 2 commits October 26, 2026 13:43
…wn, and keep the terms' counts in their index, so the Perception tab's filtered views read about half as much (00290)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lid, give up the drop after 3 s, vacuum the rollups as 00236 does, and say what the read saves (pre-push review)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 26, 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, with follow-ups.

What I checked:

  • Scope. The PR is two commits on 38ca76b (b8cdc85 and f643f07): 00290 and its schema.sql block. There's no server or web change. Main has gained no migration since that base, so 00241 is still the latest mentions_perception_live (00237's read).
  • Same output. I diffed the function against 00241's, line by line. Everything outside term_counts_all, candidates, brand_terms, the new brand_prev and the brand_terms output is unchanged. The narrowed part only feeds brand_terms[].prev_answers, and I found no input where it differs:
    • term_counts_all now counts the window only (:200, :208). The rows it no longer has are an entity's terms seen only in the window before, which had answers = 0.
      • candidates filters answers > 0 before row_number(), so the candidates, term_counts, brand_terms and their order are the same.
      • In attributes and in the attributes' values, a missing row and a 0 row both come out as coalesce(tc.answers, 0). The spreads, the order, the 8 terms and the cells are the same.
    • On the answers (a topic, a search, a window under two days), the old prev_answers was count(*) filter (where not r.cur) over the brand's unnested rows. brand_prev counts the same rows (:249-251).
    • On the rollups, the old value summed [v_prev_day, v_start_day). brand_prev sums the same range with the same brand, platform and region filters (:254-264).
    • Zeros. A shown term with nothing before gets 0 either way (:327).
    • Types. count(*) and sum(integer) are both bigint, as before, so the jsonb numbers are identical.
    • Nulls. A term is never null: mention_terms builds terms from split words, and mentions_terms_daily.term is not null. So term in (select …) and bp.term = bt.term drop nothing.
    • Ties. brand_terms keeps order by answers desc, term limit 15, a total order with one row per term. brand_prev reads that same CTE, so the terms whose earlier counts it reads are exactly the 15 shown.
    • Duplicates. brand_prev's two branches exclude each other by v_rollup, as the other CTEs' do, so the left join adds no rows.
    • A brand with no terms. brand_terms is empty and brand_prev reads nothing, so the field is [] as before.
  • Security. security definer, search_path 'public', work_mem, plan_cache_mode and stable are as in 00241.
    • The grants are unchanged: revoked from public, anon and authenticated, executable by service_role only.
    • The access check stays in mentions_perception (00241, untouched). The web (actions/mentions.ts:292) and the MCP tool (mcp/mentions.ts:637, after ownedBrand) call that function.
    • Every new read is filtered by d.brand_id = p_brand_id, or comes from rows_in, which is.
  • Signature. Unchanged: 7 arguments, same defaults. mentions_perception, refresh_mentions_perception_snapshot and health_probe call it as before. No types to regenerate.
  • The index.
    • mentions_terms_daily_key_cover has the old key's columns, order, uniqueness and nulls not distinct, plus include (answers).
    • Both reads of the table need only the key's columns and answers, so both can be index-only scans:
      • term_counts_all: brand_id, entity from shown, a day range;
      • brand_prev: brand_id, 'brand', a day range, then term, platform and region as filters.
    • Nothing else relies on the old index.
      • The only other access is refresh_mention_terms_daily's delete (00246), by brand_id, entity in (…) and a day range. Those are the same leading columns.
      • Its insert has no on conflict.
      • Nothing in server/ or web/ names the index.
    • Writes. The index has the same entries, each a few bytes wider. The refresh's delete and insert of a few days per brand won't be noticeably slower.
    • The plain build. In the migration it's a plain create unique index, which holds the refreshes' writes while it builds. The deploy note builds it concurrently by hand first, and the migration then finds it in place.
    • Validity and lock. The validity check (:59-69) and the 3 s lock_timeout on the drop (:73-77) are right. A failed run rolls back whole, the set included.
  • Autovacuum. The same three settings as 00236 gave the Insights rollups.
  • schema.sql. It's exactly what build-schema.sh builds, both from the PR's migrations and from main's plus 00290.
    • It merges cleanly onto today's main.
    • Once #1536 (00289) or #1527's chain (00286–00288) merges, schema.sql conflicts at its end. That's the only conflicting file, and a rebuild puts 00290 after 00289.
  • Before the API deploy. This is a migration only, and nothing waits on the deploy. Merging before or after the apply changes no code path.

Follow-ups (none blocks the merge):

  1. Check the hand-built index's definition, not only that it's valid (00290:59-69).
    • create unique index if not exists accepts any index of that name.
    • So one built by hand without unique, or with other columns, passes the check, and the next statement drops the table's only unique key.
    • Fix: also raise when not indisunique or indnkeyatts <> 6 or indnatts <> 7.
  2. The deploy block (the description, and the header at :42-49) has to run one statement at a time, in one session, for example in psql.
    • create index concurrently and drop index concurrently can't run inside a transaction block.
    • A tool that sends the block as one query runs it as one transaction, so it fails there.
    • The set statement_timeout = 0 also holds only for the session it ran in.
    • After the migration, run vacuum (analyze) public.mentions_terms_daily, public.mentions_entities_daily once, so the index-only scans skip the heap from the first read. Until autovacuum reaches the latest days, the read still visits their heap pages, and a timing taken right after the apply would understate the gain.

Applied on prod. The cover index was built concurrently first, then 00290 found it and dropped the old key. Before the apply, the old and new functions were compared in a rolled-back transaction on 18 calls: the largest brand at 2 to 180 days, with and without a platform, a region, a topic or a search, a past window, a small brand and a brand with no terms. Every output was identical. After the apply, the largest brand's rollup views take 0.2–1.0 s warm (30 days 0.4 s, 90 days 1.0 s, ChatGPT at 90 days 0.4 s). A search is still the slow one: 2.4 s warm and much longer cold, as the description says. Autovacuum ran on both rollups right after the new settings.

@gkhngyk
gkhngyk merged commit f22fd7b into ansvisor:main Oct 26, 2026
4 of 5 checks passed
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

Thanks for applying 00290. I re-measured Perception on prod (Ansvisor brand, read-only, 13:34–13:36 UTC). The time is the server action's:

View Before 00290 Now
ChatGPT, 30 days 6.3 s 1.1 s
ChatGPT, 90 days 8.7 s, then error 1.1 s
Default, 90 days (snapshot) 1.1 s 0.8 s
Topic "AI Visibility", 90 days — 2.6 s
Search "brand", 30 / 90 days — 1.7 / 2.8 s
Search "tool", 30 days 8.5 s, then error 2.6 s
Search "tool", 90 days — 5.2 s (ChatGPT only: 4.3 s)

So the rollup views are done. What's left is the answers path (a topic or a search) at 90 days, which is over the 3 s target.

Where the time goes. I ran the path on a synthetic copy in a scratch schema on the dev DB (since dropped): one brand, 30 prompts, 7 platforms, 12 competitors, 100 days, about 73 terms a row.

  • Most of the time is unnesting the shown entities' terms and grouping them: 1.1M elements, about 0.8 s of 1.1 s warm.
  • Reading only the keys from a covering index, and unnesting straight from the table, gave the same output but saved little.
  • Counting term ids instead of text was only 1.3× faster.
  • The cold run was 4× the warm one.

So the fix is fewer elements: a prompt's terms grouped over time.

  • Option 1, a weekly rollup: per prompt, platform, region and entity, each ISO week's terms with their counts. Whole weeks come from it and the edge days from the answers. It stays live and exact for any window.
  • Option 2, per window: the 7/30/90-day sums per prompt, refreshed with 00241's snapshot. This reads the fewest elements, but it's as fresh as the snapshot.

Which one pays off depends on how alike a prompt's answers are from day to day. Random synthetic terms can't show that: they overlap about as much on any two days.

Could you run this read-only query on the largest brand? It's about one 90-day window.

with r as (
  select prompt_id, platform, region, entity, created_at, terms
  from public.mentions_answer_terms
  where brand_id = '<largest brand>' and created_at >= now() - interval '90 days'
)
select
  (select count(*) from r) as answer_rows,
  (select count(distinct prompt_id) from r) as prompts,
  (select sum(cardinality(terms)) from r) as elements,
  (select count(*) from (select distinct prompt_id, platform, region, entity,
     date_trunc('week', created_at at time zone 'utc'), t from r, unnest(terms) t) x) as weekly_distinct,
  (select count(*) from (select distinct prompt_id, platform, region, entity, t
     from r, unnest(terms) t) x) as window_distinct,
  pg_size_pretty(pg_total_relation_size('public.mentions_answer_terms')) as table_size;

elements / weekly_distinct is option 1's gain; elements / window_distinct is option 2's. If the weekly ratio is about 3× or more, I'll build option 1. Otherwise I'll build option 2.

An explain (analyze, buffers) of mentions_perception_live(<largest brand>, now() - interval '90 days', null, null, null, null, 'tool') would also show whether cold reads (TOAST, heap) matter as much there as they did here. It runs inside plpgsql, so it needs auto_explain with log_nested_statements, which the dev DB doesn't allow.

🤖 Generated with Claude Code

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