Repository navigation
perf(insights): serve topic-filtered reads from prompt-grain rollups - #867
Conversation
gkhngyk
left a comment
There was a problem hiding this comment.
Strong work. The advisory lock fixes a real double-count, dropping the old signatures is the right call, and keeping 00098's mention_count write matters for the Topics page. Two changes before merge:
supabase/schema.sqlisn't regenerated, which is why CI is red. Runbash supabase/build-schema.sh.- Please take the sightings-only option you offered. Measured on production, the dense table would start at ~5.5M rows (~1 GB on a 4.7 GB database) and grow ~3.2M rows a month. Sightings carry every measure exactly, because non-visible elements contribute zero to all of them. The one exception is the per-competitor answer count, which can come from the topic's answers in
insights_prompt_daily, since each answer lists every tracked competitor. The only drift is for competitors added mid-window, which is acceptable. Extendinginsights_competitor_prompt_dailywith the measure columns avoids a new table.
We'll apply the migration and run the backfill on our side once it's ready; no production access needed from you.
|
Thanks again for this, @arambu1a. Following up on the earlier review — a few more things before merge:
Are you still able to pick this up? If we don't hear back by Thursday, we'll take it over on top of your branch and keep you credited as co-author — we have follow-up work (#923) that builds on these tables. |
|
Hi @gkhngyk I'll work on this today |
Topic-filtered Insights reads scanned raw prompt_results and unpacked every answer's competitor_mentions jsonb. On the largest topic (91 prompts, ~27k results) the topic detail page's aggregates ran 5-15s together, and ansvisor#861 kept the page up only by running them under the service role. 00139 adds the brand measures to insights_prompt_daily and the competitor measures to the insights_competitor_prompt_daily sightings, (brand_id, prompt_id, day) indexes on both, and p_topic_id on the seven *_daily read functions. With a topic they read the prompt-grain tables keyed through prompts.topic_id at read time, so a reassigned prompt still takes its history along; without one they return exactly what they did before. A competitor's answer count for a topic is the topic's answer count, since every answer lists every tracked competitor, so no dense per-answer table is needed. The old signatures are dropped so PostgREST does not see two overloads; competitor_aggregates_daily keeps 00113's plpgsql body and settings and visibility_rate_trend_daily keeps 00112's materialized CTEs. refresh_insights_daily takes a per-brand lock so overlapping refreshes cannot double a day, and the position math skips non-positive positions instead of aborting the refresh. dailyWindow() now routes topic calls to the rollups, every daily call passes p_topic_id, and getTopicDetail reads all time from the rollups on the caller's own client instead of the service role. The backfill script reports rows the refresh has not rewritten since 00139; topic views must not ship until it reports 0. Closes ansvisor#862
31ab976 to
c73dbbd
Compare
|
@gkhngyk thanks for the reviews. Everything's addressed and the branch is rebased onto current main:
Two things came up during the rebase:
Testing details are in the updated description: 336 raw-vs-rollup comparisons match on seeded data, including after moving a prompt between topics. |
|
Thanks, @arambu1a. This addresses everything, and your overlap notes are spot on. We're landing the #1035–#1049 stack first, since a lot of follow-up work builds on it. After that, this needs a new migration number (00139 is also used by #1053) and its |
Takes main's side: 00139 is taken on main, and refresh_insights_daily and the insights tables have moved on (00130, 00131, 00162). The change is rebuilt on top in the next commit. Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
Rebuilds ansvisor#867 on main. Topic-filtered Insights reads scanned raw prompt_results and unpacked every answer's competitor_mentions jsonb: on the largest topic (91 prompts, 35k answers) competitor_aggregates took 6-12 s for 30 days as a signed-in member, and the topic detail page's all-time reads 18 s and 11 s under the service role it fell back to. 00164 replaces ansvisor#867's 00139 (that number is taken on main): - insights_prompt_daily gains only what 00130 and 00131 didn't add (sum_visibility, sum_visibility_visible, max_created_at), the sightings sum_visibility and total_citations; (brand_id, prompt_id, day) indexes on both. - refresh_insights_daily is 00162's range-bounded body with ansvisor#867's per-brand lock (ansvisor#1020) and the new columns. - The seven aggregate reads are ansvisor#867's, with insights_aggregates_daily carrying 00131's citation, negative and position totals. - The three comparison reads main added since (same prompts 00149, change drivers 00148, platform compare 00133) take p_topic_id too, so a topic view compares the same whole days as a brand view. dailyWindow() routes topic calls to the rollups, every daily call passes p_topic_id, and getTopicDetail reads all time from the rollups on the caller's own client instead of the service role. The backfill script reports rows not rewritten since 00164. Co-authored-by: Jorge Arambula <[email protected]> Claude-Session: https://claude.ai/code/session_0121amRjX7UFrgmGELAtkc7A
gkhngyk
left a comment
There was a problem hiding this comment.
Rebuilt on main as promised, with you as co-author (659553c on top of a merge that takes main's side). Your design is unchanged. What moved:
- Migration:
00164_insights_topic_rollups.sqlreplaces 00139, which is taken on main. 00130/00131 had since added most of the prompt-grain columns, so 00164 adds only the rest:sum_visibility,sum_visibility_visibleandmax_created_at, plus the sightings'sum_visibilityandtotal_citations. - Refresh:
refresh_insights_dailyis 00162's body (it finds a range's answers through(brand_id, created_at)), with your per-brand lock, the> 0position guard and the new columns. - Read functions: The seven aggregate reads are yours.
insights_aggregates_dailyalso carries 00131's citation, negative and position totals. - Comparison reads: The three that main added since (same prompts, change drivers, platform compare) take
p_topic_idtoo. Their daily variants are reached throughcomparisonWindows, so without the topic they would have answered for the whole brand oncedailyWindowroutes topics to the rollups.
Applied and backfilled on production. 0 rows left unfilled in either prompt-grain table.
Checks on production:
- Brand level: 120 outputs of the ten functions are byte-identical before and after (4 brands, 7d, 30d and all time).
- Topic level: 10 raw and rollup reads compared on three topics, two brands and 7 and 30 days. All are identical, except that change drivers' arrays come back in a different order (
jsonb_aggwithoutORDER BY); they are equal once sorted. - Access: A user from another organization gets zero rows, or null from the definer functions.
Timings, largest topic (91 prompts), as a signed-in member:
| Read | Before | After |
|---|---|---|
competitor_aggregates, 30 days |
6.1–11.8 s | 0.59 s |
visibility_rate_trend, 30 days |
5.1 s | 0.56 s |
Topic detail, competitor_aggregates, all time |
18 s (service role) | 0.33 s |
Topic detail, visibility_rate_trend, all time |
11 s (service role) | 0.48 s |
| Same prompts / change drivers / platform, 30 days | — | 0.23 / 0.05 / 0.37 s |
getTopicDetail is back on the caller's own client. CI is green.
The topic page's best and worst prompts read the topic's last 50 runs through getPromptResults: every column of those rows (answers, citations, competitors, searches) sent to the browser, and every answer the topic ever had counted (count: 'exact', under RLS) for a total the page never showed. Once #867 moved the other reads to the rollups (00164), it was the one raw read over prompt_results left. getTopicRecentRuns reads the topic's prompts with their text, then the last 50 runs' prompt and visibility only, with no count: two queries instead of four, and the card shows the same. On the dev database's demo topic the response went from 91.6 KB to 13.7 KB. Co-authored-by: Cihan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
Summary
Topic-filtered Insights reads (topic detail page, topic filters on Insights and Competitors) now come from the daily rollups instead of scanning raw
prompt_resultsand unpacking every answer'scompetitor_mentionsjsonb, which took 5–15s on the largest topic. The seven*_dailyread functions takep_topic_idand read the prompt-grain tables throughprompts.topic_idat read time, so a prompt moved to another topic still takes its history along. Without a topic they return exactly what they did before.insights_prompt_dailygains the brand measuresinsights_brand_dailyholds, includingmentioning_answers,sum_visibility_visibleandmax_created_at, which the read functions also need.insights_competitor_prompt_daily(the sightings) gains the competitor measuresinsights_competitor_dailyholds:sum_visibility,total_citations,mention_answers,citation_answers,sum_inv_position,position_count. The existingmention_countfrom 00098 serves as total mentions and is still written. Non-visible elements contribute zero to all of these, so sightings carry them exactly. The per-competitor answer count (resultCount) comes from the topic's answers ininsights_prompt_daily, since each answer lists every tracked competitor. Every live competitor is listed for a topic, including ones the topic's answers never sighted. The only drift is for competitors added partway through the window. There is no new table.backfill-insights-daily.jsreports how many remain.*_dailysignatures are dropped before the functions are created.CREATE OR REPLACEwith an extra parameter would add a second overload, and every brand-level call that omitsp_topic_idwould then fail as ambiguous. Dropping the new signature too keeps the file re-runnable.competitor_aggregates_dailykeeps 00113's plpgsql body,work_mem 64MBandplan_cache_mode force_custom_plan, andvisibility_rate_trend_dailykeeps 00112's MATERIALIZED CTEs andwork_mem 64MB.refresh_insights_dailytakes a per-brand advisory lock. Without it, two overlapping refreshes of the same day (a backfill chunk and a run stamp) both commit their inserts and the day counts twice. Position math also skips non-positive positions instead of dividing by zero and aborting the brand's whole refresh.dailyWindow()routes topic calls to the rollups, and every daily call passesp_topic_id.getTopicDetailpasses an all-time day window (without one its calls never reach the rollups) and runs on the caller's own client again, removing the service-role stopgap from fix(topics): load large topics' detail under the service role #861 for that page.Closes #862
Rollout order
00139_insights_topic_rollups.sql.cd server && node src/scripts/backfill-insights-daily.jsuntil it reports 0 rows left.Topic views read the rollups as soon as the web deploys, so deploying the web app before the backfill finishes would show zeros on topic views.
Test plan
yarn lint,yarn typecheck,yarn format:checkpass (web and server)*_dailyfunctions withp_topic_idand that brand calls stay unscopedbash supabase/build-schema.sh:schema.sqlregeneratedrefresh_insights_daily: 336 raw-vs-rollup comparisons match. The comparisons cover all seven functions × brand/topic/topic × all-time and a 6-day window × no filter, model, region and platform filters, before and after moving a prompt to another topic without re-refreshingp_topic_idresolve to one function