Repository navigation
fix(db): faster topics_overview_window and mentions_perception_live (00536) - #2345
Merged
gkhngyk merged 1 commit intoNov 12, 2026
Merged
Conversation
…00536) Both reads already used daily rollups, but rollups at the answer's own grain (one row per prompt, engine, region and day; one per term, entity, platform, region and day), so a 90-day Topics window read about as many entries as the answers themselves. Three small rollups hold the same figures with engines and regions summed, rewritten by the same nightly refreshes and backfilled by the migration; the reads return the same results. The Perception read also runs without JIT, whose compile cost more than the read. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SvzkMf5TZg7yqwaSeMFba9
gkhngyk
approved these changes
Nov 12, 2026
gkhngyk
left a comment
Contributor
There was a problem hiding this comment.
LGTM: the refreshes and both reads match main's logic exactly. One thing before we apply it: the backfill (lines ~1026-1049) groups each source rollup in a single statement, and on production mentions_terms_daily is ~5.5M rows (1.5 GB). Through the Management API that will likely time out and roll the whole migration back. Please chunk the backfill (e.g. per brand in a DO loop before the function swap) or split it into a follow-up we can run in pieces, and create mentions_terms_daily_all_term after the backfill.
5 of 13 tasks
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 morning health report flagged two slow page reads on production:
topics_overview_windowat 90 days took 12.62 s and timed out.mentions_perception_liveat 30 days took 6.96 s, close to the timeout.The target is 3–4 s at most.
Why they were slow. Both already read daily rollups for whole days (00236, 00290). But those rollups are kept at the answer's own grain:
insights_prompt_dailyandinsights_competitor_prompt_dailyhave one row per prompt, engine, region and day.mentions_terms_dailyhas one row per term, entity, platform, region and day.So a day of rollup rows is about as many rows as a day of answers. A 90-day Topics window, plus the 90 days before it for the change, read about as many index entries as the raw answers would, and the cost grew in step with the window. Perception also read every brand term in the previous window, just to find the 15 terms it shows.
Perception's live read also paid for JIT compilation. The planner's estimate for the phrase check (the
not existsover the candidate terms) was far too high, so it passedjit_above_cost. Compiling then took longer than running the query: about 0.1 s of a 0.12 s read in local tests.What changed (migration 00536). Neither read uses the engine or the region when no filter is picked: the Topics tab has no such filter, and Perception's unfiltered view sums them all. So three small rollups keep the same figures with engines and regions summed:
topics_prompt_dailyinsights_prompt_dailytopics_competitor_dailyinsights_competitor_prompt_daily(mention counts)mentions_terms_daily_allmentions_terms_dailyrefresh_insights_dailyis the 00164 body with one block appended.refresh_mention_terms_dailyis the 00246 body with one delete and one insert added.topics_overview_window:topics_prompt_daily.topics_competitor_daily, summed per (prompt, competitor) before the topics and names are joined.mentions_perception_live:mentions_terms_daily_all.jit = off.brand-access-policies.test.js) and to the demo brand's rolled-up tables (server/src/lib/demo/core.js), since the same refreshes rebuild them.Before / after
Measured on a local Postgres 16 with every migration applied. The fixture is one brand with 200 prompts in 15 topics, 6 engines, 10 competitors and 200 days of rollups: about 216k
insights_prompt_daily, 647kinsights_competitor_prompt_dailyand 1.5Mmentions_terms_dailyrows. Warm cache, best of 5:topics_overview_window, 30 daystopics_overview_window, 90 daysmentions_perception_live, 30 days (as the probe calls it)mentions_perception_live, 90 daysOn this fixture, the new tables have 5.4×, 1.9× and 3.6× fewer rows than their sources:
Buffers per call dropped as well:
Production was not measured. The data there is larger and the cache colder, and the slowness was mostly I/O. If the local gains of about 7× and 6× carry over, the two reads would take roughly 2 s and 1 s. Growth with the window is also much flatter: 38 → 100 ms from 30 to 90 days, against 199 → 700 ms before.
Same results. The old functions were kept beside the new ones and compared on the fixture. Every case matched exactly, by row sets or
jsonbequality:After running both refreshes over three days, each new table matched a fresh aggregate of its source, with 0 mismatches. The repo has no harness that runs SQL in tests, so this check is not committed as a test.
Related issue
Health report:
topics_overview_window(90d) timed out, andmentions_perception_live(30d) was close to the budget.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 testsNeeds migration on prod: 00536
No concurrent index builds. The migration only creates three new tables, and their indexes are built as the backfill fills them. No index is added to an existing table.
Backfill cost. The backfill reads
insights_prompt_daily,insights_competitor_prompt_dailyandmentions_terms_dailyonce each. Run it with no statement timeout, outside the nightly refresh window.A refresh running during the apply finishes with its old definition, so its days are missing from the new tables. Re-run that brand and range afterwards:
After applying: run
vacuum analyzeon the three new tables, or let autovacuum visit them, so the first reads are index-only:How to test
Apply 00536 to a database that has rollups.
Time the report's probes for the two reads:
Open Topics with 7, 30 and 90 days. The figures, the daily chart and the competitor share should match what they showed before the migration.
Open Mentions → Perception with a custom date range, then with a platform filter. The figures should be unchanged.
After the next nightly refresh, check that the new tables still match their sources:
Checklist
feature/,fix/,chore/,docs/) — see CONTRIBUTING.mdyarn lintpasses (run fromweb/): no web files changedyarn typecheckpasses (run fromweb/): no web files changedyarn format:checkpasses (run fromweb/): no web files changedhelp/(or no user-visible change) — see help/README.mdChecks run:
supabase/build-schema.sh:schema.sqlregenerated and in sync.brand-access-functions.test.ts,actions/topic.test.ts,topic-trend.test.ts, and every web test that reads the migrations orschema.sql.brand-access-policies,health/report,insights-rollups,mentions-rollups, all oflib/demo, and every server test that reads the migrations.Generated by Claude Code