Skip to content

fix(db): faster topics_overview_window and mentions_perception_live (00536) - #2345

Merged
gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/slow-topics-overview-and-perception
Nov 12, 2026
Merged

gkhngyk merged 1 commit into
ansvisor:mainfrom
cihan-gyk:fix/slow-topics-overview-and-perception

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The morning health report flagged two slow page reads on production:

  • topics_overview_window at 90 days took 12.62 s and timed out.
  • mentions_perception_live at 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_daily and insights_competitor_prompt_daily have one row per prompt, engine, region and day.
  • mentions_terms_daily has 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 exists over the candidate terms) was far too high, so it passed jit_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:

New table Built from Grain
topics_prompt_daily insights_prompt_daily brand, day, prompt
topics_competitor_daily insights_competitor_prompt_daily (mention counts) brand, day, prompt, competitor
mentions_terms_daily_all mentions_terms_daily brand, entity, day, term (plus an index by term and day)
  • Refresh: the same nightly refreshes rewrite the new tables for the same days, in the same transaction.
    • refresh_insights_daily is the 00164 body with one block appended.
    • refresh_mention_terms_daily is the 00246 body with one delete and one insert added.
  • Backfill: the migration fills the new tables from the existing rollups.
  • Access and upkeep: RLS is on with no client policy, as for their sources. Autovacuum visits them about daily, as it does their sources, so reads stay index-only.
  • topics_overview_window:
    • Windows of two days or more read topics_prompt_daily.
    • The window's competitor mentions come from topics_competitor_daily, summed per (prompt, competitor) before the topics and names are joined.
    • The 24-hour window still reads the answers.
  • mentions_perception_live:
    • With no platform, country, topic or search filter, the shown entities' terms come from mentions_terms_daily_all.
    • The previous-window counts for the 15 brand terms shown also come from it, as 15 index lookups instead of a scan of every brand term.
    • Filtered views read exactly as before.
    • The function now runs with jit = off.
  • Unchanged: signatures, return shapes, grants and the brand-access check (00434). No caller changes. Prompts are still matched to topics at read time, so moving a prompt to another topic still moves its history.
  • Supporting edits: the new tables are added to the server-only brand tables list (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, 647k insights_competitor_prompt_daily and 1.5M mentions_terms_daily rows. Warm cache, best of 5:

Read Before After
topics_overview_window, 30 days 199 ms 38 ms
topics_overview_window, 90 days 700 ms 100 ms
mentions_perception_live, 30 days (as the probe calls it) 145 ms (55 ms with JIT off alone) 22 ms
mentions_perception_live, 90 days 244 ms 40 ms

On this fixture, the new tables have 5.4×, 1.9× and 3.6× fewer rows than their sources:

  • 216k → 40k;
  • 647k → 339k;
  • 1.5M → 416k.

Buffers per call dropped as well:

  • Perception at 30 days: from 3,384 to 752.
  • Topics at 90 days: from 9,254 to 5,181. On a one-brand table the planner seq-scans the small competitor table; on production it would read an index range.

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 jsonb equality:

  • Topics: 2, 7, 30, 90 and 180 days, plus two windows with an explicit end.
  • Perception: 7, 30 and 90 days, with and without an end, plus a platform filter and a country filter.

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, and mentions_perception_live (30d) was close to the budget.

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

Needs 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_daily and mentions_terms_daily once 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:

    select public.refresh_insights_daily('<brand_id>', '<day_from>', '<day_to>');
    select public.refresh_mention_terms_daily('<brand_id>', '<day_from>', '<day_to>');
  • After applying: run vacuum analyze on the three new tables, or let autovacuum visit them, so the first reads are index-only:

    vacuum analyze public.topics_prompt_daily, public.topics_competitor_daily, public.mentions_terms_daily_all;

How to test

  1. Apply 00536 to a database that has rollups.

  2. Time the report's probes for the two reads:

    select public.health_probe('<user_id>', '<brand_id>', 'topics_overview_window', 90);
    select public.health_probe('<user_id>', '<brand_id>', 'mentions_perception_live', 30);
  3. 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.

  4. Open Mentions → Perception with a custom date range, then with a platform filter. The figures should be unchanged.

  5. After the next nightly refresh, check that the new tables still match their sources:

    select count(*) from (
      select brand_id, day, prompt_id, sum(answer_count) from insights_prompt_daily group by 1, 2, 3
      except select brand_id, day, prompt_id, answer_count from topics_prompt_daily) x;  -- 0

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/): no web files changed
  • yarn typecheck passes (run from web/): no web files changed
  • yarn format:check passes (run from web/): no web files changed
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change) — see help/README.md

Checks run:

  • supabase/build-schema.sh: schema.sql regenerated and in sync.
  • Migration guard: 00536 is the only migration, and it needs the apply steps above.
  • Web vitest, 329 tests: brand-access-functions.test.ts, actions/topic.test.ts, topic-trend.test.ts, and every web test that reads the migrations or schema.sql.
  • Server vitest, all passing: brand-access-policies, health/report, insights-rollups, mentions-rollups, all of lib/demo, and every server test that reads the migrations.
  • Prettier and ESLint on the two server files touched.
  • The migration applies cleanly to a local Postgres 16, on top of every earlier migration.

Generated by Claude Code

…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
@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Nov 12, 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.

LGTM.

@gkhngyk
gkhngyk merged commit e430b96 into ansvisor:main Nov 12, 2026
13 checks passed

@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.

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.

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.

3 participants