Repository navigation
fix(topics): load large topics' detail under the service role - #861
Merged
Merged
Conversation
The topic detail page failed to load on the largest topics. Topic- filtered reads cannot use the daily rollups, so they scan raw results over the topic's whole history; on a 91-prompt topic with 27k results the competitor and visibility aggregates ran 5-11s each when run together, past the authenticated role's 8s statement timeout. getTopicDetail now checks access first on the caller's own client — the topic must belong to the brand and the brand must pass RLS — and then runs the aggregates on the service-role client, which has 120s (migration 00100). A new lib/supabase/scoped puts that client in scope for the call chain; everywhere else dbClient() still returns the caller's client, so behaviour elsewhere is unchanged. Every read in these loaders filters by brand_id, which is what makes skipping RLS safe once the brand is checked. The page now loads in about 12-15s on the largest topic. Serving topic-filtered reads from prompt-grain rollups is the lasting fix.
7 of 10 tasks
arambu1a
added a commit
to arambu1a/ansvisor
that referenced
this pull request
Oct 15, 2026
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
gkhngyk
added a commit
that referenced
this pull request
Oct 17, 2026
…867) * perf(insights): serve topic-filtered reads from prompt-grain rollups 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 #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 #862 * perf(insights): serve topic-filtered reads from prompt-grain rollups Rebuilds #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 #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 #867's per-brand lock (#1020) and the new columns. - The seven aggregate reads are #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 --------- Co-authored-by: Gökhan Geyik <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The topic detail page (
/dashboard/topics/<id>) failed with "Failed to load this topic" on the largest topics.Cause
getTopicDetailruns the Insights summary, visibility trend, share of voice, competitor comparison and results loaders in parallel, all filtered by topic.prompt_resultsover the topic's whole history.competitor_aggregatestook 7.2s andai_visibility_aggregates4.8s when run alone. The competitor comparison runs its aggregate three times (displayed window, current week, previous week). Run together the calls take 5–11s each, past the authenticated role's 8s statement timeout. At 11:33 today four of them returned 500 at the same instant.Fix (stopgap)
getTopicDetailchecks access first, on the caller's own client.getTopicByIdfilters by brand and topic under RLS; if it returns nothing, the action throws "Topic not found".lib/supabase/scoped.tsprovidesdbClient()/withDbClient(), anAsyncLocalStoragescope that puts that client in place for the call chain.tracking.tsnow callsdbClient()where it calledcreateClient(). Outside awithDbClientscope,dbClient()returns the caller's own client, so every other page behaves exactly as before.brand_id: prompt results, thep_brand_idRPCs, brand domains, competitors and tracking runs. I checked each one.getTopicDetailrather than at module load, because it needs the service key the moment it is created.Result. Run concurrently under the service role on the largest topic, every call succeeds; the slowest takes 11.2s. The page should load in about 12–15s on that topic, and much faster on smaller ones.
Lasting fix (not in this PR). Serve topic-filtered reads from prompt-grain rollups so the page does not scan raw results at all. That brings it under a second, and this workaround can then be removed.
Related issue
None. Reported from production.
Type of change
How to test
/dashboard/topics/<id>for the largest topic of the largest brand. The page loads after a few seconds instead of showing "Failed to load this topic".tracking.ts(Insights, Prompts, Competitors) behave as before.Checklist
yarn build,yarn lint(no new warnings) andyarn format:checkpass fromweb/yarn test(363 passed) passes fromweb/🤖 Generated with Claude Code