Skip to content

perf(mentions): read the Perception tab's 30 and 90 days from daily rollups - #1325

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:fix/mentions-perception-rollup
Oct 22, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:fix/mentions-perception-rollup

Conversation

@cihan-gyk

@cihan-gyk cihan-gyk commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Measured on prod on 2026-10-21 (read-only, in the browser, Ansvisor brand): Mentions → Perception at 30 and 90 days failed on every try at 8.6–8.7 s, the authenticated statement timeout. 24h loaded at 1.7 s and 7d at 3.1 s. Your #1124 review had the largest brand at ~10 s cold for 30 days.

mentions_perception (00161) unnests mentions_answer_terms for the window and the window before it on every call, so 30 days reads 60 days of per-answer term arrays and 90 days reads 180. This is your #1124 follow-up: the terms are now counted once a day, when they are written.

Apply order (your review, 2026-10-22):

  1. 00231: the tables, their keys and the refresh functions.
  2. The server deploy.
  3. node src/scripts/backfill-mention-terms-daily.js (server).
  4. 00237: the read.

00231_mentions_perception_rollups.sql

  • mentions_entities_daily (brand, UTC day, platform, region, entity) holds the answers naming each entity and how many of those name the brand too. It is exact: the tab's mention counts, its top four competitors and its co-mentions come from here.
  • mentions_terms_daily (brand, day, platform, region, entity, term) holds the answers next to each term.
    • A term is kept when it is among any entity's 200 most frequent that day, platform and region, and then for every entity there.
    • The attributes heat map compares entities on the same terms, so the cap no longer cuts a competitor's count of a term another entity uses a lot. Your fix, with coalesce(region, '') so the join can hash.
  • One row per key on both tables (nulls not distinct), as 00192 gave the Mentions rollups:
    • mentions_entities_daily_key;
    • mentions_terms_daily_key, which leads with the entity so the read takes only the shown entities.
    • They replace the (brand_id, day) indexes. Since the terms' key no longer starts with the day, the refresh deletes the terms' rows by the entities those days name (from mentions_entities_daily, before its own rows go).
  • refresh_mention_terms_daily(brand, from, to) (service role) rebuilds a day range from mentions_answer_terms. It reads no answer text and holds its own advisory lock.
  • refresh_mention_terms (00161) is unchanged except that it calls the new refresh at its end, in the same transaction. The run refresh and the nightly sweep keep the rollups current from the moment 00231 lands.
  • No history fill in the migration, so there's no long transaction holding a lock on brands.

00237_mentions_perception_read_rollups.sql: mentions_perception, the same jsonb under the same rules.

  • It reads the rollups for whole UTC days (2+ days) with no topic and no search, with the platform and country filters.
  • A window under two days, or one filtered by topic or search, reads the answers' terms as before. The branch not taken is pruned (force_custom_plan).
  • It doesn't fall back to the terms, which is why it lands after the backfill.

Server

  • src/scripts/backfill-mention-terms-daily.js walks each brand's first..last day in mentions_answer_terms through refreshMentionTermsHistory, a week per call (MENTION_TERMS_ROLLUP_CHUNK_DAYS). It is idempotent and restartable, with MENTION_TERMS_BACKFILL_PAUSE / MENTION_TERMS_BACKFILL_BRAND.
  • The deleted-prompt rebuild (00192 queue, insights-rollups.js) also calls refresh_mention_terms_daily for the queued days, a week per call, and keeps the queue entry when it fails.

Web. web/src/types/supabase.ts gets both tables.

Checked on the dev DB, in the apply order:

  1. The new 00231 (after dropping the old (brand_id, day) indexes).
  2. The backfill: 6 weeks for the demo brand.

Then, in a rolled-back transaction, 00161's read under a temp name returned the same jsonb (minus window) as the rollup read for 7, 30 and 90 days. The Perception tab loads at 7d/30d/90d.

Your prod timings with the cap from (1): 30 days 0.95 s, 90 days 1.36 s, against 6.2–16.3 s for the current read.

Related issue

None. Reported by the user; this is the follow-up from #1124's review.

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

How to test

  1. Apply 00231, deploy the server, run node src/scripts/backfill-mention-terms-daily.js, then apply 00237.
  2. Open Mentions → Perception. 30d and 90d should load well under 8 s, with the same terms, brand shape, heat map and co-mentions as before.
  3. Add a topic or a search, or pick 24h. These read the answers as before.
  4. Delete a prompt. After the nightly drain, its terms leave the 30/90-day view.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Server: npm run format, npm run lint and npm test (170 files, 2,014 tests) pass. Web: 2,496 tests and yarn build pass. bash supabase/build-schema.sh was run (00231 and 00237 in order).

🤖 Generated with Claude Code

…ollups

mentions_perception unnested every answer's terms for the window and the
one before it on each call; on prod 30 and 90 days failed at the 8 s
timeout. Migration 00231 counts them once a day instead:
mentions_entities_daily (exact mentions and co-mentions per entity) and
mentions_terms_daily (each entity's 200 most frequent terms a day, per
platform and region), rebuilt by refresh_mention_terms_daily, which
refresh_mention_terms calls for the same days. mentions_perception reads
them for whole UTC days without a topic or search, and the answers'
terms otherwise; history is filled in the migration. The deleted-prompt
rebuild refreshes them too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk This is your #1124 follow-up: Perception's 30 and 90 days read daily rollups instead of unnesting every answer's terms twice. The tab failed on prod at 8.6 s at both ranges; numbers are in the description.

  • Migration 00231 (00229 is feat(content): assign, mark as a priority or hide a Content plan row #1321's, 00230 is feat(content): start from the prompts AI doesn't name or cite the brand for yet #1323's) adds two rollup tables and refresh_mention_terms_daily.

    • refresh_mention_terms calls the new refresh at its end, in the same transaction.
    • mentions_perception reads the rollups for whole days without a topic or search.
    • The history is filled at the end of the migration.
  • On the dev DB the output was byte-identical for five calls before and after. Emptying the rollups proved they are what 30d reads.

  • Please time on prod:

    1. the backfill;
    2. 30 and 90 days on the largest brand;
    3. the two tables' sizes.

    The 200-terms-per-day cap is there to bound them. If the backfill is too heavy in one migration, I'll move it to a per-day script.

  • Server: the deleted-prompt rebuild also refreshes these rollups, a week per call.

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

A few fixes before merge:

  1. The per-entity 200-term cap skews the attributes heat map. supabase/migrations/00231_mentions_perception_rollups.sql:110-129

    I checked this on prod in a rolled-back transaction. I compared the live mentions_perception with a temp copy of this PR's read, running on rollups built by this PR's refresh, for the largest brand over 30 days:

    • entities and co_mentions were identical.
    • brand_terms was within 1%, but two rows swapped places.
    • attributes was off. The low cells are a competitor's count for a term another entity uses a lot, and they came out 25–60% short: 424 → 178, 669 → 490, 518 → 374. The 7th and 8th attributes also swapped. With the top platform filter the pattern was the same: 119 → 68, 133 → 69.

    The heat map is made of exactly those cross-entity cells, so the cap exaggerates the contrast the map is there to show.

    Fix: apply the cap per (day, platform, region) across all entities, not per entity. If a term is in any entity's top 200 that day, keep it for every entity in that partition:

    with c as materialized (
      -- today's grouped counts: day, platform, region, entity, term, answers
    ),
    keep as (
      select distinct day, platform, coalesce(region, '') as region_key, term
      from (select day, platform, region, term,
                   row_number() over (partition by day, platform, region, entity
                                      order by answers desc, term) as rn
            from c) r
      where rn <= 200
    )
    insert into public.mentions_terms_daily (brand_id, day, platform, region, entity, term, answers)
    select p_brand_id, c.day, c.platform, c.region, c.entity, c.term, c.answers
    from c
    join keep k on k.day = c.day and k.platform = c.platform
               and k.region_key = coalesce(c.region, '') and k.term = c.term;

    Use coalesce rather than is not distinct from here, so the join can use a hash.

    I ran the same comparison with this change:

    • The 15 brand terms and the 8 attributes match the raw read, in the same order.
    • Every count is within 2 of the raw read, except one attribute row that is 2–5% short.
    • Size: 36% more rows than this PR's cap for the shown entities over 60 days, and 56% more on a 2-day sample across all entities.

    I wouldn't keep every term: that is 3.7× the rows, which is bigger than mentions_answer_terms itself. Please also update the comments at lines 15-19 and 70.

  2. Don't fill the history inside the migration. 00231_mentions_perception_rollups.sql:487-508

    • Cost. Filling the largest brand alone (all entities, 11 calls) took about 90 s on prod into temp tables, which have no WAL and no unique index. All brands together hold about 1.6× its term volume: 12.9M term occurrences against 7.9M. So the one transaction would take roughly 2 minutes or more before WAL. That is at or over the 2-minute statement timeout of the SQL session we apply migrations from.
    • Locks. For the whole transaction, the two references public.brands (lines 34 and 50) hold a SHARE ROW EXCLUSIVE lock on brands. That blocks every brand insert, update and delete until it commits.
    • No fallback. mentions_perception doesn't fall back to the raw read. Any window of 2+ days without a topic or search reads only the rollups (7d included), so a day that isn't filled yet just shows as empty.

    Fix:

    • Drop the do block.
    • Add a small script, e.g. server/scripts/backfill-mention-terms-daily.js. It should walk each brand's first..last day in mentions_answer_terms through refreshMentionTermsDaily. A 7-day call takes about 5–8 s on the largest brand.
    • Move the mentions_perception replacement (lines 225-485) into its own later migration, applied after the backfill. 00232–00236 are taken (main and open PRs), so use 00237 or the next free number.
  3. The rollups have no unique key. 00231_mentions_perception_rollups.sql:33-61

    Only the advisory lock stops a day from being counted twice. 00192 added unique keys to mentions_prompt_daily and mentions_competitor_daily after that exact bug. Add:

    • create unique index ... on mentions_entities_daily (brand_id, day, platform, region, entity) nulls not distinct
    • create unique index ... on mentions_terms_daily (brand_id, entity, day, platform, region, term) nulls not distinct

    Putting entity first in the terms key also lets the read at lines 347-358 skip competitors that aren't shown: the largest brand has 19 entities and the tab shows 5. That index can then replace idx_mentions_terms_daily_brand_day.

  4. Types. web/src/types/supabase.ts is missing the two new tables. Please regenerate it.

The rest looks right:

  • Server.
    • refresh_mention_terms rebuilds the same day's rollups in the same transaction. Calls are one day at a time, so this adds about 1 s on the busiest day.
    • The drain call at server/src/lib/insights-rollups.js:126 keeps the queue entry when it fails.
    • The tests cover the chunking and the failure path.
  • Security.
    • refresh_mention_terms_daily runs as the invoker and is revoked from anon and authenticated.
    • mentions_perception keeps its membership check, its search_path and its grants.
    • The new tables have RLS on with no policies, the same as insights_rollup_rebuilds.

Timings on prod (as owner, rolled back, temp tables):

Window This PR's cap Cap from (1) Current read
30 days 0.75 s 0.95 s 6.2–16.3 s
30 days, top platform 0.28 s — 7.5 s
90 days (cap from (1), shown entities' rows only) — 1.36 s —
90 days, top platform — 0.37 s —

Apply order:

  1. The tables and refresh functions.
  2. The server deploy.
  3. The backfill.
  4. The read.

If the server is deployed before the DDL, the drain fails every 5 minutes and repeats the Insights refresh for the whole queued range each time. If the DDL lands well before the server, a prompt delete's queue entry is cleared without rebuilding these rollups. Running the backfill after the deploy repairs that.

cihan-gyk and others added 2 commits October 22, 2026 12:50
…tion-rollup

# Conflicts:
#	supabase/schema.sql
… the migration, key the rollups

- 00231 keeps a term for every entity of a day, platform and region when it
  is among any entity's 200 most frequent there, so the attributes heat
  map's cross-entity cells aren't cut short.
- Unique keys on both rollups (nulls not distinct); the terms' key leads
  with the entity for the read, and its rows are deleted by the days'
  entities. The (brand_id, day) indexes go.
- No history fill in the migration: src/scripts/backfill-mention-terms-daily.js
  rebuilds each brand's history a week per call (refreshMentionTermsHistory),
  and the mentions_perception read moves to 00237, applied after it.
- web/src/types/supabase.ts gets both tables.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Thanks for the prod comparison. All four are in 05b32885, on top of a merge of main (54fdc09e; only schema.sql conflicted, rebuilt):

  1. Cap across entities, your query: a term among any entity's 200 that day, platform and region is kept for every entity there, joined on coalesce(region, ''). The comments at the top and on the table say so.
  2. No backfill in the migration.
    • The do block is gone. src/scripts/backfill-mention-terms-daily.js walks each brand's first..last day in mentions_answer_terms through refreshMentionTermsHistory, a week per call.
    • The read moved to 00237.
    • The PR description lists the apply order: DDL → server → backfill → read.
  3. Unique keys: mentions_entities_daily_key and mentions_terms_daily_key (entity first), nulls not distinct. They replace both (brand_id, day) indexes. Since the terms' key no longer starts with the day, refresh_mention_terms_daily deletes the terms' rows by the entities those days name (read from mentions_entities_daily before its rows go), rather than a day range that would walk every day of the brand.
  4. Types: both tables are in web/src/types/supabase.ts.

On the dev DB, in that order (new 00231, backfill 6 weeks, 00237), the rollup read matched 00161's read under a temp name for 7, 30 and 90 days in a rolled-back transaction. Server: 2,014 tests. Web: 2,496 tests and the build pass.

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

All four earlier items are done:

  • The term cap now applies across entities.
  • No history fill runs inside the migration; there's a backfill script, and the read is split into 00237.
  • Both tables have nulls not distinct keys, and the terms key leads with entity.
  • supabase.ts has both tables.

On production

  • 00231 is applied. The function bodies match the file, and both tables have RLS on with no grants beyond the service role.
  • refresh_mention_terms now also fills the rollups, but nothing reads them yet.
  • 00237 stays unapplied until the AWS deploy and the backfill:
    1. Deploy the server.
    2. Run node src/scripts/backfill-mention-terms-daily.js from server/ until it reports no failures.
    3. Apply 00237, then time Perception at 30 and 90 days.

Testing: I merged main in and rebuilt schema.sql. Web and server tests, tsc, lint and Prettier pass.

@gkhngyk
gkhngyk merged commit 47a7477 into ansvisor:main Oct 22, 2026
4 of 5 checks passed
@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk the Perception tab on prod still runs the old read. At ~16:50 UTC on the Ansvisor brand (read-only, in the user's browser): 90 days timed out cold at 8.7 s (500, "Couldn't load the perception figures"; 2.3 s warm on retry), 30 days took 6.4 s, 7 days 0.8 s. As your approval says, 00237 stays unapplied until these steps. Could you run them and post the 30- and 90-day timings?

  1. Deploy the server (AWS).
  2. From server/, run node src/scripts/backfill-mention-terms-daily.js until it reports no failures.
  3. Apply 00237.

Your 0.95 s (30d) and 1.36 s (90d) meet the user's target: every Mentions & Sentiment tab at 7/30/90 days under 3–4 s cold. The Mentions tab's list is next (30d 8.4 s, 90d 4.9 s): I'm opening a separate PR for it.

@cihan-gyk

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Perception is slow again on prod (Cihan measured it today, 2026-10-23, Ansvisor brand, read-only). Yesterday's 0.2 s / 0.7 s were probably warm reads.

Window First load Retry
30 days 8.7 s → "Couldn't load" (500) 5.3 s
90 days 8.1 s (just under the timeout) —
7 days 1.0 s —

The target is 2–3 s on a cold load. I'm opening a PR now with a nightly-refreshed snapshot of the default Perception view (brand × 7/30/90 days, no filters, read in ~50 ms). Filtered views keep the live rollup read, and the page gets an automatic retry.

Could you check these on prod (read-only)?

  1. Is 00237 live?
    select position('mentions_entities_daily' in prosrc) > 0 from pg_proc where proname = 'mentions_perception';
  2. Are the rollups filled up to yesterday for the Ansvisor brand?
    select max(day) from mentions_terms_daily where brand_id = '<ansvisor>'; and the same for mentions_entities_daily.
  3. Cold vs warm timing at 30 and 90 days, and EXPLAIN (ANALYZE, BUFFERS) of the rollup reads if you can. pg_stat_statements mean/max for mentions_perception would show how often it's slow.
  4. Was the nightly tracking or the rollup sweep running when the slow loads happened?
  5. What did this morning's health e-mail show for the mentions_perception 30/90 probes (added in fix(mentions): read the Mentions table's window from its index alone #1360)?

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.

2 participants