Repository navigation
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
Conversation
…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]>
gkhngyk
left a comment
There was a problem hiding this comment.
Looks good, with follow-ups.
What I checked:
- Scope. The PR is two commits on 38ca76b (b8cdc85 and f643f07): 00290 and its
schema.sqlblock. There's no server or web change. Main has gained no migration since that base, so 00241 is still the latestmentions_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 newbrand_prevand thebrand_termsoutput is unchanged. The narrowed part only feedsbrand_terms[].prev_answers, and I found no input where it differs:term_counts_allnow counts the window only (:200,:208). The rows it no longer has are an entity's terms seen only in the window before, which hadanswers = 0.candidatesfiltersanswers > 0beforerow_number(), so the candidates,term_counts,brand_termsand their order are the same.- In
attributesand in the attributes'values, a missing row and a 0 row both come out ascoalesce(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_answerswascount(*) filter (where not r.cur)over the brand's unnested rows.brand_prevcounts the same rows (:249-251). - On the rollups, the old value summed
[v_prev_day, v_start_day).brand_prevsums 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(*)andsum(integer)are both bigint, as before, so the jsonb numbers are identical. - Nulls. A term is never null:
mention_termsbuilds terms from split words, andmentions_terms_daily.termisnot null. Soterm in (select …)andbp.term = bt.termdrop nothing. - Ties.
brand_termskeepsorder by answers desc, term limit 15, a total order with one row per term.brand_prevreads 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 byv_rollup, as the other CTEs' do, so the left join adds no rows. - A brand with no terms.
brand_termsis empty andbrand_prevreads nothing, so the field is[]as before.
- Security.
security definer,search_path 'public',work_mem,plan_cache_modeandstableare as in 00241.- The grants are unchanged: revoked from
public,anonandauthenticated, executable byservice_roleonly. - The access check stays in
mentions_perception(00241, untouched). The web (actions/mentions.ts:292) and the MCP tool (mcp/mentions.ts:637, afterownedBrand) call that function. - Every new read is filtered by
d.brand_id = p_brand_id, or comes fromrows_in, which is.
- The grants are unchanged: revoked from
- Signature. Unchanged: 7 arguments, same defaults.
mentions_perception,refresh_mentions_perception_snapshotandhealth_probecall it as before. No types to regenerate. - The index.
mentions_terms_daily_key_coverhas the old key's columns, order, uniqueness andnulls not distinct, plusinclude (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,entityfromshown, 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), bybrand_id,entity in (…)and a day range. Those are the same leading columns. - Its insert has no
on conflict. - Nothing in
server/orweb/names the index.
- The only other access is
- 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 slock_timeouton the drop (:73-77) are right. A failed run rolls back whole, thesetincluded.
- Autovacuum. The same three settings as 00236 gave the Insights rollups.
schema.sql. It's exactly whatbuild-schema.shbuilds, both from the PR's migrations and from main's plus 00290.- 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):
- Check the hand-built index's definition, not only that it's valid (
00290:59-69).create unique index if not existsaccepts 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.
- 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 concurrentlyanddrop index concurrentlycan'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 = 0also holds only for the session it ran in. - After the migration, run
vacuum (analyze) public.mentions_terms_daily, public.mentions_entities_dailyonce, 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.
|
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:
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.
So the fix is fewer elements: a prompt's terms grouped over time.
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;
An 🤖 Generated with Claude Code |
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:
This morning's health report timed
mentions_perception_liveat 10.9 s (30 days) and 8.9 s (90 days). The user's target is 3 s for every view.What changes
prev_answersof the brand's top terms.term_counts_allcounts the current window only. A newbrand_prevreads the window before for the brand's 15 terms shown.mentions_entities_daily, which is small.mentions_terms_daily's key carries the count (include (answers)), so the terms' sums can come from the index alone.mentions_terms_daily_key_coverreplaces 00231'smentions_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.mentions_entities_dailyhas no covering index; for it the gain is cleared dead rows and current statistics.mentions_terms_daily_key_coverexists but is invalid (a concurrent build that stopped part way), the migration refuses to drop the old key.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_oldand compared it with the new one, then dropped it. 1,296 parameter combinations returned identical jsonb:682 of them have terms, and 289 have a
prev_answersabove 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:Please time it on production after it's applied, cold if you can:
Please run it at 30 and 90 days, with the platform filter and with
p_search => 'tool'. The health probesmentions_perception_live30/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 featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): no web changesyarn typecheckpasses (run fromweb/): no web changesyarn format:checkpasses (run fromweb/): no web changesOther checks:
bash supabase/build-schema.sh:schema.sqlgains only 00290.npm run version:check(root) reports the docker-compose images at 0.2.0 against 0.3.0. This was already the case onmainand isn't touched here.Pre-push review
A review agent read the migration before the push. It confirmed:
brand_terms, union-all pruning;schema.sqlmatches byte for byte.Fixed from it:
🤖 Generated with Claude Code