Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(mentions): precompute the Perception tab's default view so it opens fast cold (#1385)
Cihanf3251f4ec072
diff --git a/server/src/lib/health/report.js b/server/src/lib/health/report.jsindex 84a5c102c..8184daac6 100644--- a/server/src/lib/health/report.js+++ b/server/src/lib/health/report.js@@ -29,6 +29,8 @@ export const WARN_AT_S = 4;* Mentions & Sentiment goes last (00239): the Mentions table's first page and* the Perception figures at 30 and 90 days, the windows that ran past the* budget, timed after the rest so they read as cold as a user's first visit.+ * Perception is timed twice (00241): as the tab opens it, from its+ * precomputed view, and live, as a filtered view reads the rollups.*/export const PROBES = [{ probe: 'topics_overview_window', days: 1 },@@ -43,6 +45,8 @@ export const PROBES = [{ probe: 'mentions_list', days: 90 },{ probe: 'mentions_perception', days: 30 },{ probe: 'mentions_perception', days: 90 },+ { probe: 'mentions_perception_live', days: 30 },+ { probe: 'mentions_perception_live', days: 90 },];const DAY_MS = 24 * 60 * 60 * 1000;diff --git a/server/src/lib/health/report.test.js b/server/src/lib/health/report.test.jsindex 94a3f25b3..a3d083d9e 100644--- a/server/src/lib/health/report.test.js+++ b/server/src/lib/health/report.test.js@@ -80,11 +80,14 @@ describe('collectHealthReport', () => {});it("times the Mentions & Sentiment tabs' reads last, at 30 and 90 days", () => {- expect(PROBES.slice(-4)).toEqual([+ expect(PROBES.slice(-6)).toEqual([{ probe: 'mentions_list', days: 30 },{ probe: 'mentions_list', days: 90 },{ probe: 'mentions_perception', days: 30 },{ probe: 'mentions_perception', days: 90 },+ // Perception's live read too (00241): what a filtered view still costs.+ { probe: 'mentions_perception_live', days: 30 },+ { probe: 'mentions_perception_live', days: 90 },]);});diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.jsindex daaf81469..46d60f3d8 100644--- a/server/src/lib/insights-rollups.js+++ b/server/src/lib/insights-rollups.js@@ -22,7 +22,11 @@import supabaseAdmin from '../config/supabase.js';import { logger } from './logger.js';import { rebuildQueuedCitationRollups, refreshCitationsDaily } from './citations-rollups.js';-import { refreshMentionTermsDaily, refreshMentionsDaily } from './mentions-rollups.js';+import {+ refreshMentionTermsDaily,+ refreshMentionsDaily,+ refreshPerceptionSnapshots,+} from './mentions-rollups.js';/** How many trailing days the daily sweep recomputes, today included. */export const SWEEP_DAYS = 3;@@ -62,6 +66,10 @@ export async function refreshForCompletedRun(brandId, runStartedAtIso) {const ok = await refreshInsightsDaily(brandId, dayFrom, dayTo);await refreshCitationsDaily(brandId, dayFrom, dayTo);await refreshMentionsDaily(brandId, dayFrom, dayTo);+ // The Perception tab's default view (00241) follows the rollups as they+ // now are. Not waited for: it never throws, and the run's stamp shouldn't+ // wait on three more reads.+ void refreshPerceptionSnapshots(brandId);return ok;}@@ -122,8 +130,10 @@ async function drainRebuildQueue() {const end = addDays(from, REBUILD_CHUNK_DAYS - 1);ok = await refreshInsightsDaily(brandId, from, end < dayTo ? end : dayTo);}- // The Perception rollups (00231) still count the deleted prompt's terms.+ // The Perception rollups (00231) still count the deleted prompt's terms,+ // and the view precomputed from them (00241) follows them as they now are.if (ok) ok = await refreshMentionTermsDaily(brandId, dayFrom, dayTo);+ await refreshPerceptionSnapshots(brandId);// A failed refresh logged itself; the entry stays for the next drain.if (!ok) {failed++;@@ -176,6 +186,9 @@ export async function sweepInsightsRollups({ days = SWEEP_DAYS } = {}) {const ok = await refreshInsightsDaily(brand.id, dayFrom, dayTo);const citationsOk = await refreshCitationsDaily(brand.id, dayFrom, dayTo);const mentionsOk = await refreshMentionsDaily(brand.id, dayFrom, dayTo);+ // The precomputed Perception view (00241) follows the rollups as they now+ // are; one that fails leaves the tab on the live read: logged, not counted.+ await refreshPerceptionSnapshots(brand.id);if (ok && citationsOk && mentionsOk) refreshed++;else failed++;}diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.jsindex 6b4dc6665..5acef680b 100644--- a/server/src/lib/insights-rollups.test.js+++ b/server/src/lib/insights-rollups.test.js@@ -20,9 +20,11 @@ vi.mock('./citations-rollups.js', () => ({// The Mentions rollups ride on them too (mentions-rollups.test.js).const refreshMentionsDaily = vi.fn();const refreshMentionTermsDaily = vi.fn();+const refreshPerceptionSnapshots = vi.fn();vi.mock('./mentions-rollups.js', () => ({refreshMentionsDaily: (...a) => refreshMentionsDaily(...a),refreshMentionTermsDaily: (...a) => refreshMentionTermsDaily(...a),+ refreshPerceptionSnapshots: (...a) => refreshPerceptionSnapshots(...a),}));import {@@ -74,6 +76,7 @@ beforeEach(() => {tables();refreshCitationsDaily.mockReset().mockResolvedValue(true);refreshMentionsDaily.mockReset().mockResolvedValue(true);+ refreshPerceptionSnapshots.mockReset().mockResolvedValue(true);refreshMentionTermsDaily.mockReset().mockResolvedValue(true);rebuildQueuedCitationRollups.mockReset().mockResolvedValue({ rebuilt: 0, failed: 0 });vi.useFakeTimers();@@ -150,6 +153,15 @@ describe('refreshForCompletedRun', () => {await refreshForCompletedRun('brand-1', '2026-08-20T23:45:00Z');expect(refreshCitationsDaily).toHaveBeenCalledWith('brand-1', '2026-08-20', '2026-08-21');expect(refreshMentionsDaily).toHaveBeenCalledWith('brand-1', '2026-08-20', '2026-08-21');+ // Then the Perception tab's precomputed view (00241), from the fresh rollups.+ expect(refreshPerceptionSnapshots).toHaveBeenCalledWith('brand-1');+ });++ it('refreshes the Perception view as the rollups now are, even after a failure', async () => {+ rpc.mockResolvedValue({ error: null });+ refreshMentionsDaily.mockResolvedValue(false);+ await refreshForCompletedRun('brand-1', '2026-08-20T23:45:00Z');+ expect(refreshPerceptionSnapshots).toHaveBeenCalledWith('brand-1');});});@@ -176,6 +188,7 @@ describe('sweepInsightsRollups', () => {expect(SWEEP_DAYS).toBe(3);expect(refreshCitationsDaily).toHaveBeenCalledWith('b', '2026-08-19', '2026-08-21');expect(refreshMentionsDaily).toHaveBeenCalledWith('b', '2026-08-19', '2026-08-21');+ expect(refreshPerceptionSnapshots.mock.calls).toEqual([['a'], ['b']]);expect(rebuildQueuedCitationRollups).toHaveBeenCalledTimes(1);});@@ -239,8 +252,10 @@ describe('rebuildQueuedInsightsRollups (00192)', () => {['2026-07-02', '2026-08-01'],['2026-08-02', '2026-08-10'],]);- // The Perception rollups (00231) lose the deleted prompt's terms too.+ // The Perception rollups (00231) lose the deleted prompt's terms too,+ // and so does the view precomputed from them (00241).expect(refreshMentionTermsDaily).toHaveBeenCalledWith('b1', '2026-06-01', '2026-08-10');+ expect(refreshPerceptionSnapshots).toHaveBeenCalledWith('b1');// Only if nothing re-queued the brand meanwhile.expect(queueDeletes).toEqual([[@@ -269,6 +284,8 @@ describe('rebuildQueuedInsightsRollups (00192)', () => {expect(await rebuildQueuedInsightsRollups()).toEqual({ rebuilt: 0, failed: 1 });expect(queueDeletes).toHaveLength(0);+ // The precomputed view still follows what was rebuilt.+ expect(refreshPerceptionSnapshots).toHaveBeenCalledWith('b1');});it('never runs twice at once', async () => {diff --git a/server/src/lib/mentions-rollups.js b/server/src/lib/mentions-rollups.jsindex 2004b53b4..55ab619f5 100644--- a/server/src/lib/mentions-rollups.js+++ b/server/src/lib/mentions-rollups.js@@ -53,6 +53,34 @@ export async function refreshMentionsDaily(brandId, dayFrom, dayTo) {return true;}+/** The Perception windows precomputed for the tab's default view (00241). */+export const PERCEPTION_SNAPSHOT_DAYS = [7, 30, 90];++/**+ * Recompute a brand's precomputed Perception views (00241) from its+ * rollups: the last 7, 30 and 90 days on every platform and region, the view+ * everyone opens, which the tab then reads in one lookup. One window per+ * call, so the largest brand's 90 days stay well inside the service role's+ * statement timeout. Called once the brand's Mentions rollups are fresh.+ * Resolves to true when every window is written, false at the first that+ * fails (the tab reads the rollups live meanwhile); never throws. Before+ * 00241 is applied there is no function to call: quietly false.+ */+export async function refreshPerceptionSnapshots(brandId) {+ for (const days of PERCEPTION_SNAPSHOT_DAYS) {+ const { error } = await supabaseAdmin.rpc('refresh_mentions_perception_snapshot', {+ p_brand_id: brandId,+ p_days: days,+ });+ if (error?.code === 'PGRST202') return false;+ if (error) {+ logger.error({ err: error, brandId, days }, '[mentions-rollups] Perception snapshot failed');+ return false;+ }+ }+ return true;+}+/*** Rebuild the Perception tab's daily rollups (00231) from the answers' terms* already written, a week per call: for the days a deleted prompt leaves,diff --git a/server/src/lib/mentions-rollups.test.js b/server/src/lib/mentions-rollups.test.jsindex 9b13fe142..f1407ef3c 100644--- a/server/src/lib/mentions-rollups.test.js+++ b/server/src/lib/mentions-rollups.test.js@@ -9,10 +9,12 @@ vi.mock('../config/supabase.js', () => ({}));import {+ PERCEPTION_SNAPSHOT_DAYS,refreshMentionHistory,refreshMentionTermsDaily,refreshMentionTermsHistory,refreshMentionsDaily,+ refreshPerceptionSnapshots,} from './mentions-rollups.js';/** A day-bound query on `expected`: first call ascending (first day), then descending. */@@ -87,6 +89,32 @@ describe('refreshMentionTermsDaily (00231)', () => {});});+describe('refreshPerceptionSnapshots (00241)', () => {+ it('computes the 7, 30 and 90 days, a window per call', async () => {+ rpc.mockResolvedValue({ error: null });+ expect(await refreshPerceptionSnapshots('b1')).toBe(true);+ expect(PERCEPTION_SNAPSHOT_DAYS).toEqual([7, 30, 90]);+ expect(rpc.mock.calls).toEqual(+ [7, 30, 90].map((days) => [+ 'refresh_mentions_perception_snapshot',+ { p_brand_id: 'b1', p_days: days },+ ]),+ );+ });++ it('stops at the first failure without throwing', async () => {+ rpc.mockResolvedValueOnce({ error: null }).mockResolvedValueOnce({ error: { message: 'x' } });+ expect(await refreshPerceptionSnapshots('b1')).toBe(false);+ expect(rpc).toHaveBeenCalledTimes(2);+ });++ it('is quietly false before 00241 is applied', async () => {+ rpc.mockResolvedValue({ error: { code: 'PGRST202', message: 'not found' } });+ expect(await refreshPerceptionSnapshots('b1')).toBe(false);+ expect(rpc).toHaveBeenCalledTimes(1);+ });+});+describe('refreshMentionHistory', () => {it('recomputes the whole history a day at a time', async () => {resultBounds('2026-10-01', '2026-10-03');diff --git a/server/src/scripts/backfill-mention-terms-daily.js b/server/src/scripts/backfill-mention-terms-daily.jsindex 0442b37ad..1b999c73b 100644--- a/server/src/scripts/backfill-mention-terms-daily.js+++ b/server/src/scripts/backfill-mention-terms-daily.js@@ -21,7 +21,7 @@import 'dotenv/config';import supabaseAdmin from '../config/supabase.js';-import { refreshMentionTermsHistory } from '../lib/mentions-rollups.js';+import { refreshMentionTermsHistory, refreshPerceptionSnapshots } from '../lib/mentions-rollups.js';const PAUSE_MS = Number.parseInt(process.env.MENTION_TERMS_BACKFILL_PAUSE ?? '250', 10);const ONLY_BRAND = process.env.MENTION_TERMS_BACKFILL_BRAND ?? null;@@ -36,6 +36,8 @@ async function main() {for (const brand of brands ?? []) {try {const chunks = await refreshMentionTermsHistory(brand.id, { pauseMs: PAUSE_MS });+ // The Perception tab's precomputed view (00241) reads the rebuilt rollups.+ if (chunks > 0) await refreshPerceptionSnapshots(brand.id);done++;console.log(chunks === 0diff --git a/server/src/scripts/backfill-mentions-daily.js b/server/src/scripts/backfill-mentions-daily.jsindex c17954d65..9b991dedb 100644--- a/server/src/scripts/backfill-mentions-daily.js+++ b/server/src/scripts/backfill-mentions-daily.js@@ -21,7 +21,7 @@import 'dotenv/config';import supabaseAdmin from '../config/supabase.js';-import { refreshMentionHistory } from '../lib/mentions-rollups.js';+import { refreshMentionHistory, refreshPerceptionSnapshots } from '../lib/mentions-rollups.js';const PAUSE_MS = Number.parseInt(process.env.MENTIONS_BACKFILL_PAUSE ?? '250', 10);const ONLY_BRAND = process.env.MENTIONS_BACKFILL_BRAND ?? null;@@ -36,6 +36,8 @@ async function main() {for (const brand of brands ?? []) {try {const chunks = await refreshMentionHistory(brand.id, { pauseMs: PAUSE_MS });+ // The Perception tab's precomputed view (00241) reads the rebuilt rollups.+ if (chunks > 0) await refreshPerceptionSnapshots(brand.id);done++;console.log(chunks === 0diff --git a/supabase/migrations/00241_mentions_perception_snapshots.sql b/supabase/migrations/00241_mentions_perception_snapshots.sqlnew file mode 100644index 000000000..79263d881--- /dev/null+++ b/supabase/migrations/00241_mentions_perception_snapshots.sql@@ -0,0 +1,537 @@+-- ============================================================================+-- 00241: the Perception tab's default view, precomputed (Mentions & Sentiment, MS-09)+-- ============================================================================+-- 00237's rollup read took 0.95 s (30 days) and 1.36 s (90 days) warm on+-- production, but on 2026-10-23 the Ansvisor brand's first load took 8.7 s+-- at 30 days (past the 8 s statement timeout: "Couldn't load") and 8.1 s at+-- 90, its retry 5.3 s: a cold read of the rollups' pages. The target is+-- 2–3 s cold.+--+-- The view everyone opens, the last 7, 30 or 90 days on every platform and+-- region, with no topic or search, is now computed ahead: one row per brand+-- and window in mentions_perception_snapshots, refreshed by the server when+-- a brand's Mentions rollups are (each completed tracking run, the nightly+-- sweep, the deleted-prompt rebuild). Reading it is one primary-key lookup.+--+-- * mentions_perception_live: 00237's read, unchanged, without the access+-- check; only this file's functions call it.+-- * mentions_perception: the access check, then the brand's snapshot for+-- the window when it fits the request (a preset window up to now, no+-- filters, computed today or yesterday, UTC); otherwise the live read.+-- A snapshot from yesterday shows its own window, which ends at the end+-- of yesterday: the day's runs refresh it.+-- * refresh_mentions_perception_snapshot(brand, days): one window per+-- call, so the largest brand's 90 days stay well inside the service+-- role's statement timeout.+-- * A brand's snapshots are set aside when a competitor is renamed or+-- removed, or the brand is renamed: the live read stands in until the+-- next refresh, so names and the competitors shown never go stale.+-- * health_probe gains 'mentions_perception_live', timing the read a+-- filtered view (or a brand without a snapshot) still makes.++create table if not exists public.mentions_perception_snapshots (+ brand_id uuid not null references public.brands(id) on delete cascade,+ days smallint not null+ constraint mentions_perception_snapshots_days_check check (days in (7, 30, 90)),+ -- The UTC day the window ends on (its last whole day).+ day_to date not null,+ payload jsonb not null,+ computed_at timestamptz not null default now(),+ primary key (brand_id, days)+);++comment on table public.mentions_perception_snapshots is+ 'The Perception tab''s default view (MS-09) per brand and window (7, 30 or 90 days, every platform and region, no topic or search), as mentions_perception returns it. Written by refresh_mentions_perception_snapshot; dropped when the brand''s competitors or name change.';++-- Service-role only, no policy: read through mentions_perception.+alter table public.mentions_perception_snapshots enable row level security;+revoke all on table public.mentions_perception_snapshots from anon, authenticated;+grant all on table public.mentions_perception_snapshots to service_role;++-- 00237's read, word for word, without the access check (mentions_perception keeps it).+create or replace function public.mentions_perception_live(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null,+ p_platform text default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_search text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ v_days integer;+ v_day_to date;+ v_start timestamptz;+ v_end timestamptz;+ v_prev_start timestamptz;+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');+ v_rollup boolean;+ v_start_day date;+ v_end_day date;+ v_prev_day date;+ v_result jsonb;+begin+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);+ if v_days < 2 then+ v_start := v_from;+ v_end := v_to + interval '1 microsecond';+ else+ v_day_to := (v_to at time zone 'utc')::date;+ v_start := (v_day_to - (v_days - 1))::timestamp at time zone 'utc';+ v_end := (v_day_to + 1)::timestamp at time zone 'utc';+ end if;+ v_prev_start := v_start - (v_end - v_start);+ -- Whole UTC days with no topic or search read the daily rollups (00231);+ -- a window under two days, or a filter on the prompts, reads the answers'+ -- terms as before. The branch not taken is pruned (plan_cache_mode).+ v_rollup := v_days >= 2 and p_topic_id is null and v_search is null;+ v_start_day := (v_start at time zone 'utc')::date;+ v_end_day := (v_end at time zone 'utc')::date;+ v_prev_day := (v_prev_start at time zone 'utc')::date;++ with+ prompts_in as (+ select p.id+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ and (p_topic_id is null or p.topic_id = p_topic_id)+ and (v_search is null or position(v_search in lower(p.text)) > 0)+ ),+ rows_in as (+ select t.result_id, t.entity, t.terms, (t.created_at >= v_start) as cur+ from public.mentions_answer_terms t+ join prompts_in pi on pi.id = t.prompt_id+ where not v_rollup+ and t.brand_id = p_brand_id+ and t.created_at >= v_prev_start+ and t.created_at < v_end+ and (p_platform is null or t.platform = p_platform)+ and (p_region is null or t.region = p_region)+ ),+ entity_counts as (+ select entity,+ count(*) filter (where cur) as mentions,+ count(*) filter (where not cur) as prev_mentions+ from rows_in+ group by entity+ union all+ select d.entity,+ coalesce(sum(d.answers) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.answers) filter (where d.day < v_start_day), 0)+ from public.mentions_entities_daily d+ where v_rollup+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity+ ),+ shown as (+ select 'brand'::text as entity, 0 as rank+ union all+ select * from (+ select ec.entity, row_number() over (order by ec.mentions desc, ec.entity)::int+ from entity_counts ec+ join public.competitors co on co.id::text = ec.entity and co.brand_id = p_brand_id+ where ec.mentions > 0+ order by ec.mentions desc, ec.entity+ limit 4+ ) top_competitors+ ),+ term_counts_all as (+ select r.entity, term,+ count(*) filter (where r.cur) as answers,+ count(*) filter (where not r.cur) as prev_answers+ from rows_in r+ join shown s on s.entity = r.entity+ cross join lateral unnest(r.terms) as term+ group by r.entity, term+ union all+ select d.entity, d.term,+ coalesce(sum(d.answers) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.answers) filter (where d.day < v_start_day), 0)+ from public.mentions_terms_daily d+ join shown s on s.entity = d.entity+ where v_rollup+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity, d.term+ ),+ -- Each entity's 60 most frequent terms are the candidates.+ candidates as (+ select entity, term, answers, prev_answers+ from (+ select t.*, row_number() over (partition by t.entity order by t.answers desc, t.term) as rn+ from term_counts_all t+ where t.answers > 0+ ) ranked+ where rn <= 60+ ),+ -- A word that nearly always comes in one phrase is that phrase: "fresh" and+ -- "roast" give way to "fresh roast" when it has 80% of their answers.+ term_counts as (+ select c.*+ from candidates c+ where position(' ' in c.term) > 0+ or not exists (+ select 1 from candidates p+ where p.entity = c.entity+ and position(' ' in p.term) > 0+ and (p.term like c.term || ' %' or p.term like '% ' || c.term)+ and p.answers >= 0.8 * c.answers)+ ),+ brand_terms as (+ select term, answers, prev_answers+ from term_counts+ where entity = 'brand' and answers > 0+ order by answers desc, term+ limit 15+ ),+ -- The terms that tell the brands apart most: the widest spread between the+ -- highest and lowest share of mentions, then the highest shares.+ attributes as (+ select u.term+ from (select distinct term from term_counts) u+ cross join shown s+ left join term_counts_all tc on tc.entity = s.entity and tc.term = u.term+ left join entity_counts ec on ec.entity = s.entity+ group by u.term+ order by+ max(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0))+ - min(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0)) desc nulls last,+ sum(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0)) desc nulls last,+ u.term+ limit 8+ ),+ -- A competitor's rows in answers that name the brand too, in one pass.+ co as (+ select x.entity,+ count(*) filter (where x.cur) as co_mentions,+ count(*) filter (where not x.cur) as prev_co_mentions+ from (+ select r.entity, r.cur,+ bool_or(r.entity = 'brand') over (partition by r.result_id) as with_brand+ from rows_in r+ ) x+ where x.entity <> 'brand' and x.with_brand+ group by x.entity+ union all+ select d.entity,+ coalesce(sum(d.with_brand) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.with_brand) filter (where d.day < v_start_day), 0)+ from public.mentions_entities_daily d+ where v_rollup+ and d.entity <> 'brand'+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity+ having sum(d.with_brand) > 0+ )+ select jsonb_build_object(+ 'window', jsonb_build_object('from', v_start, 'to', v_end, 'days', v_days),+ 'entities', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'entity', s.entity,+ 'name', case when s.entity = 'brand' then b.name else co.name end,+ 'is_brand', s.entity = 'brand',+ 'mentions', coalesce(ec.mentions, 0),+ 'prev_mentions', coalesce(ec.prev_mentions, 0))+ order by s.rank)+ from shown s+ left join entity_counts ec on ec.entity = s.entity+ left join public.brands b on s.entity = 'brand' and b.id = p_brand_id+ left join public.competitors co on co.id::text = s.entity and co.brand_id = p_brand_id+ ), '[]'::jsonb),+ 'brand_terms', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'term', bt.term, 'answers', bt.answers, 'prev_answers', bt.prev_answers)+ order by bt.answers desc, bt.term)+ from brand_terms bt+ ), '[]'::jsonb),+ 'attributes', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'term', a.term,+ 'values', (+ select jsonb_agg(jsonb_build_object(+ 'entity', s.entity, 'answers', coalesce(tc.answers, 0))+ order by s.rank)+ from shown s+ left join term_counts_all tc on tc.entity = s.entity and tc.term = a.term)))+ from attributes a+ ), '[]'::jsonb),+ 'co_mentions', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'competitor_id', c.entity,+ 'name', comp.name,+ 'co_mentions', c.co_mentions,+ 'prev_co_mentions', c.prev_co_mentions)+ order by c.co_mentions desc, comp.name)+ from co c+ join public.competitors comp on comp.id::text = c.entity and comp.brand_id = p_brand_id+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.mentions_perception_live(uuid, timestamptz, timestamptz, text, text, uuid, text)+ from public, anon, authenticated;+grant execute on function public.mentions_perception_live(uuid, timestamptz, timestamptz, text, text, uuid, text)+ to service_role;++create or replace function public.mentions_perception(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null,+ p_platform text default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_search text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+as $$+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ v_days integer;+ v_snapshot jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ -- The window's whole days, as mentions_perception_live counts them.+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);+ if p_date_to is null+ and v_days in (7, 30, 90)+ and p_platform is null+ and p_region is null+ and p_topic_id is null+ and nullif(btrim(coalesce(p_search, '')), '') is null then+ select s.payload into v_snapshot+ from public.mentions_perception_snapshots s+ where s.brand_id = p_brand_id+ and s.days = v_days+ and s.day_to >= (now() at time zone 'utc')::date - 1;+ if v_snapshot is not null then+ return v_snapshot;+ end if;+ end if;++ return public.mentions_perception_live(+ p_brand_id, p_date_from, p_date_to, p_platform, p_region, p_topic_id, p_search);+end;+$$;++revoke execute on function public.mentions_perception(uuid, timestamptz, timestamptz, text, text, uuid, text)+ from public, anon;+grant execute on function public.mentions_perception(uuid, timestamptz, timestamptz, text, text, uuid, text)+ to authenticated, service_role;++-- One window of one brand's default view, computed now and kept. The+-- server calls it for 7, 30 and 90 days after it refreshes the brand's+-- Mentions rollups.+create or replace function public.refresh_mentions_perception_snapshot(+ p_brand_id uuid,+ p_days integer+)+returns void+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_now timestamptz := now();+begin+ if p_days is null or p_days not in (7, 30, 90) then+ raise exception 'a Perception snapshot covers 7, 30 or 90 days, not %', p_days;+ end if;+ insert into public.mentions_perception_snapshots as s (brand_id, days, day_to, payload, computed_at)+ values (+ p_brand_id,+ p_days,+ (v_now at time zone 'utc')::date,+ public.mentions_perception_live(p_brand_id, v_now - make_interval(days => p_days)),+ v_now)+ on conflict (brand_id, days) do update+ set day_to = excluded.day_to,+ payload = excluded.payload,+ computed_at = excluded.computed_at+ -- A slower refresh that started earlier never writes over a newer one,+ -- nor over a snapshot set aside since (forget_mentions_perception_snapshots).+ where s.computed_at < excluded.computed_at;+end;+$$;++revoke all on function public.refresh_mentions_perception_snapshot(uuid, integer)+ from public, anon, authenticated;+grant execute on function public.refresh_mentions_perception_snapshot(uuid, integer)+ to service_role;++-- A competitor renamed or removed, or the brand renamed, changes what the+-- view lists: its snapshots are set aside (a day_to the read never takes),+-- and the live read stands in. Set aside, not deleted, and stamped now: a+-- refresh already under way when this ran (it started earlier) can't put+-- the old names back. A competitor added changes nothing yet: no answer+-- named it when the rollups were counted.+create or replace function public.forget_mentions_perception_snapshots()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_brands uuid[];+begin+ if tg_table_name = 'brands' then+ v_brands := array[new.id];+ elsif tg_op = 'UPDATE' then+ v_brands := array[old.brand_id, new.brand_id];+ else+ v_brands := array[old.brand_id];+ end if;+ update public.mentions_perception_snapshots+ set day_to = date '1970-01-01', computed_at = clock_timestamp()+ where brand_id = any (v_brands);+ return null;+end;+$$;++revoke all on function public.forget_mentions_perception_snapshots() from public, anon, authenticated;++drop trigger if exists competitors_forget_perception_snapshots on public.competitors;+create trigger competitors_forget_perception_snapshots+ after delete or update of name, brand_id on public.competitors+ for each row execute function public.forget_mentions_perception_snapshots();++drop trigger if exists brands_forget_perception_snapshots on public.brands;+create trigger brands_forget_perception_snapshots+ after update of name on public.brands+ for each row+ when (old.name is distinct from new.name)+ execute function public.forget_mentions_perception_snapshots();++-- health_probe as 00239 left it, with 'mentions_perception_live'.+create or replace function public.health_probe(+ p_user_id uuid,+ p_brand_id uuid,+ p_probe text,+ p_days integer default null+) returns numeric+language plpgsql+security invoker+set search_path to 'public'+as $$+declare+ t0 timestamptz;+ ts_from timestamptz := case when p_days is null then null else now() - make_interval(days => p_days) end;+ day_from date := (now() at time zone 'utc')::date - coalesce(p_days, 0);+ page_day_from date := case when p_days is null then null+ else (now() at time zone 'utc')::date - (p_days - 1) end;+ n bigint;+begin+ perform set_config('role', 'authenticated', true);+ perform set_config(+ 'request.jwt.claims',+ json_build_object('sub', p_user_id, 'role', 'authenticated')::text,+ true+ );+ t0 := clock_timestamp();++ case p_probe+ when 'citations_window_stats' then+ select count(*) into n from public.citations_window_stats(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);+ when 'citations_domains' then+ select count(*) into n from public.citations_domains(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);+ when 'citations_urls' then+ select count(*) into n from public.citations_urls(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null,+ p_limit => 100, p_domains => null, p_exclude_domains => null);+ when 'citations_domains_daily' then+ select count(*) into n from public.citations_domains_daily(+ p_brand_id => p_brand_id, p_day_from => page_day_from, p_day_to => null);+ when 'citations_urls_daily' then+ select count(*) into n from public.citations_urls_daily(+ p_brand_id => p_brand_id, p_day_from => page_day_from, p_day_to => null,+ p_limit => 2000);+ when 'insights_aggregates_daily' then+ select count(*) into n from public.insights_aggregates_daily(+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);+ when 'competitor_aggregates_daily' then+ select count(*) into n from public.competitor_aggregates_daily(+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);+ when 'topics_overview_aggregates' then+ select count(*) into n from public.topics_overview_aggregates(p_brand_id => p_brand_id);+ -- What the Topics tab runs: its window, the last p_days days (a day when+ -- unset, the tab's default 24 hours).+ when 'topics_overview_window' then+ select count(*) into n from public.topics_overview_window(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 1)),+ p_date_to => null);+ -- The Mentions & Sentiment tabs' reads over the last p_days days (a+ -- month when unset), as the page asks for them: the table's first page,+ -- newest first, and the Perception figures.+ when 'mentions_list' then+ perform public.mentions_list(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => null);+ when 'mentions_perception' then+ perform public.mentions_perception(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => null);+ -- The read a filtered Perception view makes (and the default view's,+ -- for a brand without a snapshot): an explicit end skips the snapshot.+ when 'mentions_perception_live' then+ perform public.mentions_perception(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => now());+ else+ raise exception 'unknown health probe: %', p_probe;+ end case;++ return round(extract(epoch from clock_timestamp() - t0)::numeric, 2);+end;+$$;+++revoke all on function public.health_probe(uuid, uuid, text, integer) from public, anon, authenticated;+grant execute on function public.health_probe(uuid, uuid, text, integer) to service_role;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex ef889c07c..4250776ee 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -35829,3 +35829,544 @@ alter table public.content_draft_suggestionscomment on column public.content_draft_suggestions.after_links is'A replace''s links: [{ "start", "end", "href" }], offsets into after_text (00240).';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00241_mentions_perception_snapshots.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00241: the Perception tab's default view, precomputed (Mentions & Sentiment, MS-09)+-- ============================================================================+-- 00237's rollup read took 0.95 s (30 days) and 1.36 s (90 days) warm on+-- production, but on 2026-10-23 the Ansvisor brand's first load took 8.7 s+-- at 30 days (past the 8 s statement timeout: "Couldn't load") and 8.1 s at+-- 90, its retry 5.3 s: a cold read of the rollups' pages. The target is+-- 2–3 s cold.+--+-- The view everyone opens, the last 7, 30 or 90 days on every platform and+-- region, with no topic or search, is now computed ahead: one row per brand+-- and window in mentions_perception_snapshots, refreshed by the server when+-- a brand's Mentions rollups are (each completed tracking run, the nightly+-- sweep, the deleted-prompt rebuild). Reading it is one primary-key lookup.+--+-- * mentions_perception_live: 00237's read, unchanged, without the access+-- check; only this file's functions call it.+-- * mentions_perception: the access check, then the brand's snapshot for+-- the window when it fits the request (a preset window up to now, no+-- filters, computed today or yesterday, UTC); otherwise the live read.+-- A snapshot from yesterday shows its own window, which ends at the end+-- of yesterday: the day's runs refresh it.+-- * refresh_mentions_perception_snapshot(brand, days): one window per+-- call, so the largest brand's 90 days stay well inside the service+-- role's statement timeout.+-- * A brand's snapshots are set aside when a competitor is renamed or+-- removed, or the brand is renamed: the live read stands in until the+-- next refresh, so names and the competitors shown never go stale.+-- * health_probe gains 'mentions_perception_live', timing the read a+-- filtered view (or a brand without a snapshot) still makes.++create table if not exists public.mentions_perception_snapshots (+ brand_id uuid not null references public.brands(id) on delete cascade,+ days smallint not null+ constraint mentions_perception_snapshots_days_check check (days in (7, 30, 90)),+ -- The UTC day the window ends on (its last whole day).+ day_to date not null,+ payload jsonb not null,+ computed_at timestamptz not null default now(),+ primary key (brand_id, days)+);++comment on table public.mentions_perception_snapshots is+ 'The Perception tab''s default view (MS-09) per brand and window (7, 30 or 90 days, every platform and region, no topic or search), as mentions_perception returns it. Written by refresh_mentions_perception_snapshot; dropped when the brand''s competitors or name change.';++-- Service-role only, no policy: read through mentions_perception.+alter table public.mentions_perception_snapshots enable row level security;+revoke all on table public.mentions_perception_snapshots from anon, authenticated;+grant all on table public.mentions_perception_snapshots to service_role;++-- 00237's read, word for word, without the access check (mentions_perception keeps it).+create or replace function public.mentions_perception_live(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null,+ p_platform text default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_search text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ v_days integer;+ v_day_to date;+ v_start timestamptz;+ v_end timestamptz;+ v_prev_start timestamptz;+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');+ v_rollup boolean;+ v_start_day date;+ v_end_day date;+ v_prev_day date;+ v_result jsonb;+begin+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);+ if v_days < 2 then+ v_start := v_from;+ v_end := v_to + interval '1 microsecond';+ else+ v_day_to := (v_to at time zone 'utc')::date;+ v_start := (v_day_to - (v_days - 1))::timestamp at time zone 'utc';+ v_end := (v_day_to + 1)::timestamp at time zone 'utc';+ end if;+ v_prev_start := v_start - (v_end - v_start);+ -- Whole UTC days with no topic or search read the daily rollups (00231);+ -- a window under two days, or a filter on the prompts, reads the answers'+ -- terms as before. The branch not taken is pruned (plan_cache_mode).+ v_rollup := v_days >= 2 and p_topic_id is null and v_search is null;+ v_start_day := (v_start at time zone 'utc')::date;+ v_end_day := (v_end at time zone 'utc')::date;+ v_prev_day := (v_prev_start at time zone 'utc')::date;++ with+ prompts_in as (+ select p.id+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where ps.brand_id = p_brand_id+ and (p_topic_id is null or p.topic_id = p_topic_id)+ and (v_search is null or position(v_search in lower(p.text)) > 0)+ ),+ rows_in as (+ select t.result_id, t.entity, t.terms, (t.created_at >= v_start) as cur+ from public.mentions_answer_terms t+ join prompts_in pi on pi.id = t.prompt_id+ where not v_rollup+ and t.brand_id = p_brand_id+ and t.created_at >= v_prev_start+ and t.created_at < v_end+ and (p_platform is null or t.platform = p_platform)+ and (p_region is null or t.region = p_region)+ ),+ entity_counts as (+ select entity,+ count(*) filter (where cur) as mentions,+ count(*) filter (where not cur) as prev_mentions+ from rows_in+ group by entity+ union all+ select d.entity,+ coalesce(sum(d.answers) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.answers) filter (where d.day < v_start_day), 0)+ from public.mentions_entities_daily d+ where v_rollup+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity+ ),+ shown as (+ select 'brand'::text as entity, 0 as rank+ union all+ select * from (+ select ec.entity, row_number() over (order by ec.mentions desc, ec.entity)::int+ from entity_counts ec+ join public.competitors co on co.id::text = ec.entity and co.brand_id = p_brand_id+ where ec.mentions > 0+ order by ec.mentions desc, ec.entity+ limit 4+ ) top_competitors+ ),+ term_counts_all as (+ select r.entity, term,+ count(*) filter (where r.cur) as answers,+ count(*) filter (where not r.cur) as prev_answers+ from rows_in r+ join shown s on s.entity = r.entity+ cross join lateral unnest(r.terms) as term+ group by r.entity, term+ union all+ select d.entity, d.term,+ coalesce(sum(d.answers) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.answers) filter (where d.day < v_start_day), 0)+ from public.mentions_terms_daily d+ join shown s on s.entity = d.entity+ where v_rollup+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity, d.term+ ),+ -- Each entity's 60 most frequent terms are the candidates.+ candidates as (+ select entity, term, answers, prev_answers+ from (+ select t.*, row_number() over (partition by t.entity order by t.answers desc, t.term) as rn+ from term_counts_all t+ where t.answers > 0+ ) ranked+ where rn <= 60+ ),+ -- A word that nearly always comes in one phrase is that phrase: "fresh" and+ -- "roast" give way to "fresh roast" when it has 80% of their answers.+ term_counts as (+ select c.*+ from candidates c+ where position(' ' in c.term) > 0+ or not exists (+ select 1 from candidates p+ where p.entity = c.entity+ and position(' ' in p.term) > 0+ and (p.term like c.term || ' %' or p.term like '% ' || c.term)+ and p.answers >= 0.8 * c.answers)+ ),+ brand_terms as (+ select term, answers, prev_answers+ from term_counts+ where entity = 'brand' and answers > 0+ order by answers desc, term+ limit 15+ ),+ -- The terms that tell the brands apart most: the widest spread between the+ -- highest and lowest share of mentions, then the highest shares.+ attributes as (+ select u.term+ from (select distinct term from term_counts) u+ cross join shown s+ left join term_counts_all tc on tc.entity = s.entity and tc.term = u.term+ left join entity_counts ec on ec.entity = s.entity+ group by u.term+ order by+ max(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0))+ - min(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0)) desc nulls last,+ sum(coalesce(tc.answers, 0)::numeric / nullif(ec.mentions, 0)) desc nulls last,+ u.term+ limit 8+ ),+ -- A competitor's rows in answers that name the brand too, in one pass.+ co as (+ select x.entity,+ count(*) filter (where x.cur) as co_mentions,+ count(*) filter (where not x.cur) as prev_co_mentions+ from (+ select r.entity, r.cur,+ bool_or(r.entity = 'brand') over (partition by r.result_id) as with_brand+ from rows_in r+ ) x+ where x.entity <> 'brand' and x.with_brand+ group by x.entity+ union all+ select d.entity,+ coalesce(sum(d.with_brand) filter (where d.day >= v_start_day), 0),+ coalesce(sum(d.with_brand) filter (where d.day < v_start_day), 0)+ from public.mentions_entities_daily d+ where v_rollup+ and d.entity <> 'brand'+ and d.brand_id = p_brand_id+ and d.day >= v_prev_day+ and d.day < v_end_day+ and (p_platform is null or d.platform = p_platform)+ and (p_region is null or d.region = p_region)+ group by d.entity+ having sum(d.with_brand) > 0+ )+ select jsonb_build_object(+ 'window', jsonb_build_object('from', v_start, 'to', v_end, 'days', v_days),+ 'entities', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'entity', s.entity,+ 'name', case when s.entity = 'brand' then b.name else co.name end,+ 'is_brand', s.entity = 'brand',+ 'mentions', coalesce(ec.mentions, 0),+ 'prev_mentions', coalesce(ec.prev_mentions, 0))+ order by s.rank)+ from shown s+ left join entity_counts ec on ec.entity = s.entity+ left join public.brands b on s.entity = 'brand' and b.id = p_brand_id+ left join public.competitors co on co.id::text = s.entity and co.brand_id = p_brand_id+ ), '[]'::jsonb),+ 'brand_terms', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'term', bt.term, 'answers', bt.answers, 'prev_answers', bt.prev_answers)+ order by bt.answers desc, bt.term)+ from brand_terms bt+ ), '[]'::jsonb),+ 'attributes', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'term', a.term,+ 'values', (+ select jsonb_agg(jsonb_build_object(+ 'entity', s.entity, 'answers', coalesce(tc.answers, 0))+ order by s.rank)+ from shown s+ left join term_counts_all tc on tc.entity = s.entity and tc.term = a.term)))+ from attributes a+ ), '[]'::jsonb),+ 'co_mentions', coalesce((+ select jsonb_agg(jsonb_build_object(+ 'competitor_id', c.entity,+ 'name', comp.name,+ 'co_mentions', c.co_mentions,+ 'prev_co_mentions', c.prev_co_mentions)+ order by c.co_mentions desc, comp.name)+ from co c+ join public.competitors comp on comp.id::text = c.entity and comp.brand_id = p_brand_id+ ), '[]'::jsonb)+ )+ into v_result;++ return v_result;+end;+$$;++revoke all on function public.mentions_perception_live(uuid, timestamptz, timestamptz, text, text, uuid, text)+ from public, anon, authenticated;+grant execute on function public.mentions_perception_live(uuid, timestamptz, timestamptz, text, text, uuid, text)+ to service_role;++create or replace function public.mentions_perception(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null,+ p_platform text default null,+ p_region text default null,+ p_topic_id uuid default null,+ p_search text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+as $$+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ v_days integer;+ v_snapshot jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ -- The window's whole days, as mentions_perception_live counts them.+ v_days := greatest(1, ceil(extract(epoch from v_to - v_from) / 86400.0 - 1.0 / 24)::integer);+ if p_date_to is null+ and v_days in (7, 30, 90)+ and p_platform is null+ and p_region is null+ and p_topic_id is null+ and nullif(btrim(coalesce(p_search, '')), '') is null then+ select s.payload into v_snapshot+ from public.mentions_perception_snapshots s+ where s.brand_id = p_brand_id+ and s.days = v_days+ and s.day_to >= (now() at time zone 'utc')::date - 1;+ if v_snapshot is not null then+ return v_snapshot;+ end if;+ end if;++ return public.mentions_perception_live(+ p_brand_id, p_date_from, p_date_to, p_platform, p_region, p_topic_id, p_search);+end;+$$;++revoke execute on function public.mentions_perception(uuid, timestamptz, timestamptz, text, text, uuid, text)+ from public, anon;+grant execute on function public.mentions_perception(uuid, timestamptz, timestamptz, text, text, uuid, text)+ to authenticated, service_role;++-- One window of one brand's default view, computed now and kept. The+-- server calls it for 7, 30 and 90 days after it refreshes the brand's+-- Mentions rollups.+create or replace function public.refresh_mentions_perception_snapshot(+ p_brand_id uuid,+ p_days integer+)+returns void+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_now timestamptz := now();+begin+ if p_days is null or p_days not in (7, 30, 90) then+ raise exception 'a Perception snapshot covers 7, 30 or 90 days, not %', p_days;+ end if;+ insert into public.mentions_perception_snapshots as s (brand_id, days, day_to, payload, computed_at)+ values (+ p_brand_id,+ p_days,+ (v_now at time zone 'utc')::date,+ public.mentions_perception_live(p_brand_id, v_now - make_interval(days => p_days)),+ v_now)+ on conflict (brand_id, days) do update+ set day_to = excluded.day_to,+ payload = excluded.payload,+ computed_at = excluded.computed_at+ -- A slower refresh that started earlier never writes over a newer one,+ -- nor over a snapshot set aside since (forget_mentions_perception_snapshots).+ where s.computed_at < excluded.computed_at;+end;+$$;++revoke all on function public.refresh_mentions_perception_snapshot(uuid, integer)+ from public, anon, authenticated;+grant execute on function public.refresh_mentions_perception_snapshot(uuid, integer)+ to service_role;++-- A competitor renamed or removed, or the brand renamed, changes what the+-- view lists: its snapshots are set aside (a day_to the read never takes),+-- and the live read stands in. Set aside, not deleted, and stamped now: a+-- refresh already under way when this ran (it started earlier) can't put+-- the old names back. A competitor added changes nothing yet: no answer+-- named it when the rollups were counted.+create or replace function public.forget_mentions_perception_snapshots()+returns trigger+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_brands uuid[];+begin+ if tg_table_name = 'brands' then+ v_brands := array[new.id];+ elsif tg_op = 'UPDATE' then+ v_brands := array[old.brand_id, new.brand_id];+ else+ v_brands := array[old.brand_id];+ end if;+ update public.mentions_perception_snapshots+ set day_to = date '1970-01-01', computed_at = clock_timestamp()+ where brand_id = any (v_brands);+ return null;+end;+$$;++revoke all on function public.forget_mentions_perception_snapshots() from public, anon, authenticated;++drop trigger if exists competitors_forget_perception_snapshots on public.competitors;+create trigger competitors_forget_perception_snapshots+ after delete or update of name, brand_id on public.competitors+ for each row execute function public.forget_mentions_perception_snapshots();++drop trigger if exists brands_forget_perception_snapshots on public.brands;+create trigger brands_forget_perception_snapshots+ after update of name on public.brands+ for each row+ when (old.name is distinct from new.name)+ execute function public.forget_mentions_perception_snapshots();++-- health_probe as 00239 left it, with 'mentions_perception_live'.+create or replace function public.health_probe(+ p_user_id uuid,+ p_brand_id uuid,+ p_probe text,+ p_days integer default null+) returns numeric+language plpgsql+security invoker+set search_path to 'public'+as $$+declare+ t0 timestamptz;+ ts_from timestamptz := case when p_days is null then null else now() - make_interval(days => p_days) end;+ day_from date := (now() at time zone 'utc')::date - coalesce(p_days, 0);+ page_day_from date := case when p_days is null then null+ else (now() at time zone 'utc')::date - (p_days - 1) end;+ n bigint;+begin+ perform set_config('role', 'authenticated', true);+ perform set_config(+ 'request.jwt.claims',+ json_build_object('sub', p_user_id, 'role', 'authenticated')::text,+ true+ );+ t0 := clock_timestamp();++ case p_probe+ when 'citations_window_stats' then+ select count(*) into n from public.citations_window_stats(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);+ when 'citations_domains' then+ select count(*) into n from public.citations_domains(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null);+ when 'citations_urls' then+ select count(*) into n from public.citations_urls(+ p_brand_id => p_brand_id, p_date_from => ts_from, p_date_to => null,+ p_models => null, p_regions => null, p_prompt_ids => null, p_topic_ids => null,+ p_limit => 100, p_domains => null, p_exclude_domains => null);+ when 'citations_domains_daily' then+ select count(*) into n from public.citations_domains_daily(+ p_brand_id => p_brand_id, p_day_from => page_day_from, p_day_to => null);+ when 'citations_urls_daily' then+ select count(*) into n from public.citations_urls_daily(+ p_brand_id => p_brand_id, p_day_from => page_day_from, p_day_to => null,+ p_limit => 2000);+ when 'insights_aggregates_daily' then+ select count(*) into n from public.insights_aggregates_daily(+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);+ when 'competitor_aggregates_daily' then+ select count(*) into n from public.competitor_aggregates_daily(+ p_brand_id => p_brand_id, p_platform => null, p_models => null, p_region => null,+ p_day_from => case when p_days is null then null else day_from end, p_day_to => null);+ when 'topics_overview_aggregates' then+ select count(*) into n from public.topics_overview_aggregates(p_brand_id => p_brand_id);+ -- What the Topics tab runs: its window, the last p_days days (a day when+ -- unset, the tab's default 24 hours).+ when 'topics_overview_window' then+ select count(*) into n from public.topics_overview_window(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 1)),+ p_date_to => null);+ -- The Mentions & Sentiment tabs' reads over the last p_days days (a+ -- month when unset), as the page asks for them: the table's first page,+ -- newest first, and the Perception figures.+ when 'mentions_list' then+ perform public.mentions_list(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => null);+ when 'mentions_perception' then+ perform public.mentions_perception(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => null);+ -- The read a filtered Perception view makes (and the default view's,+ -- for a brand without a snapshot): an explicit end skips the snapshot.+ when 'mentions_perception_live' then+ perform public.mentions_perception(+ p_brand_id => p_brand_id,+ p_date_from => now() - make_interval(days => coalesce(p_days, 30)),+ p_date_to => now());+ else+ raise exception 'unknown health probe: %', p_probe;+ end case;++ return round(extract(epoch from clock_timestamp() - t0)::numeric, 2);+end;+$$;+++revoke all on function public.health_probe(uuid, uuid, text, integer) from public, anon, authenticated;+grant execute on function public.health_probe(uuid, uuid, text, integer) to service_role;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 42831e099..195de09cf 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -5684,6 +5684,7 @@"perception": {"sectionLabel": "Perception","loadError": "Couldn't load the perception figures.",+ "slow": "Still reading this period's figures. It can take a few seconds.","unavailable": "Perception isn't available yet. It appears once the mentions data has been prepared.","pickDates": "Choose a start or end date to see the perception figures.","noMentions": "AI didn't name {brand} in the tracked responses of this period.",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsxindex ec874453e..afbd4450e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.test.tsx@@ -235,7 +235,10 @@ describe('MentionsPerceptionTab', () => {it('says a read failed, and shows the skeleton again once a newer one is on its way', async () => {vi.useFakeTimers();- getMentionsPerception.mockRejectedValueOnce(new Error('offline'));+ // Failed twice: once, and once more on the tab's own retry.+ getMentionsPerception+ .mockRejectedValueOnce(new Error('offline'))+ .mockRejectedValueOnce(new Error('offline'));render(<MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,);@@ -255,9 +258,65 @@ describe('MentionsPerceptionTab', () => {expect(container.querySelector('[aria-hidden]')).not.toBeNull();});+ it('tries a failed read once more before saying it failed (a cold read past the limit)', async () => {+ vi.useFakeTimers();+ getMentionsPerception+ .mockRejectedValueOnce(new Error('timeout'))+ .mockResolvedValueOnce(perception);+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(250);+ });+ expect(getMentionsPerception).toHaveBeenCalledTimes(2);+ expect(getMentionsPerception.mock.calls[1]).toEqual(getMentionsPerception.mock.calls[0]);+ expect(container.textContent).toContain('What AI associates with Ansvisor');+ expect(container.textContent).not.toContain("Couldn't load");+ });++ it('says it is still reading when a read takes a while', async () => {+ vi.useFakeTimers();+ let answer: (value: typeof perception) => void = () => {};+ getMentionsPerception.mockReturnValueOnce(new Promise((resolve) => (answer = resolve)));+ render(+ <MentionsPerceptionTab brandId="b1" brand="Ansvisor" filters={DEFAULT_MENTIONS_FILTERS} />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(3_000);+ });+ // In the page from the start, empty, so a screen reader announces the words.+ expect(container.querySelector('[role="status"]')!.textContent).toBe('');+ await act(async () => {+ await vi.advanceTimersByTimeAsync(1_000);+ });+ expect(container.querySelector('[role="status"]')!.textContent).toBe(+ "Still reading this period's figures. It can take a few seconds.",+ );+ await act(async () => answer(perception));+ expect(container.querySelector('[role="status"]')!.textContent).toBe('');+ expect(container.textContent).toContain('What AI associates with Ansvisor');++ // New filters: the last figures stay, dimmed, and a slow read says so.+ getMentionsPerception.mockReturnValueOnce(new Promise(() => {}));+ render(+ <MentionsPerceptionTab+ brandId="b1"+ brand="Ansvisor"+ filters={{ ...DEFAULT_MENTIONS_FILTERS, range: '90d' }}+ />,+ );+ await act(async () => {+ await vi.advanceTimersByTimeAsync(4_000);+ });+ expect(container.querySelector('section[aria-busy="true"]')).not.toBeNull();+ expect(container.querySelector('[role="status"]')!.textContent).toContain('Still reading');+ });+it('reads the same filters again on Try again, with the skeleton meanwhile', async () => {vi.useFakeTimers();getMentionsPerception+ .mockRejectedValueOnce(new Error('timeout')).mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce(perception);render(@@ -274,8 +333,8 @@ describe('MentionsPerceptionTab', () => {await act(async () => {await vi.advanceTimersByTimeAsync(250);});- expect(getMentionsPerception).toHaveBeenCalledTimes(2);- expect(getMentionsPerception.mock.calls[1]).toEqual(getMentionsPerception.mock.calls[0]);+ expect(getMentionsPerception).toHaveBeenCalledTimes(3);+ expect(getMentionsPerception.mock.calls[2]).toEqual(getMentionsPerception.mock.calls[0]);expect(container.textContent).toContain('What AI associates with Ansvisor');});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsxindex 289246b64..39212065d 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_perception.tsx@@ -15,6 +15,8 @@ import { CoMentionsCard, HeatmapCard, TermsCard } from './_perception-cards';/** Typing in the search box reads once it pauses, not on every key. */const READ_DELAY_MS = 250;+/** A read still on its way after this says it is still reading. */+const SLOW_MS = 4_000;type Loaded =| { brandId: string; key: string; status: 'ok'; perception: MentionsPerception | null }@@ -34,7 +36,10 @@ function Message({ children }: { children: React.ReactNode }) {* The Perception tab (MS-09), as in the mockup: what AI associates with the* brand and the brand's shape against its competitors, then the brand ×* attribute heat map and the competitors named beside it. One read per- * filter change; a newer change wins over a read still on its way.+ * filter change; a newer change wins over a read still on its way. A read+ * that fails is tried once more before the tab says so (a cold read past+ * the database's limit usually answers the second time), and a slow one+ * says it is still reading.*/export function MentionsPerceptionTab({brandId,@@ -52,12 +57,18 @@ export function MentionsPerceptionTab({const [loaded, setLoaded] = useState<Loaded | null>(null);// Try again reads the same filters once more.const [attempt, setAttempt] = useState(0);+ // The read (for these filters, this try) still on its way after SLOW_MS.+ const [slow, setSlow] = useState<string | null>(null);+ const readKey = key ? `${key}#${attempt}` : null;useEffect(() => {if (!key || !query) return;let cancelled = false;+ const read = () => getMentionsPerception(brandId, query);const timer = setTimeout(() => {- getMentionsPerception(brandId, query)+ read()+ // Once more before saying it failed.+ .catch((err) => (cancelled ? Promise.reject(err) : read())).then((perception) => {if (!cancelled) setLoaded({ brandId, key, status: 'ok', perception });})@@ -65,14 +76,20 @@ export function MentionsPerceptionTab({if (!cancelled) setLoaded({ brandId, key, status: 'error' });});}, READ_DELAY_MS);+ const slowTimer = setTimeout(() => {+ if (!cancelled) setSlow(`${key}#${attempt}`);+ }, SLOW_MS);return () => {cancelled = true;clearTimeout(timer);+ clearTimeout(slowTimer);};}, [brandId, key, query, attempt]);+ const isSlow = slow !== null && slow === readKey;+ const skeleton = <PerceptionSkeleton slow={isSlow} />;if (!query) return <Message>{t('pickDates')}</Message>;- if (!loaded || loaded.brandId !== brandId) return <PerceptionSkeleton />;+ if (!loaded || loaded.brandId !== brandId) return skeleton;if (loaded.status === 'error') {return loaded.key === key ? (<Message>@@ -91,7 +108,7 @@ export function MentionsPerceptionTab({</Button></Message>) : (- <PerceptionSkeleton />+ skeleton);}if (!loaded.perception) return <Message>{t('unavailable')}</Message>;@@ -101,36 +118,56 @@ export function MentionsPerceptionTab({const mentions = perception.entities.find((e) => e.isBrand)?.mentions ?? 0;return (- <section- aria-label={t('sectionLabel')}- aria-busy={stale}- className={cn('flex flex-col gap-3 transition-opacity', stale && 'opacity-60')}- >- {mentions === 0 ? (- <Message>{t('noMentions', { brand })}</Message>- ) : (- <>- <div className="grid items-start gap-3 xl:grid-cols-2">- <TermsCard perception={perception} brand={brand} />- <BrandShapeCard perception={perception} brand={brand} />- </div>- <div className="grid items-start gap-3 xl:grid-cols-2">- <HeatmapCard perception={perception} />- <CoMentionsCard perception={perception} />- </div>- <p className="text-xs text-muted-foreground">{t('method')}</p>- </>- )}- </section>+ <div className="flex flex-col gap-3">+ {/* The figures shown are the last filters': a slow read of the new ones says so. */}+ <SlowNote slow={stale && isSlow} />+ <section+ aria-label={t('sectionLabel')}+ aria-busy={stale}+ className={cn('flex flex-col gap-3 transition-opacity', stale && 'opacity-60')}+ >+ {mentions === 0 ? (+ <Message>{t('noMentions', { brand })}</Message>+ ) : (+ <>+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <TermsCard perception={perception} brand={brand} />+ <BrandShapeCard perception={perception} brand={brand} />+ </div>+ <div className="grid items-start gap-3 xl:grid-cols-2">+ <HeatmapCard perception={perception} />+ <CoMentionsCard perception={perception} />+ </div>+ <p className="text-xs text-muted-foreground">{t('method')}</p>+ </>+ )}+ </section>+ </div>+ );+}++/**+ * Says a read is still on its way. Always in the page, empty until then, so+ * screen readers announce the words when they come.+ */+function SlowNote({ slow }: { slow: boolean }) {+ const t = useTranslations('mentions.perception');+ return (+ <p role="status" className={cn('text-sm text-muted-foreground', !slow && 'sr-only')}>+ {slow ? t('slow') : ''}+ </p>);}-function PerceptionSkeleton() {+function PerceptionSkeleton({ slow }: { slow: boolean }) {return (- <div className="grid gap-3 xl:grid-cols-2" aria-hidden>- {[0, 1, 2, 3].map((i) => (- <Skeleton key={i} className="h-[300px] rounded-xl" />- ))}+ <div className="flex flex-col gap-3">+ <SlowNote slow={slow} />+ <div className="grid gap-3 xl:grid-cols-2" aria-hidden>+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-[300px] rounded-xl" />+ ))}+ </div></div>);}