Skip to content

fix(mentions): precompute the Perception tab's default view so it opens fast cold - #1385

Merged
gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:fix/perception-snapshot
Oct 23, 2026
Merged

gkhngyk merged 2 commits into
ansvisor:mainfrom
cihan-gyk:fix/perception-snapshot

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

The Perception tab's default view (7, 30 or 90 days, every platform and region, no topic or search) is now precomputed per brand and read in one lookup. A slow or failed read retries once and says it is still reading.

On prod today (2026-10-23, Ansvisor brand, read-only):

  • 30 days: the first load took 8.7 s, past the 8 s statement timeout, so it showed "Couldn't load". Try again took 5.3 s.
  • 90 days: 8.1 s.
  • 7 days: 1.0 s.

00237's rollup read is fast warm (0.95 s / 1.36 s as you timed it), but a cold read of the rollups' pages isn't. The target is 2–3 s on a cold load. My questions about prod (00237 live, rollups filled, EXPLAIN, nightly overlap, this morning's probe timings) are on #1325.

Migration 00241

  • mentions_perception_snapshots (brand_id, days ∈ {7,30,90}, day_to, payload, computed_at), primary key (brand_id, days). RLS is on, service role only.

  • mentions_perception_live is 00237's read word for word, minus the access check. It is service role only.

  • mentions_perception keeps the access check. It returns the brand's snapshot when the request is the default view:

    • no p_date_to, and 7, 30 or 90 whole days;
    • no platform, region, topic or search;
    • a snapshot whose day_to is today or yesterday (UTC).

    Anything else reads live, as before. A snapshot from yesterday shows its own window, ending yesterday; the day's runs refresh it.

  • refresh_mentions_perception_snapshot(brand, days) upserts one window per call, so the largest brand's 90 days stay well inside the service role's timeout. A slower refresh that started earlier never writes over a newer row (where computed_at < excluded.computed_at).

  • Triggers on competitors (delete, update of name / brand_id) and brands (update of name) set the brand's snapshots aside: day_to 1970, stamped clock_timestamp().

    • The live read stands in until the next refresh, so the competitors listed and the names never go stale.
    • A refresh already running can't put the old names back.
    • A competitor added changes nothing yet (no answer named it when the rollups were counted), so it keeps the snapshot.
  • health_probe (00239's body) gains mentions_perception_live: an explicit end skips the snapshot, so it times what a filtered view still costs.

Server

  • refreshPerceptionSnapshots(brandId) (mentions-rollups.js) makes 3 RPC calls. It runs once a brand's Mentions rollups have been refreshed, whatever the outcome, so it follows them as they now are:
    • each completed tracking run (refreshForCompletedRun), not awaited, so the run's stamp doesn't wait;
    • the nightly sweep;
    • the deleted-prompt rebuild drain;
    • the two mention backfill scripts.
  • It is best-effort. A failure is logged, and the tab reads live meanwhile. PGRST202 (before 00241 is applied) is quiet.
  • The morning health e-mail times Perception both ways at 30 and 90 days:
    • mentions_perception: what the tab opens;
    • mentions_perception_live: the filtered read.

Web (mentions/_perception.tsx)

  • A failed read is tried once more before the tab says it failed. A cold read past the limit usually answers the second time: today's retry took 5.3 s.
  • After 4 s, the page says "Still reading this period's figures. It can take a few seconds." It does so over the skeleton, or over the last figures while they're shown dimmed for new filters. The role="status" paragraph is always in the page, so screen readers announce the words.
  • Try again stays for a read that fails twice.

Verified on the dev DB (demo brand, rows 2026-09-09..10-16):

  • Same output: 30 combinations (1/2/7/30/90 days × platform none/chatgpt-web/claude × search none/"coffee") give identical output before and after, with and without snapshots (md5 per combination; the 24 h window's window key aside, since it moves with now()).
  • Which read answers: a marked snapshot payload is returned for the default 30 days. A platform filter, an explicit end or a two-day-old snapshot reads live.
  • Triggers (inside rolled-back transactions):
    • deleting a competitor or renaming the brand sets the 3 snapshots aside, and the read goes live;
    • inserting a competitor keeps them;
    • an older refresh doesn't write over a set-aside row;
    • authenticated has no access to the table.
  • Speed and probes: the 3 windows computed in 112 ms. Both probes run as the demo user.

Note on the health e-mail: the new mentions_perception_live probes time the filtered path cold. They will likely read yellow or red on the Ansvisor brand (it's the 8 s read). That is the honest cost of a filtered view. A covering index on the rollups, like 00239's, would be the next step for filtered views if it matters.

Known trade-off: between 00:00 UTC and a brand's first run or the morning sweep, the default view shows the snapshot computed yesterday, whose window ends yesterday. The web doesn't print the window's dates; MCP returns them in window.

Deploy order

  1. Apply 00241. The read keeps working with no snapshots: it reads live.
  2. Deploy the server. Snapshots then appear as each brand's next run or the nightly sweep refreshes it.
  3. Please fill them at once for the biggest brands (otherwise the fix shows only after their next run or the sweep):
    select refresh_mentions_perception_snapshot('<brand>', d) from unnest(array[7,30,90]) d;
  4. Re-measure Perception 30/90 days cold on the Ansvisor brand.

Related issue

Page speed queue item 5 (Perception regression, 2026-10-23). Follows #1325 (00231/00237) and #1360 (00239 probes). No issue.

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 00241 and run the refresh above for a brand.
  2. Open Mentions › Perception at 30 and 90 days. It loads from the snapshot (~0.1–0.2 s for the server action locally, against the hosted dev DB).
  3. Pick a platform or type a search. That reads live, with output as before.
  4. Rename a competitor. select count(*) from mentions_perception_snapshots where brand_id = … is 0 until the next refresh.
  5. To see the retry, make the first read fail: the tab tries once more before saying it failed. With a read slower than 4 s, the skeleton says it is still reading.

Tests:

  • server: mentions-rollups.test.js, insights-rollups.test.js, health/report.test.js;
  • web: _perception.test.tsx (the retry, the slow note, Try again after two failures).

Checked in the browser at 1024 px, in light and dark themes.

Checklist

  • Branch follows the naming convention (feature/, fix/, chore/, docs/) — see CONTRIBUTING.md
  • Commits follow Conventional Commits
  • yarn lint passes (run from web/) (0 errors; the 6 warnings are in untouched files, as on main)
  • yarn typecheck passes (run from web/)
  • yarn format:check passes (run from web/)
  • Changes are focused — one concern per PR

Also run:

  • web yarn test (2,815 tests) and yarn build;
  • server npm run format, npm run lint and npm test (2,050 tests);
  • bash supabase/build-schema.sh.

🤖 Generated with Claude Code

…ns fast cold

On prod the Perception tab's first load took 8.7 s at 30 days (past the
8 s statement timeout) and 8.1 s at 90: 00237's rollup read is fast warm
but not cold. 00241 keeps the default view (7, 30 or 90 days, no
filters) per brand in mentions_perception_snapshots, refreshed after the
brand's Mentions rollups (completed runs, the nightly sweep, the
deleted-prompt rebuild, the backfills), and mentions_perception reads it
in one lookup; filtered views read live as before. Competitor or brand
renames and removals set the snapshots aside. The health e-mail also
times the live read, and the tab retries a failed read once and says
when a read is slow.

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

Copy link
Copy Markdown
Collaborator Author

@gkhngyk Urgent, top of our queue: Perception's first load is 8.7 s → error at 30 days on prod again (details and my prod questions on #1325). This precomputes the default view (00241, independent of the open content stack, which uses 00240). Deploy order in the body: apply 00241, deploy the server, then please run refresh_mentions_perception_snapshot for the biggest brands at once and re-time 30/90 days cold.

@github-actions github-actions Bot added the needs-migration Adds or edits a migration — apply it to the hosted database label Oct 22, 2026
gkhngyk
gkhngyk previously approved these changes Oct 23, 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.

Looks good. Two small follow-ups and one cosmetic fix, none of them blocking:

  1. A failed refresh keeps serving the previous snapshot. It doesn't fall back to the live read. server/src/lib/mentions-rollups.js:66 says "the tab reads the rollups live meanwhile", and server/src/lib/insights-rollups.js:189-190 says a failed refresh "leaves the tab on the live read". But mentions_perception (00241_mentions_perception_snapshots.sql:339-346) returns any snapshot whose day_to is today or yesterday. So when a run's rollups land and the snapshot refresh after them fails, the default view keeps showing the pre-run figures until the next run or the 02:00 sweep. A filtered view reads the newer rollups during that time. The same happens after any rollup rewrite that doesn't go through the server (a manual backfill in SQL). Pick one:

    • Set the brand's snapshots aside wherever the rollups change. refresh_mention_terms_daily (00231) could run the same update … set day_to = date '1970-01-01', computed_at = clock_timestamp() where brand_id = p_brand_id as forget_mentions_perception_snapshots, in its own transaction. Then a snapshot is never older than the rollups. The computed_at guard already keeps a refresh that started earlier from writing over it. Cheap to do now, while 00241 isn't applied.
    • Or keep the behaviour and correct the two comments (and the PR text) to say the last snapshot stays until the next refresh.
  2. The drain refreshes the snapshots even when nothing was rebuilt. At server/src/lib/insights-rollups.js:135-136, refreshPerceptionSnapshots runs even when the Insights refresh failed and refreshMentionTermsDaily never ran. The entry stays queued, so a brand whose rebuild keeps failing recomputes its three windows every 5 minutes. On the largest brand that is about 16 s of cold reads each time. Only refresh after the terms refresh has run:

    if (ok) {
      ok = await refreshMentionTermsDaily(brandId, dayFrom, dayTo);
      await refreshPerceptionSnapshots(brandId);
    }

    The "Perception rollups fail to rebuild" test (insights-rollups.test.js:280) still holds. Add an assertion to "keeps the entry for the next drain when a refresh fails" (:268) that b1's snapshots weren't refreshed.

  3. Cosmetic: the slow note can show too early. slow (_perception.tsx:61) is never cleared. If you go back to a filter set whose earlier read was slow, isSlow (:89) is true at once, so the note shows over the dimmed figures before SLOW_MS. Clear it when the read's effect ends, e.g. setSlow((s) => (s === `${key}#${attempt}` ? null : s)) in the cleanup.

Checked on production, as authenticated (a member of the largest brand's organization). Each check ran in a rolled-back block against pg_temp copies of the new table and functions:

  • Same output: the snapshot equals the current mentions_perception output (jsonb equality) at 7, 30 and 90 days. It also matches, and still comes from the snapshot, when the request's start is 50 minutes before or 20 hours after now − N days (client clock skew). A start 2 hours early is a 31-day window and reads live, as it does today.
  • Live paths unchanged: a platform filter and an explicit end read live with identical output. A user from another organization gets null.
  • Timings: the current read took 3.49 s (30 days, first read), 2.58 s (90 days) and 0.25 s (7 days). The snapshot read takes about 1 ms. Building the three windows took 0.25 s, 1.30 s and 1.78 s warm, and 15.8 s for all three cold. All 229 brands took 68 s in total, cold. Each payload is about 2.3 KB.
  • Deploy order: fill the snapshots only after the server with refreshPerceptionSnapshots is live. A snapshot filled before that is served until the end of the next day, and no run refreshes it in the meantime.

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

Re-approving after merging main into the branch. The merge only brings in the squashed parent PR; the tree matches the one tested (web and server tests, typecheck, lint, format).

@gkhngyk
gkhngyk merged commit f3251f4 into ansvisor:main Oct 23, 2026
4 of 5 checks passed
gkhngyk added a commit that referenced this pull request Oct 23, 2026
…ps (#1392)

Follow-ups from #1385's review:
- 00246: refresh_mention_terms_daily sets the brand's snapshots aside at
  its end, in the rebuild's transaction, so the default view reads the
  new rollups live until the snapshots are refreshed, even when that
  refresh fails or the rollups were rebuilt in SQL.
- The deleted-prompt drain refreshes the snapshots only after the terms
  refresh has run.
- The slow note is cleared when its read's effect ends, so going back to
  filters whose last read was slow doesn't show it before SLOW_MS.

Co-authored-by: Cihan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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

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