Skip to content

perf(insights): serve topic-filtered reads from prompt-grain rollups - #867

Merged
gkhngyk merged 3 commits into
ansvisor:mainfrom
arambu1a:fix/topic-reads-from-rollups
Oct 17, 2026
Merged

gkhngyk merged 3 commits into
ansvisor:mainfrom
arambu1a:fix/topic-reads-from-rollups

Conversation

@arambu1a

@arambu1a arambu1a commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

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_results and unpacking every answer's competitor_mentions jsonb, which took 5–15s on the largest topic. The seven *_daily read functions take p_topic_id and read the prompt-grain tables through prompts.topic_id at 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_daily gains the brand measures insights_brand_daily holds, including mentioning_answers, sum_visibility_visible and max_created_at, which the read functions also need.
  • insights_competitor_prompt_daily (the sightings) gains the competitor measures insights_competitor_daily holds: sum_visibility, total_citations, mention_answers, citation_answers, sum_inv_position, position_count. The existing mention_count from 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 in insights_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.
  • The new columns are nullable with no default, so rows not yet backfilled read as NULL instead of a plausible zero. backfill-insights-daily.js reports how many remain.
  • Both old and new *_daily signatures are dropped before the functions are created. CREATE OR REPLACE with an extra parameter would add a second overload, and every brand-level call that omits p_topic_id would then fail as ambiguous. Dropping the new signature too keeps the file re-runnable.
  • Recreating the functions resets their settings, so competitor_aggregates_daily keeps 00113's plpgsql body, work_mem 64MB and plan_cache_mode force_custom_plan, and visibility_rate_trend_daily keeps 00112's MATERIALIZED CTEs and work_mem 64MB.
  • refresh_insights_daily takes 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 passes p_topic_id. getTopicDetail passes 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

  1. Apply migration 00139_insights_topic_rollups.sql.
  2. Run cd server && node src/scripts/backfill-insights-daily.js until it reports 0 rows left.
  3. Deploy the web app.

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:check pass (web and server)
  • Web (547) and server (1175) tests pass. New tests check that topic calls reach the *_daily functions with p_topic_id and that brand calls stay unscoped
  • bash supabase/build-schema.sh: schema.sql regenerated
  • Every migration applied in order to an empty Postgres 17 (PGlite), then 00139 applied a second time without errors
  • Seeded brand with two topics, six prompts and three competitors (one never sighted, plus a deleted competitor id in the jsonb), then refresh_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-refreshing
  • Brand-level outputs are identical to the pre-00139 function definitions on the same data
  • Brand-level calls by named arguments without p_topic_id resolve to one function
  • Run the backfill in production and confirm it reports 0 rows left
  • Compare raw vs rollup outputs for a few real topics on brands of different sizes
  • Open the largest topic's detail page after deploy and confirm it loads in under a second

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 2, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. supabase/schema.sql isn't regenerated, which is why CI is red. Run bash supabase/build-schema.sh.
  2. 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. Extending insights_competitor_prompt_daily with 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.

@gkhngyk

gkhngyk commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

Thanks again for this, @arambu1a. Following up on the earlier review — a few more things before merge:

  1. Renumber the migration to 00106 — 00101 is taken on main (00101_prompt_clusters.sql, already applied), and main is now at 00105. Nothing in 00102–00105 touches the rollup tables or functions, so a rebase + rename is safe.
  2. Still open from the last review: regenerate supabase/schema.sql (bash supabase/build-schema.sh) and switch to the sightings-only option instead of the dense insights_competitor_prompt_measures_daily table.
  3. create policy (lines 102–107) isn't re-runnable — add drop policy if exists … first, like the rest of the file.
  4. Please add the rollout order to the PR description: migration → backfill until it reports 0 rows left → web deploy. Topic views read the rollups as soon as the web deploys.

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.

@arambu1a

Copy link
Copy Markdown
Contributor Author

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
@arambu1a
arambu1a force-pushed the fix/topic-reads-from-rollups branch from 31ab976 to c73dbbd Compare October 15, 2026 08:54
@arambu1a

Copy link
Copy Markdown
Contributor Author

@gkhngyk thanks for the reviews. Everything's addressed and the branch is rebased onto current main:

  1. Migration number: renamed to 00139_insights_topic_rollups.sql. 00106 has been taken since your comment (main is at 00127), and open PRs claim 00123/00124 and 00128–00138, so I took the next free number. Happy to change it if you'd prefer another.
  2. schema.sql: regenerated with bash supabase/build-schema.sh.
  3. Sightings only: the dense insights_competitor_prompt_measures_daily table is gone. insights_competitor_prompt_daily gains the measure columns, and the per-competitor answer count comes from the topic's answers in insights_prompt_daily, as you suggested.
  4. Re-runnable: the create policy went away with the dense table. I also found that running the file a second time failed on create function, so it now drops the new 7-arg signatures as well as the old ones. Verified by applying it twice.
  5. Rollout order: added to the description.

Two things came up during the rebase:

  • 00110/00112/00113 changed competitor_aggregates_daily and visibility_rate_trend_daily after this PR was opened. Since this migration drops and recreates them, I carried those changes over: plpgsql + force_custom_plan + work_mem 64MB on the first, and the MATERIALIZED CTEs + work_mem 64MB on the second. Brand-level outputs are identical to the current definitions on the same data.
  • The open fix(insights): show the same visibility on the card, breakdown and leaderboard #1035–fix(insights): show No data, mark low samples and use the UI's locale #1049 stack overlaps with this one. Its 00130 adds mention_answers, citation_answers, sum_inv_position and position_count to the same two tables. I used the same names and types, so add column if not exists works in either order. But its 00130/00131 also redefine refresh_insights_daily, and 00131 does create or replace on the 6-arg insights_aggregates_daily. Whichever lands second needs to merge those two function bodies (this PR's lock, position guard and new columns, plus that stack's negative_count/sum_position columns). Otherwise one side's changes get lost, or a second insights_aggregates_daily overload appears.

Testing details are in the updated description: 336 raw-vs-rollup comparisons match on seeded data, including after moving a prompt between topics.

@gkhngyk

gkhngyk commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

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 refresh_insights_daily and *_daily bodies rebuilt on the stack's versions. We'll do that rebase on our side on top of your branch and keep you as co-author.

gkhngyk and others added 2 commits October 17, 2026 20:50
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 gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.sql replaces 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_visible and max_created_at, plus the sightings' sum_visibility and total_citations.
  • Refresh: refresh_insights_daily is 00162's body (it finds a range's answers through (brand_id, created_at)), with your per-brand lock, the > 0 position guard and the new columns.
  • Read functions: The seven aggregate reads are yours. insights_aggregates_daily also 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_id too. Their daily variants are reached through comparisonWindows, so without the topic they would have answered for the whole brand once dailyWindow routes 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_agg without ORDER 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.

@gkhngyk
gkhngyk merged commit a0f1dee into ansvisor:main Oct 17, 2026
5 checks passed
gkhngyk pushed a commit that referenced this pull request Oct 18, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-migration Adds or edits a migration — apply it to the hosted database

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(insights): serve topic-filtered reads from prompt-grain rollups

2 participants