Repository navigation
perf(mentions): read the Perception tab's 30 and 90 days from daily rollups - #1325
Conversation
…ollups mentions_perception unnested every answer's terms for the window and the one before it on each call; on prod 30 and 90 days failed at the 8 s timeout. Migration 00231 counts them once a day instead: mentions_entities_daily (exact mentions and co-mentions per entity) and mentions_terms_daily (each entity's 200 most frequent terms a day, per platform and region), rebuilt by refresh_mention_terms_daily, which refresh_mention_terms calls for the same days. mentions_perception reads them for whole UTC days without a topic or search, and the answers' terms otherwise; history is filled in the migration. The deleted-prompt rebuild refreshes them too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk This is your #1124 follow-up: Perception's 30 and 90 days read daily rollups instead of unnesting every answer's terms twice. The tab failed on prod at 8.6 s at both ranges; numbers are in the description.
|
gkhngyk
left a comment
There was a problem hiding this comment.
A few fixes before merge:
-
The per-entity 200-term cap skews the attributes heat map.
supabase/migrations/00231_mentions_perception_rollups.sql:110-129I checked this on prod in a rolled-back transaction. I compared the live
mentions_perceptionwith a temp copy of this PR's read, running on rollups built by this PR's refresh, for the largest brand over 30 days:entitiesandco_mentionswere identical.brand_termswas within 1%, but two rows swapped places.attributeswas off. The low cells are a competitor's count for a term another entity uses a lot, and they came out 25–60% short: 424 → 178, 669 → 490, 518 → 374. The 7th and 8th attributes also swapped. With the top platform filter the pattern was the same: 119 → 68, 133 → 69.
The heat map is made of exactly those cross-entity cells, so the cap exaggerates the contrast the map is there to show.
Fix: apply the cap per
(day, platform, region)across all entities, not per entity. If a term is in any entity's top 200 that day, keep it for every entity in that partition:with c as materialized ( -- today's grouped counts: day, platform, region, entity, term, answers ), keep as ( select distinct day, platform, coalesce(region, '') as region_key, term from (select day, platform, region, term, row_number() over (partition by day, platform, region, entity order by answers desc, term) as rn from c) r where rn <= 200 ) insert into public.mentions_terms_daily (brand_id, day, platform, region, entity, term, answers) select p_brand_id, c.day, c.platform, c.region, c.entity, c.term, c.answers from c join keep k on k.day = c.day and k.platform = c.platform and k.region_key = coalesce(c.region, '') and k.term = c.term;
Use
coalescerather thanis not distinct fromhere, so the join can use a hash.I ran the same comparison with this change:
- The 15 brand terms and the 8 attributes match the raw read, in the same order.
- Every count is within 2 of the raw read, except one attribute row that is 2–5% short.
- Size: 36% more rows than this PR's cap for the shown entities over 60 days, and 56% more on a 2-day sample across all entities.
I wouldn't keep every term: that is 3.7× the rows, which is bigger than
mentions_answer_termsitself. Please also update the comments at lines 15-19 and 70. -
Don't fill the history inside the migration.
00231_mentions_perception_rollups.sql:487-508- Cost. Filling the largest brand alone (all entities, 11 calls) took about 90 s on prod into temp tables, which have no WAL and no unique index. All brands together hold about 1.6× its term volume: 12.9M term occurrences against 7.9M. So the one transaction would take roughly 2 minutes or more before WAL. That is at or over the 2-minute statement timeout of the SQL session we apply migrations from.
- Locks. For the whole transaction, the two
references public.brands(lines 34 and 50) hold a SHARE ROW EXCLUSIVE lock onbrands. That blocks every brand insert, update and delete until it commits. - No fallback.
mentions_perceptiondoesn't fall back to the raw read. Any window of 2+ days without a topic or search reads only the rollups (7d included), so a day that isn't filled yet just shows as empty.
Fix:
- Drop the
doblock. - Add a small script, e.g.
server/scripts/backfill-mention-terms-daily.js. It should walk each brand's first..last day inmentions_answer_termsthroughrefreshMentionTermsDaily. A 7-day call takes about 5–8 s on the largest brand. - Move the
mentions_perceptionreplacement (lines 225-485) into its own later migration, applied after the backfill. 00232–00236 are taken (main and open PRs), so use 00237 or the next free number.
-
The rollups have no unique key.
00231_mentions_perception_rollups.sql:33-61Only the advisory lock stops a day from being counted twice. 00192 added unique keys to
mentions_prompt_dailyandmentions_competitor_dailyafter that exact bug. Add:create unique index ... on mentions_entities_daily (brand_id, day, platform, region, entity) nulls not distinctcreate unique index ... on mentions_terms_daily (brand_id, entity, day, platform, region, term) nulls not distinct
Putting
entityfirst in the terms key also lets the read at lines 347-358 skip competitors that aren't shown: the largest brand has 19 entities and the tab shows 5. That index can then replaceidx_mentions_terms_daily_brand_day. -
Types.
web/src/types/supabase.tsis missing the two new tables. Please regenerate it.
The rest looks right:
- Server.
refresh_mention_termsrebuilds the same day's rollups in the same transaction. Calls are one day at a time, so this adds about 1 s on the busiest day.- The drain call at
server/src/lib/insights-rollups.js:126keeps the queue entry when it fails. - The tests cover the chunking and the failure path.
- Security.
refresh_mention_terms_dailyruns as the invoker and is revoked fromanonandauthenticated.mentions_perceptionkeeps its membership check, itssearch_pathand its grants.- The new tables have RLS on with no policies, the same as
insights_rollup_rebuilds.
Timings on prod (as owner, rolled back, temp tables):
| Window | This PR's cap | Cap from (1) | Current read |
|---|---|---|---|
| 30 days | 0.75 s | 0.95 s | 6.2–16.3 s |
| 30 days, top platform | 0.28 s | — | 7.5 s |
| 90 days (cap from (1), shown entities' rows only) | — | 1.36 s | — |
| 90 days, top platform | — | 0.37 s | — |
Apply order:
- The tables and refresh functions.
- The server deploy.
- The backfill.
- The read.
If the server is deployed before the DDL, the drain fails every 5 minutes and repeats the Insights refresh for the whole queued range each time. If the DDL lands well before the server, a prompt delete's queue entry is cleared without rebuilding these rollups. Running the backfill after the deploy repairs that.
…tion-rollup # Conflicts: # supabase/schema.sql
… the migration, key the rollups - 00231 keeps a term for every entity of a day, platform and region when it is among any entity's 200 most frequent there, so the attributes heat map's cross-entity cells aren't cut short. - Unique keys on both rollups (nulls not distinct); the terms' key leads with the entity for the read, and its rows are deleted by the days' entities. The (brand_id, day) indexes go. - No history fill in the migration: src/scripts/backfill-mention-terms-daily.js rebuilds each brand's history a week per call (refreshMentionTermsHistory), and the mentions_perception read moves to 00237, applied after it. - web/src/types/supabase.ts gets both tables. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@gkhngyk Thanks for the prod comparison. All four are in
On the dev DB, in that order (new 00231, backfill 6 weeks, 00237), the rollup read matched 00161's read under a temp name for 7, 30 and 90 days in a rolled-back transaction. Server: 2,014 tests. Web: 2,496 tests and the build pass. |
gkhngyk
left a comment
There was a problem hiding this comment.
All four earlier items are done:
- The term cap now applies across entities.
- No history fill runs inside the migration; there's a backfill script, and the read is split into 00237.
- Both tables have
nulls not distinctkeys, and the terms key leads withentity. supabase.tshas both tables.
On production
- 00231 is applied. The function bodies match the file, and both tables have RLS on with no grants beyond the service role.
refresh_mention_termsnow also fills the rollups, but nothing reads them yet.- 00237 stays unapplied until the AWS deploy and the backfill:
- Deploy the server.
- Run
node src/scripts/backfill-mention-terms-daily.jsfromserver/until it reports no failures. - Apply 00237, then time Perception at 30 and 90 days.
Testing: I merged main in and rebuilt schema.sql. Web and server tests, tsc, lint and Prettier pass.
|
@gkhngyk the Perception tab on prod still runs the old read. At ~16:50 UTC on the Ansvisor brand (read-only, in the user's browser): 90 days timed out cold at 8.7 s (500, "Couldn't load the perception figures"; 2.3 s warm on retry), 30 days took 6.4 s, 7 days 0.8 s. As your approval says, 00237 stays unapplied until these steps. Could you run them and post the 30- and 90-day timings?
Your 0.95 s (30d) and 1.36 s (90d) meet the user's target: every Mentions & Sentiment tab at 7/30/90 days under 3–4 s cold. The Mentions tab's list is next (30d 8.4 s, 90d 4.9 s): I'm opening a separate PR for it. |
|
@gkhngyk Perception is slow again on prod (Cihan measured it today, 2026-10-23, Ansvisor brand, read-only). Yesterday's 0.2 s / 0.7 s were probably warm reads.
The target is 2–3 s on a cold load. I'm opening a PR now with a nightly-refreshed snapshot of the default Perception view (brand × 7/30/90 days, no filters, read in ~50 ms). Filtered views keep the live rollup read, and the page gets an automatic retry. Could you check these on prod (read-only)?
|
Summary
Measured on prod on 2026-10-21 (read-only, in the browser, Ansvisor brand): Mentions → Perception at 30 and 90 days failed on every try at 8.6–8.7 s, the authenticated statement timeout. 24h loaded at 1.7 s and 7d at 3.1 s. Your #1124 review had the largest brand at ~10 s cold for 30 days.
mentions_perception(00161) unnestsmentions_answer_termsfor the window and the window before it on every call, so 30 days reads 60 days of per-answer term arrays and 90 days reads 180. This is your #1124 follow-up: the terms are now counted once a day, when they are written.Apply order (your review, 2026-10-22):
00231: the tables, their keys and the refresh functions.node src/scripts/backfill-mention-terms-daily.js(server).00237: the read.00231_mentions_perception_rollups.sqlmentions_entities_daily(brand, UTC day, platform, region, entity) holds the answers naming each entity and how many of those name the brand too. It is exact: the tab's mention counts, its top four competitors and its co-mentions come from here.mentions_terms_daily(brand, day, platform, region, entity, term) holds the answers next to each term.coalesce(region, '')so the join can hash.nulls not distinct), as 00192 gave the Mentions rollups:mentions_entities_daily_key;mentions_terms_daily_key, which leads with the entity so the read takes only the shown entities.(brand_id, day)indexes. Since the terms' key no longer starts with the day, the refresh deletes the terms' rows by the entities those days name (frommentions_entities_daily, before its own rows go).refresh_mention_terms_daily(brand, from, to)(service role) rebuilds a day range frommentions_answer_terms. It reads no answer text and holds its own advisory lock.refresh_mention_terms(00161) is unchanged except that it calls the new refresh at its end, in the same transaction. The run refresh and the nightly sweep keep the rollups current from the moment 00231 lands.brands.00237_mentions_perception_read_rollups.sql:mentions_perception, the same jsonb under the same rules.force_custom_plan).Server
src/scripts/backfill-mention-terms-daily.jswalks each brand's first..last day inmentions_answer_termsthroughrefreshMentionTermsHistory, a week per call (MENTION_TERMS_ROLLUP_CHUNK_DAYS). It is idempotent and restartable, withMENTION_TERMS_BACKFILL_PAUSE/MENTION_TERMS_BACKFILL_BRAND.insights-rollups.js) also callsrefresh_mention_terms_dailyfor the queued days, a week per call, and keeps the queue entry when it fails.Web.
web/src/types/supabase.tsgets both tables.Checked on the dev DB, in the apply order:
(brand_id, day)indexes).Then, in a rolled-back transaction, 00161's read under a temp name returned the same jsonb (minus
window) as the rollup read for 7, 30 and 90 days. The Perception tab loads at 7d/30d/90d.Your prod timings with the cap from (1): 30 days 0.95 s, 90 days 1.36 s, against 6.2–16.3 s for the current read.
Related issue
None. Reported by the user; this is the follow-up from #1124's review.
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
00231, deploy the server, runnode src/scripts/backfill-mention-terms-daily.js, then apply00237.Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/)yarn typecheckpasses (run fromweb/)yarn format:checkpasses (run fromweb/)Server:
npm run format,npm run lintandnpm test(170 files, 2,014 tests) pass. Web: 2,496 tests andyarn buildpass.bash supabase/build-schema.shwas run (00231 and 00237 in order).🤖 Generated with Claude Code