Skip to content

fix(topics): load large topics' detail under the service role - #861

Merged
gkhngyk merged 1 commit into
mainfrom
fix/topic-detail-loads
Sep 30, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
fix/topic-detail-loads

Conversation

@gkhngyk

@gkhngyk gkhngyk commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Summary

The topic detail page (/dashboard/topics/<id>) failed with "Failed to load this topic" on the largest topics.

Cause

  • getTopicDetail runs the Insights summary, visibility trend, share of voice, competitor comparison and results loaders in parallel, all filtered by topic.
  • Topic-filtered reads cannot use the daily rollups, so they scan raw prompt_results over the topic's whole history.
  • On a 91-prompt topic with 27k results, competitor_aggregates took 7.2s and ai_visibility_aggregates 4.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.
  • Narrowing the window to 30 days does not save it: run together, the 30-day competitor aggregate still took 8.6s.

Fix (stopgap)

  • getTopicDetail checks access first, on the caller's own client. getTopicById filters by brand and topic under RLS; if it returns nothing, the action throws "Topic not found".
  • It then runs the aggregates on the service-role client, which now has a 120s statement timeout (fix(db): give service_role a 120s statement timeout #860).
  • A new lib/supabase/scoped.ts provides dbClient() / withDbClient(), an AsyncLocalStorage scope that puts that client in place for the call chain. tracking.ts now calls dbClient() where it called createClient(). Outside a withDbClient scope, dbClient() returns the caller's own client, so every other page behaves exactly as before.
  • The service-role client skips RLS. That is safe only because the brand and topic are checked first and every read in these loaders filters by brand_id: prompt results, the p_brand_id RPCs, brand domains, competitors and tracking runs. I checked each one.
  • The admin client is imported inside getTopicDetail rather 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

  • Bug fix

How to test

  1. Open /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".
  2. Open a small topic. It loads as quickly as before.
  3. Open a topic id that belongs to another brand, or doesn't exist. The page shows its error state; no data from another brand is returned.
  4. Other pages that use tracking.ts (Insights, Prompts, Competitors) behave as before.

Checklist

  • yarn build, yarn lint (no new warnings) and yarn format:check pass from web/
  • yarn test (363 passed) passes from web/

🤖 Generated with Claude Code

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.
@gkhngyk
gkhngyk merged commit 0b7ca8a into main Sep 30, 2026
6 checks passed
@gkhngyk
gkhngyk deleted the fix/topic-detail-loads branch September 30, 2026 17:23
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant