Skip to content

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.

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

Cihan47a74776225b
diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.js
index 4f2fab8d5..daaf81469 100644
--- a/server/src/lib/insights-rollups.js
+++ b/server/src/lib/insights-rollups.js
@@ -22,7 +22,7 @@
import supabaseAdmin from '../config/supabase.js';
import { logger } from './logger.js';
import { rebuildQueuedCitationRollups, refreshCitationsDaily } from './citations-rollups.js';
-import { refreshMentionsDaily } from './mentions-rollups.js';
+import { refreshMentionTermsDaily, refreshMentionsDaily } from './mentions-rollups.js';
/** How many trailing days the daily sweep recomputes, today included. */
export const SWEEP_DAYS = 3;
@@ -122,6 +122,8 @@ 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.
+ if (ok) ok = await refreshMentionTermsDaily(brandId, dayFrom, dayTo);
// A failed refresh logged itself; the entry stays for the next drain.
if (!ok) {
failed++;
diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.js
index 84688d5c1..6b4dc6665 100644
--- a/server/src/lib/insights-rollups.test.js
+++ b/server/src/lib/insights-rollups.test.js
@@ -19,8 +19,10 @@ vi.mock('./citations-rollups.js', () => ({
// The Mentions rollups ride on them too (mentions-rollups.test.js).
const refreshMentionsDaily = vi.fn();
+const refreshMentionTermsDaily = vi.fn();
vi.mock('./mentions-rollups.js', () => ({
refreshMentionsDaily: (...a) => refreshMentionsDaily(...a),
+ refreshMentionTermsDaily: (...a) => refreshMentionTermsDaily(...a),
}));
import {
@@ -72,6 +74,7 @@ beforeEach(() => {
tables();
refreshCitationsDaily.mockReset().mockResolvedValue(true);
refreshMentionsDaily.mockReset().mockResolvedValue(true);
+ refreshMentionTermsDaily.mockReset().mockResolvedValue(true);
rebuildQueuedCitationRollups.mockReset().mockResolvedValue({ rebuilt: 0, failed: 0 });
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-08-21T05:30:00Z'));
@@ -236,6 +239,8 @@ 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.
+ expect(refreshMentionTermsDaily).toHaveBeenCalledWith('b1', '2026-06-01', '2026-08-10');
// Only if nothing re-queued the brand meanwhile.
expect(queueDeletes).toEqual([
[
@@ -257,6 +262,15 @@ describe('rebuildQueuedInsightsRollups (00192)', () => {
expect(queueDeletes[0][0]).toEqual(['eq', 'brand_id', 'b2']);
});
+ it('keeps the entry when the Perception rollups fail to rebuild', async () => {
+ queueRows = [entry];
+ rpc.mockResolvedValue({ error: null });
+ refreshMentionTermsDaily.mockResolvedValue(false);
+
+ expect(await rebuildQueuedInsightsRollups()).toEqual({ rebuilt: 0, failed: 1 });
+ expect(queueDeletes).toHaveLength(0);
+ });
+
it('never runs twice at once', async () => {
queueRows = [entry];
let release;
diff --git a/server/src/lib/mentions-rollups.js b/server/src/lib/mentions-rollups.js
index 4e2343d98..2004b53b4 100644
--- a/server/src/lib/mentions-rollups.js
+++ b/server/src/lib/mentions-rollups.js
@@ -53,6 +53,68 @@ export async function refreshMentionsDaily(brandId, dayFrom, dayTo) {
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,
+ * whose terms went with its answers (the terms refresh above rebuilds them
+ * itself). No answer text is read. Resolves to true when every call
+ * succeeds, false at the first that fails; never throws.
+ */
+export async function refreshMentionTermsDaily(brandId, dayFrom, dayTo) {
+ for (const [from, to] of dayChunks(dayFrom, dayTo, MENTION_TERMS_ROLLUP_CHUNK_DAYS)) {
+ const { error } = await supabaseAdmin.rpc('refresh_mention_terms_daily', {
+ p_brand_id: brandId,
+ p_day_from: from,
+ p_day_to: to,
+ });
+ if (error) {
+ logger.error(
+ { err: error, brandId, dayFrom: from, dayTo: to },
+ '[mentions-rollups] terms rollup refresh failed',
+ );
+ return false;
+ }
+ }
+ return true;
+}
+
+/** The first or last UTC day of a brand's answers' terms (00161), or null with none. */
+async function termsDayBound(brandId, ascending) {
+ const { data, error } = await supabaseAdmin
+ .from('mentions_answer_terms')
+ .select('created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending })
+ .limit(1);
+ if (error) throw new Error(error.message);
+ const at = data?.[0]?.created_at;
+ return at ? new Date(at).toISOString().slice(0, 10) : null;
+}
+
+/**
+ * Rebuild a brand's Perception rollups (00231) over its whole terms history,
+ * a week per call, from the terms already written: the backfill that runs
+ * after 00231 and the server deploy, before 00237 moves the read onto the
+ * rollups. Resolves to the number of calls; throws when one fails, so the
+ * backfill can be run again.
+ */
+export async function refreshMentionTermsHistory(brandId, { pauseMs = 0 } = {}) {
+ const firstDay = await termsDayBound(brandId, true);
+ if (!firstDay) return 0;
+ const lastDay = await termsDayBound(brandId, false);
+
+ const chunks = dayChunks(firstDay, lastDay, MENTION_TERMS_ROLLUP_CHUNK_DAYS);
+ for (const [from, to] of chunks) {
+ const ok = await refreshMentionTermsDaily(brandId, from, to);
+ if (!ok) throw new Error(`mention terms rollup refresh failed for ${brandId} ${from}..${to}`);
+ if (pauseMs > 0) await new Promise((resolve) => setTimeout(resolve, pauseMs));
+ }
+ return chunks.length;
+}
+
+/** Days per terms rollup call: a week of the largest brand's terms, counted. */
+export const MENTION_TERMS_ROLLUP_CHUNK_DAYS = 7;
+
/**
* Days per history refresh call. Shorter than the citation rollups' two
* weeks: the terms (00161) read each answer's text, a few milliseconds per
diff --git a/server/src/lib/mentions-rollups.test.js b/server/src/lib/mentions-rollups.test.js
index dacb485a1..9b13fe142 100644
--- a/server/src/lib/mentions-rollups.test.js
+++ b/server/src/lib/mentions-rollups.test.js
@@ -8,13 +8,18 @@ vi.mock('../config/supabase.js', () => ({
default: { rpc: (...a) => rpc(...a), from: (...a) => from(...a) },
}));
-import { refreshMentionHistory, refreshMentionsDaily } from './mentions-rollups.js';
+import {
+ refreshMentionHistory,
+ refreshMentionTermsDaily,
+ refreshMentionTermsHistory,
+ refreshMentionsDaily,
+} from './mentions-rollups.js';
-/** A prompt_results bound query: first call ascending (first day), then descending. */
-function resultBounds(first, last) {
+/** A day-bound query on `expected`: first call ascending (first day), then descending. */
+function bounds(expected, first, last) {
const days = [first, last];
from.mockImplementation((table) => {
- if (table !== 'prompt_results') throw new Error(`unexpected table ${table}`);
+ if (table !== expected) throw new Error(`unexpected table ${table}`);
const day = days.shift();
const q = {
select: () => q,
@@ -26,6 +31,7 @@ function resultBounds(first, last) {
return q;
});
}
+const resultBounds = (first, last) => bounds('prompt_results', first, last);
beforeEach(() => {
rpc.mockReset();
@@ -58,6 +64,29 @@ describe('refreshMentionsDaily', () => {
});
});
+describe('refreshMentionTermsDaily (00231)', () => {
+ it('rebuilds the Perception rollups a week at a time', async () => {
+ rpc.mockResolvedValue({ error: null });
+ await expect(refreshMentionTermsDaily('brand-1', '2026-10-01', '2026-10-16')).resolves.toBe(
+ true,
+ );
+ const args = (from, to) => ({ p_brand_id: 'brand-1', p_day_from: from, p_day_to: to });
+ expect(rpc.mock.calls).toEqual([
+ ['refresh_mention_terms_daily', args('2026-10-01', '2026-10-07')],
+ ['refresh_mention_terms_daily', args('2026-10-08', '2026-10-14')],
+ ['refresh_mention_terms_daily', args('2026-10-15', '2026-10-16')],
+ ]);
+ });
+
+ it('stops at a failed week and says so, without throwing', async () => {
+ rpc.mockResolvedValueOnce({ error: { message: 'timeout' } });
+ await expect(refreshMentionTermsDaily('brand-1', '2026-10-01', '2026-10-16')).resolves.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');
@@ -91,3 +120,31 @@ describe('refreshMentionHistory', () => {
);
});
});
+
+describe('refreshMentionTermsHistory (00231 backfill)', () => {
+ it("rebuilds the rollups over the brand's terms history, a week at a time", async () => {
+ bounds('mentions_answer_terms', '2026-10-01', '2026-10-16');
+ rpc.mockResolvedValue({ error: null });
+
+ await expect(refreshMentionTermsHistory('brand-1')).resolves.toBe(3);
+ expect(rpc.mock.calls.map(([fn, args]) => [fn, args.p_day_from, args.p_day_to])).toEqual([
+ ['refresh_mention_terms_daily', '2026-10-01', '2026-10-07'],
+ ['refresh_mention_terms_daily', '2026-10-08', '2026-10-14'],
+ ['refresh_mention_terms_daily', '2026-10-15', '2026-10-16'],
+ ]);
+ });
+
+ it('skips a brand with no terms', async () => {
+ bounds('mentions_answer_terms', null, null);
+ await expect(refreshMentionTermsHistory('brand-1')).resolves.toBe(0);
+ expect(rpc).not.toHaveBeenCalled();
+ });
+
+ it('stops at a failed week so the backfill can be run again', async () => {
+ bounds('mentions_answer_terms', '2026-10-01', '2026-10-16');
+ rpc.mockResolvedValueOnce({ error: null }).mockResolvedValueOnce({ error: { message: 'x' } });
+ await expect(refreshMentionTermsHistory('brand-1')).rejects.toThrow(
+ 'mention terms rollup refresh failed for brand-1 2026-10-08..2026-10-14',
+ );
+ });
+});
diff --git a/server/src/scripts/backfill-mention-terms-daily.js b/server/src/scripts/backfill-mention-terms-daily.js
new file mode 100644
index 000000000..0442b37ad
--- /dev/null
+++ b/server/src/scripts/backfill-mention-terms-daily.js
@@ -0,0 +1,57 @@
+/**
+ * Backfill the Mentions Perception rollups (00231) from the answers' terms
+ * already written (00161).
+ *
+ * Run: `node src/scripts/backfill-mention-terms-daily.js`
+ *
+ * Order on a deploy: 00231, then the server, then this, then 00237 (the read
+ * that moves onto the rollups and doesn't fall back to the terms).
+ *
+ * Options via env:
+ * - MENTION_TERMS_BACKFILL_PAUSE milliseconds between refresh calls
+ * (default 250)
+ * - MENTION_TERMS_BACKFILL_BRAND limit the run to one brand id
+ *
+ * Covers every brand with terms. Idempotent and restartable:
+ * `refresh_mention_terms_daily` is delete + insert per day range, a week per
+ * call (MENTION_TERMS_ROLLUP_CHUNK_DAYS, about 5–8 s on the largest brand),
+ * with a pause between calls because this shares the instance with live
+ * dashboards. No answer text is read.
+ */
+
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { refreshMentionTermsHistory } 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;
+
+async function main() {
+ const query = supabaseAdmin.from('brands').select('id');
+ const { data: brands, error } = ONLY_BRAND ? await query.eq('id', ONLY_BRAND) : await query;
+ if (error) throw new Error(error.message);
+
+ let done = 0;
+ let failed = 0;
+ for (const brand of brands ?? []) {
+ try {
+ const chunks = await refreshMentionTermsHistory(brand.id, { pauseMs: PAUSE_MS });
+ done++;
+ console.log(
+ chunks === 0
+ ? `[${done}/${brands.length}] ${brand.id} — no terms, skipped`
+ : `[${done}/${brands.length}] ${brand.id} — ${chunks} week(s)`,
+ );
+ } catch (err) {
+ failed++;
+ console.error(`FAILED ${brand.id}: ${err.message}`);
+ }
+ }
+ console.log(`Backfill complete: ${done} brand(s), ${failed} failure(s).`);
+ if (failed > 0) process.exitCode = 1;
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/supabase/migrations/00231_mentions_perception_rollups.sql b/supabase/migrations/00231_mentions_perception_rollups.sql
new file mode 100644
index 000000000..00050fbdc
--- /dev/null
+++ b/supabase/migrations/00231_mentions_perception_rollups.sql
@@ -0,0 +1,257 @@
+-- ============================================================================
+-- 00231: daily rollups for the Perception tab (Mentions & Sentiment, MS-09)
+-- ============================================================================
+-- mentions_perception (00161) read every answer's terms for the window and
+-- the window before it, unnested per call: 30 days read 60 days of
+-- mentions_answer_terms. On production the Perception tab's 30 and 90 days
+-- failed on every try at the authenticated 8 s timeout (2026-10-21, the
+-- Ansvisor brand; ~10 s cold at 30 days on the largest brand in #1124's
+-- review). The terms are now counted once a day, when they are written. This
+-- migration adds the rollups and keeps them current; 00237 moves the read
+-- onto them once they are filled:
+--
+-- * mentions_entities_daily: per brand, UTC day, platform and region, the
+-- answers naming each entity ('brand' or a competitor's id), and how many
+-- of those name the brand too. Exact: the tab's mention counts, its top
+-- competitors and its co-mentions come from here.
+-- * mentions_terms_daily: per brand, day, platform, region and entity, the
+-- answers each term is next to. 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 the entities on
+-- the same terms, so a competitor's count of a term another entity uses a
+-- lot must not be cut short (a cap per entity left those cells 25–60%
+-- short on the largest brand). A rarer term's count can still come out
+-- short on the days it missed every entity's 200, the price of a bounded
+-- table (keeping every term would be 3.7× the rows).
+-- * One row per key on both (unique, nulls not distinct), as 00192 gave the
+-- Mentions rollups: the advisory lock alone kept a day from being counted
+-- twice. The terms' key leads with the entity, so the read takes only the
+-- entities the tab shows (5 of the largest brand's 19).
+-- * refresh_mention_terms_daily(brand, from, to) rebuilds a day range from
+-- mentions_answer_terms. refresh_mention_terms (00161) calls it after
+-- writing the same days' terms, in the same transaction; the server's
+-- deleted-prompt rebuild calls it for the days a deleted prompt leaves
+-- (its terms rows went with its answers). Service-role only.
+--
+-- The history is not filled here: on production it would hold a lock on
+-- brands (the tables reference it) for minutes, past the statement timeout.
+-- Apply in this order:
+-- 1. this migration;
+-- 2. the server (its deleted-prompt rebuild calls refresh_mention_terms_daily);
+-- 3. `node src/scripts/backfill-mention-terms-daily.js` (server), which
+-- rebuilds each brand's history a week per call;
+-- 4. 00237, the read.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+create table if not exists public.mentions_entities_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ platform text not null,
+ region text,
+ -- 'brand', or the competitor's id.
+ entity text not null,
+ -- Answers naming it.
+ answers integer not null,
+ -- Of those, answers naming the brand too.
+ with_brand integer not null
+);
+
+create unique index if not exists mentions_entities_daily_key
+ on public.mentions_entities_daily (brand_id, day, platform, region, entity)
+ nulls not distinct;
+
+create table if not exists public.mentions_terms_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ platform text not null,
+ region text,
+ entity text not null,
+ term text not null,
+ -- Answers whose sentences naming the entity hold the term.
+ answers integer not null
+);
+
+-- The entity first: the read joins the shown entities to it.
+create unique index if not exists mentions_terms_daily_key
+ on public.mentions_terms_daily (brand_id, entity, day, platform, region, term)
+ nulls not distinct;
+
+-- Read through mentions_perception (security definer) only.
+alter table public.mentions_entities_daily enable row level security;
+alter table public.mentions_terms_daily enable row level security;
+
+comment on table public.mentions_entities_daily is
+ 'Mentions Perception (00231): per brand, UTC day, platform, region and entity, the answers naming it and those naming the brand too. Rebuilt from mentions_answer_terms by refresh_mention_terms_daily.';
+comment on table public.mentions_terms_daily is
+ 'Mentions Perception (00231): per brand, UTC day, platform, region and entity, the answers next to each term among any entity''s 200 most frequent that day, platform and region. Rebuilt from mentions_answer_terms by refresh_mention_terms_daily.';
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+
+create or replace function public.refresh_mention_terms_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ -- One rebuild per brand at a time: a run's refresh and the deleted-prompt
+ -- rebuild can cover the same days. The lock releases at commit.
+ perform pg_advisory_xact_lock(
+ hashtextextended('refresh_mention_terms_daily:' || p_brand_id::text, 0));
+
+ -- The terms' key leads with the entity, so their rows go by the entities
+ -- those days name (the same rows the entities' come from), before those.
+ delete from public.mentions_terms_daily
+ where brand_id = p_brand_id
+ and entity in (
+ select distinct e.entity
+ from public.mentions_entities_daily e
+ where e.brand_id = p_brand_id and e.day between p_day_from and p_day_to)
+ and day between p_day_from and p_day_to;
+ delete from public.mentions_entities_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.mentions_entities_daily (
+ brand_id, day, platform, region, entity, answers, with_brand)
+ select p_brand_id, x.day, x.platform, x.region, x.entity,
+ count(*), count(*) filter (where x.with_brand)
+ from (
+ select (t.created_at at time zone 'utc')::date as day, t.platform, t.region, t.entity,
+ bool_or(t.entity = 'brand') over (partition by t.result_id) as with_brand
+ from public.mentions_answer_terms t
+ where t.brand_id = p_brand_id
+ and t.created_at >= v_from
+ and t.created_at < v_to
+ ) x
+ group by x.day, x.platform, x.region, x.entity;
+
+ with c as materialized (
+ select (t.created_at at time zone 'utc')::date as day, t.platform, t.region, t.entity,
+ term, count(*)::integer as answers
+ from public.mentions_answer_terms t
+ cross join lateral unnest(t.terms) as term
+ where t.brand_id = p_brand_id
+ and t.created_at >= v_from
+ and t.created_at < v_to
+ group by 1, 2, 3, 4, 5
+ ),
+ -- The terms among any entity's 200 most frequent of a day, platform and
+ -- region, kept for every entity there. coalesce rather than "is not
+ -- distinct from", so the join below can hash.
+ keep as (
+ select distinct r.day, r.platform, coalesce(r.region, '') as region_key, r.term
+ from (
+ select c.day, c.platform, c.region, c.term,
+ row_number() over (
+ partition by c.day, c.platform, c.region, c.entity
+ order by c.answers desc, c.term) as rn
+ from c
+ ) r
+ where r.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;
+end;
+$$;
+
+revoke execute on function public.refresh_mention_terms_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- 00161's terms refresh, unchanged but for the rollups at its end.
+
+create or replace function public.refresh_mention_terms(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ -- The range's bounds as instants, so the answers are found by range.
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ -- One refresh per brand at a time, as refresh_mentions_daily (00192): a
+ -- run's refresh and the nightly sweep can cover the same days, and the
+ -- second insert would fail on the (result_id, entity) key. The lock
+ -- releases at commit.
+ perform pg_advisory_xact_lock(
+ hashtextextended('refresh_mention_terms:' || p_brand_id::text, 0));
+
+ delete from public.mentions_answer_terms
+ where brand_id = p_brand_id and created_at >= v_from and created_at < v_to;
+
+ -- The terms next to each entity an answer names, matched by the same names
+ -- tracking counts: the brand's name and domains, each competitor's name
+ -- and domain.
+ with brand_names as (
+ select array_remove(array[b.name] || coalesce(
+ (select array_agg(bd.domain) from public.brand_domains bd where bd.brand_id = b.id),
+ '{}'), null) as names
+ from public.brands b
+ where b.id = p_brand_id
+ ),
+ competitor_names as (
+ select c.id::text as entity, array_remove(array[c.name, nullif(c.domain, '')], null) as names
+ from public.competitors c
+ where c.brand_id = p_brand_id
+ ),
+ name_words as (
+ select coalesce(array_agg(distinct w), '{}') as words
+ from (
+ select regexp_split_to_table(lower(n), '[^[:alnum:]-]+') as w
+ from (
+ select unnest(names) as n from brand_names
+ union all
+ select unnest(names) from competitor_names
+ ) all_names
+ ) split
+ where w <> ''
+ )
+ insert into public.mentions_answer_terms (
+ brand_id, result_id, created_at, prompt_id, platform, region, entity, terms)
+ select
+ p_brand_id, pr.id, pr.created_at, pr.prompt_id, pr.platform, pr.region, e.entity,
+ public.mention_terms(
+ pr.response,
+ e.names,
+ (select words from name_words) || regexp_split_to_array(lower(p.text), '[^[:alnum:]-]+'))
+ from public.prompt_results pr
+ join public.prompts p on p.id = pr.prompt_id
+ cross join lateral (
+ select 'brand'::text as entity, (select names from brand_names) as names
+ where pr.mention_count > 0
+ union all
+ select cn.entity, cn.names
+ from competitor_names cn
+ where exists (
+ select 1
+ from jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value->>'competitor_id' = cn.entity
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0)
+ ) e
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to;
+
+ -- The Perception tab's daily rollups of the same days (00231), in the
+ -- same transaction, so they never lag the terms.
+ perform public.refresh_mention_terms_daily(p_brand_id, p_day_from, p_day_to);
+end;
+$$;
+
+revoke execute on function public.refresh_mention_terms(uuid, date, date)
+ from public, anon, authenticated;
diff --git a/supabase/migrations/00237_mentions_perception_read_rollups.sql b/supabase/migrations/00237_mentions_perception_read_rollups.sql
new file mode 100644
index 000000000..6a033498f
--- /dev/null
+++ b/supabase/migrations/00237_mentions_perception_read_rollups.sql
@@ -0,0 +1,271 @@
+-- ============================================================================
+-- 00237: the Perception tab reads the daily rollups (Mentions & Sentiment, MS-09)
+-- ============================================================================
+-- 00161's read, the same jsonb and the same rules. For whole UTC days (two
+-- days or more) without a topic or a search, the rollups 00231 adds stand in
+-- for the answers' terms; under two days, or filtered to some prompts, it
+-- reads the answers' terms as before.
+--
+-- Apply it after 00231, the server and
+-- `node src/scripts/backfill-mention-terms-daily.js` (server): this read
+-- doesn't fall back to the answers' terms, so a day not yet in the rollups
+-- would show as empty. Timed on production (as owner, rolled back): 30 days
+-- 0.95 s and 90 days 1.36 s, against 6.2–16.3 s for 00161's read.
+
+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'
+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
+ 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;
+
+ 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 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;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index cc09bd2ec..dbfbac046 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -33627,6 +33627,267 @@ grant execute on function public.content_start_prompts(uuid, integer, integer) t
comment on function public.content_start_prompts(uuid, integer, integer) is
'Content Editor New content (CE-003): the brand''s active prompts, each marked seen when an answer in the last p_days UTC days named the brand or cited its pages (insights_prompt_daily); not seen first, by text, up to p_limit, with the count of seen ones. Security definer, planned with its arguments; null when the caller is not a member of the brand''s organization.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00231_mentions_perception_rollups.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00231: daily rollups for the Perception tab (Mentions & Sentiment, MS-09)
+-- ============================================================================
+-- mentions_perception (00161) read every answer's terms for the window and
+-- the window before it, unnested per call: 30 days read 60 days of
+-- mentions_answer_terms. On production the Perception tab's 30 and 90 days
+-- failed on every try at the authenticated 8 s timeout (2026-10-21, the
+-- Ansvisor brand; ~10 s cold at 30 days on the largest brand in #1124's
+-- review). The terms are now counted once a day, when they are written. This
+-- migration adds the rollups and keeps them current; 00237 moves the read
+-- onto them once they are filled:
+--
+-- * mentions_entities_daily: per brand, UTC day, platform and region, the
+-- answers naming each entity ('brand' or a competitor's id), and how many
+-- of those name the brand too. Exact: the tab's mention counts, its top
+-- competitors and its co-mentions come from here.
+-- * mentions_terms_daily: per brand, day, platform, region and entity, the
+-- answers each term is next to. 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 the entities on
+-- the same terms, so a competitor's count of a term another entity uses a
+-- lot must not be cut short (a cap per entity left those cells 25–60%
+-- short on the largest brand). A rarer term's count can still come out
+-- short on the days it missed every entity's 200, the price of a bounded
+-- table (keeping every term would be 3.7× the rows).
+-- * One row per key on both (unique, nulls not distinct), as 00192 gave the
+-- Mentions rollups: the advisory lock alone kept a day from being counted
+-- twice. The terms' key leads with the entity, so the read takes only the
+-- entities the tab shows (5 of the largest brand's 19).
+-- * refresh_mention_terms_daily(brand, from, to) rebuilds a day range from
+-- mentions_answer_terms. refresh_mention_terms (00161) calls it after
+-- writing the same days' terms, in the same transaction; the server's
+-- deleted-prompt rebuild calls it for the days a deleted prompt leaves
+-- (its terms rows went with its answers). Service-role only.
+--
+-- The history is not filled here: on production it would hold a lock on
+-- brands (the tables reference it) for minutes, past the statement timeout.
+-- Apply in this order:
+-- 1. this migration;
+-- 2. the server (its deleted-prompt rebuild calls refresh_mention_terms_daily);
+-- 3. `node src/scripts/backfill-mention-terms-daily.js` (server), which
+-- rebuilds each brand's history a week per call;
+-- 4. 00237, the read.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+create table if not exists public.mentions_entities_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ platform text not null,
+ region text,
+ -- 'brand', or the competitor's id.
+ entity text not null,
+ -- Answers naming it.
+ answers integer not null,
+ -- Of those, answers naming the brand too.
+ with_brand integer not null
+);
+
+create unique index if not exists mentions_entities_daily_key
+ on public.mentions_entities_daily (brand_id, day, platform, region, entity)
+ nulls not distinct;
+
+create table if not exists public.mentions_terms_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ platform text not null,
+ region text,
+ entity text not null,
+ term text not null,
+ -- Answers whose sentences naming the entity hold the term.
+ answers integer not null
+);
+
+-- The entity first: the read joins the shown entities to it.
+create unique index if not exists mentions_terms_daily_key
+ on public.mentions_terms_daily (brand_id, entity, day, platform, region, term)
+ nulls not distinct;
+
+-- Read through mentions_perception (security definer) only.
+alter table public.mentions_entities_daily enable row level security;
+alter table public.mentions_terms_daily enable row level security;
+
+comment on table public.mentions_entities_daily is
+ 'Mentions Perception (00231): per brand, UTC day, platform, region and entity, the answers naming it and those naming the brand too. Rebuilt from mentions_answer_terms by refresh_mention_terms_daily.';
+comment on table public.mentions_terms_daily is
+ 'Mentions Perception (00231): per brand, UTC day, platform, region and entity, the answers next to each term among any entity''s 200 most frequent that day, platform and region. Rebuilt from mentions_answer_terms by refresh_mention_terms_daily.';
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+
+create or replace function public.refresh_mention_terms_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ -- One rebuild per brand at a time: a run's refresh and the deleted-prompt
+ -- rebuild can cover the same days. The lock releases at commit.
+ perform pg_advisory_xact_lock(
+ hashtextextended('refresh_mention_terms_daily:' || p_brand_id::text, 0));
+
+ -- The terms' key leads with the entity, so their rows go by the entities
+ -- those days name (the same rows the entities' come from), before those.
+ delete from public.mentions_terms_daily
+ where brand_id = p_brand_id
+ and entity in (
+ select distinct e.entity
+ from public.mentions_entities_daily e
+ where e.brand_id = p_brand_id and e.day between p_day_from and p_day_to)
+ and day between p_day_from and p_day_to;
+ delete from public.mentions_entities_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.mentions_entities_daily (
+ brand_id, day, platform, region, entity, answers, with_brand)
+ select p_brand_id, x.day, x.platform, x.region, x.entity,
+ count(*), count(*) filter (where x.with_brand)
+ from (
+ select (t.created_at at time zone 'utc')::date as day, t.platform, t.region, t.entity,
+ bool_or(t.entity = 'brand') over (partition by t.result_id) as with_brand
+ from public.mentions_answer_terms t
+ where t.brand_id = p_brand_id
+ and t.created_at >= v_from
+ and t.created_at < v_to
+ ) x
+ group by x.day, x.platform, x.region, x.entity;
+
+ with c as materialized (
+ select (t.created_at at time zone 'utc')::date as day, t.platform, t.region, t.entity,
+ term, count(*)::integer as answers
+ from public.mentions_answer_terms t
+ cross join lateral unnest(t.terms) as term
+ where t.brand_id = p_brand_id
+ and t.created_at >= v_from
+ and t.created_at < v_to
+ group by 1, 2, 3, 4, 5
+ ),
+ -- The terms among any entity's 200 most frequent of a day, platform and
+ -- region, kept for every entity there. coalesce rather than "is not
+ -- distinct from", so the join below can hash.
+ keep as (
+ select distinct r.day, r.platform, coalesce(r.region, '') as region_key, r.term
+ from (
+ select c.day, c.platform, c.region, c.term,
+ row_number() over (
+ partition by c.day, c.platform, c.region, c.entity
+ order by c.answers desc, c.term) as rn
+ from c
+ ) r
+ where r.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;
+end;
+$$;
+
+revoke execute on function public.refresh_mention_terms_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- 00161's terms refresh, unchanged but for the rollups at its end.
+
+create or replace function public.refresh_mention_terms(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ -- The range's bounds as instants, so the answers are found by range.
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ -- One refresh per brand at a time, as refresh_mentions_daily (00192): a
+ -- run's refresh and the nightly sweep can cover the same days, and the
+ -- second insert would fail on the (result_id, entity) key. The lock
+ -- releases at commit.
+ perform pg_advisory_xact_lock(
+ hashtextextended('refresh_mention_terms:' || p_brand_id::text, 0));
+
+ delete from public.mentions_answer_terms
+ where brand_id = p_brand_id and created_at >= v_from and created_at < v_to;
+
+ -- The terms next to each entity an answer names, matched by the same names
+ -- tracking counts: the brand's name and domains, each competitor's name
+ -- and domain.
+ with brand_names as (
+ select array_remove(array[b.name] || coalesce(
+ (select array_agg(bd.domain) from public.brand_domains bd where bd.brand_id = b.id),
+ '{}'), null) as names
+ from public.brands b
+ where b.id = p_brand_id
+ ),
+ competitor_names as (
+ select c.id::text as entity, array_remove(array[c.name, nullif(c.domain, '')], null) as names
+ from public.competitors c
+ where c.brand_id = p_brand_id
+ ),
+ name_words as (
+ select coalesce(array_agg(distinct w), '{}') as words
+ from (
+ select regexp_split_to_table(lower(n), '[^[:alnum:]-]+') as w
+ from (
+ select unnest(names) as n from brand_names
+ union all
+ select unnest(names) from competitor_names
+ ) all_names
+ ) split
+ where w <> ''
+ )
+ insert into public.mentions_answer_terms (
+ brand_id, result_id, created_at, prompt_id, platform, region, entity, terms)
+ select
+ p_brand_id, pr.id, pr.created_at, pr.prompt_id, pr.platform, pr.region, e.entity,
+ public.mention_terms(
+ pr.response,
+ e.names,
+ (select words from name_words) || regexp_split_to_array(lower(p.text), '[^[:alnum:]-]+'))
+ from public.prompt_results pr
+ join public.prompts p on p.id = pr.prompt_id
+ cross join lateral (
+ select 'brand'::text as entity, (select names from brand_names) as names
+ where pr.mention_count > 0
+ union all
+ select cn.entity, cn.names
+ from competitor_names cn
+ where exists (
+ select 1
+ from jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where cm.value->>'competitor_id' = cn.entity
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0)
+ ) e
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to;
+
+ -- The Perception tab's daily rollups of the same days (00231), in the
+ -- same transaction, so they never lag the terms.
+ perform public.refresh_mention_terms_daily(p_brand_id, p_day_from, p_day_to);
+end;
+$$;
+
+revoke execute on function public.refresh_mention_terms(uuid, date, date)
+ from public, anon, authenticated;
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00232_prompt_results_metrics_cover.sql
-- ─────────────────────────────────────────────────────────────────────────
@@ -34205,3 +34466,278 @@ grant execute on function public.health_probe(uuid, uuid, text, integer) to serv
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00237_mentions_perception_read_rollups.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00237: the Perception tab reads the daily rollups (Mentions & Sentiment, MS-09)
+-- ============================================================================
+-- 00161's read, the same jsonb and the same rules. For whole UTC days (two
+-- days or more) without a topic or a search, the rollups 00231 adds stand in
+-- for the answers' terms; under two days, or filtered to some prompts, it
+-- reads the answers' terms as before.
+--
+-- Apply it after 00231, the server and
+-- `node src/scripts/backfill-mention-terms-daily.js` (server): this read
+-- doesn't fall back to the answers' terms, so a day not yet in the rollups
+-- would show as empty. Timed on production (as owner, rolled back): 30 days
+-- 0.95 s and 90 days 1.36 s, against 6.2–16.3 s for 00161's read.
+
+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'
+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
+ 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;
+
+ 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 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;
+
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 36b23a92a..bb3838327 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -2934,6 +2934,82 @@ export type Database = {
},
]
}
+ mentions_entities_daily: {
+ Row: {
+ answers: number
+ brand_id: string
+ day: string
+ entity: string
+ platform: string
+ region: string | null
+ with_brand: number
+ }
+ Insert: {
+ answers: number
+ brand_id: string
+ day: string
+ entity: string
+ platform: string
+ region?: string | null
+ with_brand: number
+ }
+ Update: {
+ answers?: number
+ brand_id?: string
+ day?: string
+ entity?: string
+ platform?: string
+ region?: string | null
+ with_brand?: number
+ }
+ Relationships: [
+ {
+ foreignKeyName: "mentions_entities_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ mentions_terms_daily: {
+ Row: {
+ answers: number
+ brand_id: string
+ day: string
+ entity: string
+ platform: string
+ region: string | null
+ term: string
+ }
+ Insert: {
+ answers: number
+ brand_id: string
+ day: string
+ entity: string
+ platform: string
+ region?: string | null
+ term: string
+ }
+ Update: {
+ answers?: number
+ brand_id?: string
+ day?: string
+ entity?: string
+ platform?: string
+ region?: string | null
+ term?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "mentions_terms_daily_brand_id_fkey"
+ columns: ["brand_id"]
+ isOneToOne: false
+ referencedRelation: "brands"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
sentiment_overrides: {
Row: {
brand_id: string